1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974
|
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/nearby_sharing/nearby_sharing_service_impl.h"
#include <array>
#include <utility>
#include "ash/public/cpp/new_window_delegate.h"
#include "ash/public/cpp/session/session_controller.h"
#include "base/barrier_closure.h"
#include "base/containers/contains.h"
#include "base/files/file.h"
#include "base/functional/bind.h"
#include "base/hash/hash.h"
#include "base/logging.h"
#include "base/metrics/histogram_functions.h"
#include "base/notimplemented.h"
#include "base/numerics/checked_math.h"
#include "base/rand_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/system/sys_info.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/thread_pool.h"
#include "base/time/time.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/download/download_prefs.h"
#include "chrome/browser/nearby_sharing/certificates/common.h"
#include "chrome/browser/nearby_sharing/certificates/nearby_share_certificate_manager_impl.h"
#include "chrome/browser/nearby_sharing/certificates/nearby_share_encrypted_metadata_key.h"
#include "chrome/browser/nearby_sharing/client/nearby_share_client_impl.h"
#include "chrome/browser/nearby_sharing/common/nearby_share_features.h"
#include "chrome/browser/nearby_sharing/common/nearby_share_prefs.h"
#include "chrome/browser/nearby_sharing/constants.h"
#include "chrome/browser/nearby_sharing/contacts/nearby_share_contact_manager_impl.h"
#include "chrome/browser/nearby_sharing/fast_initiation/fast_initiation_advertiser.h"
#include "chrome/browser/nearby_sharing/fast_initiation/fast_initiation_scanner.h"
#include "chrome/browser/nearby_sharing/local_device_data/nearby_share_local_device_data_manager_impl.h"
#include "chrome/browser/nearby_sharing/nearby_share_error.h"
#include "chrome/browser/nearby_sharing/nearby_share_feature_status.h"
#include "chrome/browser/nearby_sharing/nearby_share_metrics.h"
#include "chrome/browser/nearby_sharing/nearby_share_transfer_profiler.h"
#include "chrome/browser/nearby_sharing/paired_key_verification_runner.h"
#include "chrome/browser/nearby_sharing/share_target.h"
#include "chrome/browser/nearby_sharing/transfer_metadata.h"
#include "chrome/browser/nearby_sharing/transfer_metadata_builder.h"
#include "chrome/browser/nearby_sharing/wifi_network_configuration/wifi_network_configuration_handler.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/scoped_tabbed_browser_displayer.h"
#include "chrome/services/sharing/public/cpp/advertisement.h"
#include "chrome/services/sharing/public/cpp/conversions.h"
#include "chromeos/ash/components/nearby/common/connections_manager/nearby_connections_manager.h"
#include "chromeos/ash/services/nearby/public/mojom/nearby_connections_types.mojom.h"
#include "chromeos/ash/services/nearby/public/mojom/nearby_decoder.mojom.h"
#include "chromeos/ash/services/nearby/public/mojom/nearby_share_target_types.mojom.h"
#include "chromeos/constants/chromeos_features.h"
#include "components/cross_device/logging/logging.h"
#include "components/cross_device/nearby/nearby_features.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/storage_partition.h"
#include "crypto/random.h"
#include "device/bluetooth/bluetooth_adapter_factory.h"
#include "device/bluetooth/bluetooth_low_energy_scan_filter.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "url/gurl.h"
// static
constexpr int
NearbySharingServiceImpl::kMaxRecentNearbyProcessUnexpectedShutdownCount;
namespace {
using NearbyProcessShutdownReason =
ash::nearby::NearbyProcessManager::NearbyProcessShutdownReason;
constexpr base::TimeDelta kBackgroundAdvertisementRotationDelayMin =
base::Minutes(12);
// 870 seconds represents 14:30 minutes
constexpr base::TimeDelta kBackgroundAdvertisementRotationDelayMax =
base::Seconds(870);
constexpr base::TimeDelta kInvalidateSurfaceStateDelayAfterTransferDone =
base::Milliseconds(3000);
constexpr base::TimeDelta kProcessShutdownPendingTimerDelay = base::Seconds(15);
constexpr base::TimeDelta kProcessNetworkChangeTimerDelay = base::Seconds(1);
// Cooldown period after a successful incoming share before we allow the "Device
// nearby is sharing" notification to appear again.
constexpr base::TimeDelta kFastInitiationScannerCooldown = base::Seconds(8);
// The maximum number of certificate downloads that can be performed during a
// discovery session.
constexpr size_t kMaxCertificateDownloadsDuringDiscovery = 3u;
// The time between certificate downloads during a discovery session. The
// download is only attempted if there are discovered, contact-based
// advertisements that cannot decrypt any currently stored public certificates.
constexpr base::TimeDelta kCertificateDownloadDuringDiscoveryPeriod =
base::Seconds(10);
// Used to hash a token into a 4 digit string.
constexpr int kHashModulo = 9973;
constexpr int kHashBaseMultiplier = 31;
// Length of the window during which we count the amount of times the nearby
// process stops unexpectedly.
constexpr base::TimeDelta kClearNearbyProcessUnexpectedShutdownCountDelay =
base::Minutes(1);
// The length of window during which we display visibility reminder
// notification to users. The real length set for timer should be calculated
// by (180 - kNearbySharingVisibilityReminderLastShownTimePrefName set in
// nearby_share_prefs).
constexpr base::TimeDelta kNearbyVisibilityReminderTimerDelay = base::Days(180);
// Whether or not WifiLan is supported for advertising (mDNS). Support as
// a bandwidth upgrade medium is behind a feature flag. Currently unsupported.
constexpr bool kIsWifiLanAdvertisingSupported = false;
std::string ReceiveSurfaceStateToString(
NearbySharingService::ReceiveSurfaceState state) {
switch (state) {
case NearbySharingService::ReceiveSurfaceState::kForeground:
return "FOREGROUND";
case NearbySharingService::ReceiveSurfaceState::kBackground:
return "BACKGROUND";
case NearbySharingService::ReceiveSurfaceState::kUnknown:
return "UNKNOWN";
}
}
std::string SendSurfaceStateToString(
NearbySharingService::SendSurfaceState state) {
switch (state) {
case NearbySharingService::SendSurfaceState::kForeground:
return "FOREGROUND";
case NearbySharingService::SendSurfaceState::kBackground:
return "BACKGROUND";
case NearbySharingService::SendSurfaceState::kUnknown:
return "UNKNOWN";
}
}
std::string PowerLevelToString(NearbyConnectionsManager::PowerLevel level) {
switch (level) {
case NearbyConnectionsManager::PowerLevel::kLowPower:
return "LOW_POWER";
case NearbyConnectionsManager::PowerLevel::kMediumPower:
return "MEDIUM_POWER";
case NearbyConnectionsManager::PowerLevel::kHighPower:
return "HIGH_POWER";
case NearbyConnectionsManager::PowerLevel::kUnknown:
return "UNKNOWN";
}
}
std::optional<std::vector<uint8_t>> GetBluetoothMacAddressFromCertificate(
const NearbyShareDecryptedPublicCertificate& certificate) {
if (!certificate.unencrypted_metadata().has_bluetooth_mac_address()) {
RecordNearbyShareError(
NearbyShareError::kPublicCertificateHasNoBluetoothMacAddress);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": Public certificate "
<< base::HexEncode(certificate.id()) << " did not contain "
<< "a Bluetooth mac address.";
return std::nullopt;
}
std::string mac_address =
certificate.unencrypted_metadata().bluetooth_mac_address();
if (mac_address.size() != 6) {
RecordNearbyShareError(
NearbyShareError::kPublicCertificateHasInvalidBluetoothMacAddress);
CD_LOG(ERROR, Feature::NS)
<< __func__ << ": Invalid bluetooth mac address: '" << mac_address
<< "'";
return std::nullopt;
}
return std::vector<uint8_t>(mac_address.begin(), mac_address.end());
}
std::optional<std::string> GetDeviceName(
const sharing::mojom::AdvertisementPtr& advertisement,
const std::optional<NearbyShareDecryptedPublicCertificate>& certificate) {
DCHECK(advertisement);
// Device name is always included when visible to everyone.
if (advertisement->device_name) {
return *(advertisement->device_name);
}
// For contacts only advertisements, we can't do anything without the
// certificate.
if (!certificate || !certificate->unencrypted_metadata().has_device_name()) {
return std::nullopt;
}
return certificate->unencrypted_metadata().device_name();
}
// Return the most stable device identifier with the following priority:
// 1. Hash of Bluetooth MAC address.
// 2. Certificate ID.
// 3. Endpoint ID.
std::string GetDeviceId(
const std::string& endpoint_id,
const std::optional<NearbyShareDecryptedPublicCertificate>& certificate) {
if (!certificate) {
return endpoint_id;
}
std::optional<std::vector<uint8_t>> mac_address =
GetBluetoothMacAddressFromCertificate(*certificate);
if (mac_address) {
return base::NumberToString(base::FastHash(base::span(*mac_address)));
}
if (!certificate->id().empty()) {
return std::string(certificate->id().begin(), certificate->id().end());
}
return endpoint_id;
}
std::optional<std::string> ToFourDigitString(
const std::optional<std::vector<uint8_t>>& bytes) {
if (!bytes) {
return std::nullopt;
}
int hash = 0;
int multiplier = 1;
for (uint8_t byte : *bytes) {
// Java bytes are signed two's complement so cast to use the correct sign.
hash = (hash + static_cast<int8_t>(byte) * multiplier) % kHashModulo;
multiplier = (multiplier * kHashBaseMultiplier) % kHashModulo;
}
return base::StringPrintf("%04d", std::abs(hash));
}
bool IsOutOfStorage(const base::FilePath& file_path,
int64_t storage_required,
std::optional<int64_t> free_disk_space_for_testing) {
int64_t free_space = free_disk_space_for_testing.value_or(
base::SysInfo::AmountOfFreeDiskSpace(file_path));
return free_space < storage_required;
}
int64_t GeneratePayloadId() {
int64_t payload_id = 0;
crypto::RandBytes(base::byte_span_from_ref(payload_id));
return payload_id;
}
// Wraps a call to OnTransferUpdate() to filter any updates after receiving a
// final status.
class TransferUpdateDecorator : public TransferUpdateCallback {
public:
using Callback = base::RepeatingCallback<void(const ShareTarget&,
const TransferMetadata&)>;
explicit TransferUpdateDecorator(Callback callback)
: callback_(std::move(callback)) {}
TransferUpdateDecorator(const TransferUpdateDecorator&) = delete;
TransferUpdateDecorator& operator=(const TransferUpdateDecorator&) = delete;
~TransferUpdateDecorator() override = default;
void OnTransferUpdate(const ShareTarget& share_target,
const TransferMetadata& transfer_metadata) override {
if (got_final_status_) {
// If we already got a final status, we can ignore any subsequent final
// statuses caused by race conditions.
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Transfer update decorator swallowed "
<< "status update because a final status was already received: "
<< share_target.id << ": "
<< TransferMetadata::StatusToString(transfer_metadata.status());
return;
}
got_final_status_ = transfer_metadata.is_final_status();
callback_.Run(share_target, transfer_metadata);
}
private:
bool got_final_status_ = false;
Callback callback_;
};
bool isVisibleForAdvertising(nearby_share::mojom::Visibility visibility) {
return visibility == nearby_share::mojom::Visibility::kAllContacts ||
visibility == nearby_share::mojom::Visibility::kSelectedContacts ||
visibility == nearby_share::mojom::Visibility::kYourDevices;
}
NearbyShareEncryptedMetadataKey AdvertisementToKey(
const sharing::mojom::AdvertisementPtr& advertisement) {
return NearbyShareEncryptedMetadataKey(
base::span<const uint8_t, kNearbyShareNumBytesMetadataEncryptionKeySalt>(
advertisement->salt),
base::span<const uint8_t, kNearbyShareNumBytesMetadataEncryptionKey>(
advertisement->encrypted_metadata_key));
}
} // namespace
NearbySharingServiceImpl::NearbySharingServiceImpl(
user_manager::User& user,
Profile* profile,
NotificationDisplayService* notification_display_service,
std::unique_ptr<NearbyConnectionsManager> nearby_connections_manager,
ash::nearby::NearbyProcessManager* process_manager,
std::unique_ptr<PowerClient> power_client,
std::unique_ptr<WifiNetworkConfigurationHandler> wifi_network_handler)
: profile_(profile),
prefs_(profile_->GetPrefs()),
nearby_connections_manager_(std::move(nearby_connections_manager)),
process_manager_(process_manager),
power_client_(std::move(power_client)),
wifi_network_handler_(std::move(wifi_network_handler)),
http_client_factory_(std::make_unique<NearbyShareClientFactoryImpl>(
IdentityManagerFactory::GetForProfile(profile),
profile->GetURLLoaderFactory(),
&nearby_share_http_notifier_)),
local_device_data_manager_(
NearbyShareLocalDeviceDataManagerImpl::Factory::Create(
user,
http_client_factory_.get())),
contact_manager_(NearbyShareContactManagerImpl::Factory::Create(
profile_->GetProfileUserName(),
prefs_,
http_client_factory_.get(),
local_device_data_manager_.get())),
certificate_manager_(NearbyShareCertificateManagerImpl::Factory::Create(
profile_->GetProfileUserName(),
profile->GetPath(),
prefs_,
local_device_data_manager_.get(),
contact_manager_.get(),
profile->GetDefaultStoragePartition()->GetProtoDatabaseProvider(),
http_client_factory_.get())),
transfer_profiler_(std::make_unique<NearbyShareTransferProfiler>()),
logger_(std::make_unique<NearbyShareLogger>()),
settings_(prefs_, local_device_data_manager_.get()),
feature_usage_metrics_(prefs_),
on_network_changed_delay_timer_(
FROM_HERE,
kProcessNetworkChangeTimerDelay,
base::BindRepeating(&NearbySharingServiceImpl::
StopAdvertisingAndInvalidateSurfaceState,
base::Unretained(this))),
visibility_reminder_timer_delay_(kNearbyVisibilityReminderTimerDelay),
discovery_metric_logger_(
std::make_unique<nearby::share::metrics::DiscoveryMetricLogger>()),
throughput_metric_logger_(
std::make_unique<nearby::share::metrics::ThroughputMetricLogger>()),
attachment_metric_logger_(
std::make_unique<nearby::share::metrics::AttachmentMetricLogger>()),
neaby_share_metric_logger_(
std::make_unique<nearby::share::metrics::NearbyShareMetricLogger>()) {
DCHECK(profile_);
DCHECK(nearby_connections_manager_);
DCHECK(power_client_);
nearby_connections_manager_->RegisterBandwidthUpgradeListener(
weak_ptr_factory_.GetWeakPtr());
fast_initiation_scanning_metrics_ =
std::make_unique<FastInitiationScannerFeatureUsageMetrics>(prefs_);
RecordNearbyShareEnabledMetric(GetNearbyShareEnabledState(prefs_));
auto* session_controller = ash::SessionController::Get();
if (session_controller) {
is_screen_locked_ = session_controller->IsScreenLocked();
session_controller->AddObserver(this);
}
power_client_->AddObserver(this);
certificate_manager_->AddObserver(this);
settings_.AddSettingsObserver(settings_receiver_.BindNewPipeAndPassRemote());
// Register logging observers.
AddObserver(logger_.get());
AddObserver(discovery_metric_logger_.get());
AddObserver(throughput_metric_logger_.get());
AddObserver(attachment_metric_logger_.get());
AddObserver(neaby_share_metric_logger_.get());
GetBluetoothAdapter();
nearby_notification_manager_ = std::make_unique<NearbyNotificationManager>(
notification_display_service, this, prefs_, profile_);
net::NetworkChangeNotifier::AddNetworkChangeObserver(this);
if (settings_.GetEnabled()) {
local_device_data_manager_->Start();
contact_manager_->Start();
certificate_manager_->Start();
BindToNearbyProcess();
}
UpdateVisibilityReminderTimer(/*reset_timestamp=*/false);
user_visibility_ = settings_.GetVisibility();
}
NearbySharingServiceImpl::~NearbySharingServiceImpl() {
// Make sure the service has been shut down properly before.
DCHECK(!nearby_notification_manager_);
if (bluetooth_adapter_) {
DCHECK(!bluetooth_adapter_->HasObserver(this));
}
// Unregister observers.
RemoveObserver(logger_.get());
RemoveObserver(discovery_metric_logger_.get());
RemoveObserver(throughput_metric_logger_.get());
RemoveObserver(attachment_metric_logger_.get());
RemoveObserver(neaby_share_metric_logger_.get());
}
void NearbySharingServiceImpl::Shutdown() {
// Before we clean up, lets give observers a heads up we are shutting down.
for (auto& observer : observers_) {
observer.OnShutdown();
}
observers_.Clear();
StopAdvertising();
StopFastInitiationScanning();
StopFastInitiationAdvertising();
StopScanning();
nearby_connections_manager_->Shutdown();
// Destroy NearbyNotificationManager as its profile has been shut down.
nearby_notification_manager_.reset();
// On shutdown, we want to do all the same clean up as happens when
// the nearby process stops.
CleanupAfterNearbyProcessStopped();
power_client_->RemoveObserver(this);
certificate_manager_->RemoveObserver(this);
// TODO(crbug/1147652): The call to update the advertising interval is
// removed to prevent a Bluez crash. We need to either reduce the global
// advertising interval asynchronously and wait for the result or use the
// updated API referenced in the bug which allows setting a per-advertisement
// interval.
if (bluetooth_adapter_) {
bluetooth_adapter_->RemoveObserver(this);
bluetooth_adapter_.reset();
}
auto* session_controller = ash::SessionController::Get();
if (session_controller) {
session_controller->RemoveObserver(this);
}
foreground_receive_callbacks_.Clear();
background_receive_callbacks_.Clear();
settings_receiver_.reset();
if (settings_.GetEnabled()) {
local_device_data_manager_->Stop();
contact_manager_->Stop();
certificate_manager_->Stop();
}
// |profile_| has now been shut down so we shouldn't use it anymore.
profile_ = nullptr;
net::NetworkChangeNotifier::RemoveNetworkChangeObserver(this);
on_network_changed_delay_timer_.Stop();
fast_initiation_scanner_cooldown_timer_.Stop();
}
void NearbySharingServiceImpl::AddObserver(
NearbySharingService::Observer* observer) {
observers_.AddObserver(observer);
}
void NearbySharingServiceImpl::RemoveObserver(
NearbySharingService::Observer* observer) {
observers_.RemoveObserver(observer);
}
bool NearbySharingServiceImpl::HasObserver(
NearbySharingService::Observer* observer) {
return observers_.HasObserver(observer);
}
NearbySharingService::StatusCodes NearbySharingServiceImpl::RegisterSendSurface(
TransferUpdateCallback* transfer_callback,
ShareTargetDiscoveredCallback* discovery_callback,
SendSurfaceState state) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(transfer_callback);
DCHECK(discovery_callback);
DCHECK_NE(state, SendSurfaceState::kUnknown);
if (foreground_send_transfer_callbacks_.HasObserver(transfer_callback) ||
background_send_transfer_callbacks_.HasObserver(transfer_callback)) {
RecordNearbyShareError(
NearbyShareError::kRegisterSendSurfaceAlreadyRegistered);
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": RegisterSendSurface failed. Already registered for a "
"different state.";
return StatusCodes::kError;
}
if (state == SendSurfaceState::kForeground) {
// Only check this error case for foreground senders
if (!HasAvailableDiscoveryMediums()) {
RecordNearbyShareError(
NearbyShareError::kRegisterSendSurfaceNoAvailableConnectionMedium);
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": No available connection medium.";
return StatusCodes::kNoAvailableConnectionMedium;
}
foreground_send_transfer_callbacks_.AddObserver(transfer_callback);
foreground_send_discovery_callbacks_.AddObserver(discovery_callback);
} else {
background_send_transfer_callbacks_.AddObserver(transfer_callback);
background_send_discovery_callbacks_.AddObserver(discovery_callback);
}
if (is_receiving_files_) {
UnregisterSendSurface(transfer_callback, discovery_callback);
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Ignore registering (and unregistering if registered) send "
"surface because we're currently receiving files.";
return StatusCodes::kTransferAlreadyInProgress;
}
// If the share sheet to be registered is a foreground surface, let it catch
// up with most recent transfer metadata immediately.
if (state == SendSurfaceState::kForeground && last_outgoing_metadata_) {
// When a new share sheet is registered, we want to immediately show the
// in-progress bar.
discovery_callback->OnShareTargetDiscovered(last_outgoing_metadata_->first);
transfer_callback->OnTransferUpdate(last_outgoing_metadata_->first,
last_outgoing_metadata_->second);
}
// Sync down data from Nearby server when the sending flow starts, making our
// best effort to have fresh contact and certificate data. There is no need to
// wait for these calls to finish. The periodic server requests will typically
// be sufficient, but we don't want the user to be blocked for hours waiting
// for a periodic sync.
if (state == SendSurfaceState::kForeground && !last_outgoing_metadata_) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Downloading local device data, contacts, and certificates from "
<< "Nearby server at start of sending flow.";
local_device_data_manager_->DownloadDeviceData();
contact_manager_->DownloadContacts();
certificate_manager_->DownloadPublicCertificates();
}
// Let newly registered send surface catch up with discovered share targets
// from current scanning session.
for (const std::pair<std::string, ShareTarget>& item :
outgoing_share_target_map_) {
discovery_callback->OnShareTargetDiscovered(item.second);
}
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": A SendSurface has been registered for state: "
<< SendSurfaceStateToString(state);
InvalidateSendSurfaceState();
return StatusCodes::kOk;
}
NearbySharingService::StatusCodes
NearbySharingServiceImpl::UnregisterSendSurface(
TransferUpdateCallback* transfer_callback,
ShareTargetDiscoveredCallback* discovery_callback) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(transfer_callback);
DCHECK(discovery_callback);
if (!foreground_send_transfer_callbacks_.HasObserver(transfer_callback) &&
!background_send_transfer_callbacks_.HasObserver(transfer_callback)) {
RecordNearbyShareError(
NearbyShareError::kUnregisterSendSurfaceUnknownTransferUpdateCallback);
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": unregisterSendSurface failed. Unknown TransferUpdateCallback";
return StatusCodes::kError;
}
if (!foreground_send_transfer_callbacks_.empty() && last_outgoing_metadata_ &&
last_outgoing_metadata_->second.is_final_status()) {
// We already saw the final status in the foreground
// Nullify it so the next time the user opens sharing, it starts the UI from
// the beginning
last_outgoing_metadata_.reset();
}
SendSurfaceState state = SendSurfaceState::kUnknown;
if (foreground_send_transfer_callbacks_.HasObserver(transfer_callback)) {
foreground_send_transfer_callbacks_.RemoveObserver(transfer_callback);
foreground_send_discovery_callbacks_.RemoveObserver(discovery_callback);
state = SendSurfaceState::kForeground;
} else {
background_send_transfer_callbacks_.RemoveObserver(transfer_callback);
background_send_discovery_callbacks_.RemoveObserver(discovery_callback);
state = SendSurfaceState::kBackground;
}
// Displays the most recent payload status processed by foreground surfaces on
// background surfaces.
if (foreground_send_transfer_callbacks_.empty() && last_outgoing_metadata_) {
for (TransferUpdateCallback& background_transfer_callback :
background_send_transfer_callbacks_) {
background_transfer_callback.OnTransferUpdate(
last_outgoing_metadata_->first, last_outgoing_metadata_->second);
}
}
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": A SendSurface has been unregistered: "
<< SendSurfaceStateToString(state);
InvalidateSurfaceState();
return StatusCodes::kOk;
}
NearbySharingService::StatusCodes
NearbySharingServiceImpl::RegisterReceiveSurface(
TransferUpdateCallback* transfer_callback,
ReceiveSurfaceState state) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(transfer_callback);
DCHECK_NE(state, ReceiveSurfaceState::kUnknown);
// Only check these errors cases for foreground receivers.
if (state == ReceiveSurfaceState::kForeground) {
if (is_scanning_ || is_transferring_) {
UnregisterReceiveSurface(transfer_callback);
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Ignore registering (and unregistering if registered) receive "
"surface, because we're currently sending or receiving files.";
return StatusCodes::kTransferAlreadyInProgress;
}
if (!HasAvailableAdvertisingMediums()) {
RecordNearbyShareError(
NearbyShareError::kRegisterReceiveSurfaceNoAvailableConnectionMedium);
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": No available connection medium.";
return StatusCodes::kNoAvailableConnectionMedium;
}
}
// We specifically allow re-registring with out error so it is clear to caller
// that the transfer_callback is currently registered.
if (GetReceiveCallbacksFromState(state).HasObserver(transfer_callback)) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": transfer callback already registered, ignoring";
return StatusCodes::kOk;
} else if (foreground_receive_callbacks_.HasObserver(transfer_callback) ||
background_receive_callbacks_.HasObserver(transfer_callback)) {
RecordNearbyShareError(
NearbyShareError::
kRegisterReceiveSurfaceTransferCallbackAlreadyRegisteredDifferentState);
CD_LOG(ERROR, Feature::NS)
<< __func__
<< ": transfer callback already registered but for a different state.";
return StatusCodes::kError;
}
// If the receive surface to be registered is a foreground surface, let it
// catch up with most recent transfer metadata immediately.
if (state == ReceiveSurfaceState::kForeground && last_incoming_metadata_) {
transfer_callback->OnTransferUpdate(last_incoming_metadata_->first,
last_incoming_metadata_->second);
}
GetReceiveCallbacksFromState(state).AddObserver(transfer_callback);
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": A ReceiveSurface(" << ReceiveSurfaceStateToString(state)
<< ") has been registered";
// TODO(crbug.com/40753805): Remove these logs. They are only needed to help
// debug crbug.com/1186559.
if (state == ReceiveSurfaceState::kForeground) {
if (!IsBluetoothPresent()) {
CD_LOG(ERROR, Feature::NS) << __func__ << ": Bluetooth is not present.";
} else if (!IsBluetoothPowered()) {
CD_LOG(WARNING, Feature::NS) << __func__ << ": Bluetooth is not powered.";
} else {
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": This device's MAC address is: "
<< bluetooth_adapter_->GetAddress();
}
}
InvalidateReceiveSurfaceState();
return StatusCodes::kOk;
}
NearbySharingService::StatusCodes
NearbySharingServiceImpl::UnregisterReceiveSurface(
TransferUpdateCallback* transfer_callback) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(transfer_callback);
bool is_foreground =
foreground_receive_callbacks_.HasObserver(transfer_callback);
bool is_background =
background_receive_callbacks_.HasObserver(transfer_callback);
if (!is_foreground && !is_background) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Unknown transfer callback was un-registered, ignoring.";
// We intentionally allow this be successful so the caller can be sure
// they are not registered anymore.
return StatusCodes::kOk;
}
if (!foreground_receive_callbacks_.empty() && last_incoming_metadata_ &&
last_incoming_metadata_->second.is_final_status()) {
// We already saw the final status in the foreground.
// Nullify it so the next time the user opens sharing, it starts the UI from
// the beginning
last_incoming_metadata_.reset();
}
if (is_foreground) {
foreground_receive_callbacks_.RemoveObserver(transfer_callback);
} else {
background_receive_callbacks_.RemoveObserver(transfer_callback);
}
// Displays the most recent payload status processed by foreground surfaces on
// background surface.
if (foreground_receive_callbacks_.empty() && last_incoming_metadata_) {
for (TransferUpdateCallback& background_callback :
background_receive_callbacks_) {
background_callback.OnTransferUpdate(last_incoming_metadata_->first,
last_incoming_metadata_->second);
}
}
CD_LOG(VERBOSE, Feature::NS) << __func__ << ": A ReceiveSurface("
<< (is_foreground ? "foreground" : "background")
<< ") has been unregistered";
InvalidateSurfaceState();
return StatusCodes::kOk;
}
NearbySharingService::StatusCodes
NearbySharingServiceImpl::ClearForegroundReceiveSurfaces() {
std::vector<TransferUpdateCallback*> fg_receivers;
for (auto& callback : foreground_receive_callbacks_) {
fg_receivers.push_back(&callback);
}
StatusCodes status = StatusCodes::kOk;
for (TransferUpdateCallback* callback : fg_receivers) {
if (UnregisterReceiveSurface(callback) != StatusCodes::kOk) {
status = StatusCodes::kError;
}
}
return status;
}
bool NearbySharingServiceImpl::IsInHighVisibility() const {
if (chromeos::features::IsQuickShareV2Enabled()) {
return prefs_->GetBoolean(prefs::kNearbySharingInHighVisibilityPrefName);
}
return in_high_visibility_;
}
bool NearbySharingServiceImpl::IsTransferring() const {
return is_transferring_;
}
bool NearbySharingServiceImpl::IsReceivingFile() const {
return is_receiving_files_;
}
bool NearbySharingServiceImpl::IsSendingFile() const {
return is_sending_files_;
}
bool NearbySharingServiceImpl::IsScanning() const {
return is_scanning_;
}
bool NearbySharingServiceImpl::IsConnecting() const {
return is_connecting_;
}
NearbySharingService::StatusCodes NearbySharingServiceImpl::SendAttachments(
const ShareTarget& share_target,
std::vector<std::unique_ptr<Attachment>> attachments) {
if (!is_scanning_) {
RecordNearbyShareError(NearbyShareError::kSendAttachmentsNotScanning);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": Failed to send attachments. Not scanning.";
return StatusCodes::kError;
}
// |is_scanning_| means at least one send transfer callback.
DCHECK(!foreground_send_transfer_callbacks_.empty() ||
!background_send_transfer_callbacks_.empty());
// |is_scanning_| and |is_transferring_| are mutually exclusive.
DCHECK(!is_transferring_);
ShareTargetInfo* info = GetShareTargetInfo(share_target);
if (!info || !info->endpoint_id()) {
// TODO(crbug.com/1119276): Support scanning for unknown share targets.
RecordNearbyShareError(
NearbyShareError::kSendAttachmentsUnknownShareTarget);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": Failed to send attachments. Unknown ShareTarget.";
return StatusCodes::kError;
}
ShareTarget share_target_copy = share_target;
for (std::unique_ptr<Attachment>& attachment : attachments) {
DCHECK(attachment);
attachment->MoveToShareTarget(share_target_copy);
}
if (!share_target_copy.has_attachments()) {
RecordNearbyShareError(NearbyShareError::kSendAttachmentsNoAttachments);
CD_LOG(WARNING, Feature::NS) << __func__ << ": No attachments to send.";
return StatusCodes::kError;
}
// For sending advertisement from scanner, the request advertisement should
// always be visible to everyone.
std::optional<std::vector<uint8_t>> endpoint_info =
CreateEndpointInfo(local_device_data_manager_->GetDeviceName());
if (!endpoint_info) {
RecordNearbyShareError(
NearbyShareError::kSendAttachmentsCouldNotCreateLocalEndpointInfo);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": Could not create local endpoint info.";
return StatusCodes::kError;
}
info->set_transfer_update_callback(std::make_unique<TransferUpdateDecorator>(
base::BindRepeating(&NearbySharingServiceImpl::OnOutgoingTransferUpdate,
weak_ptr_factory_.GetWeakPtr())));
send_attachments_timestamp_ = base::TimeTicks::Now();
OnTransferStarted(/*is_incoming=*/false);
CHECK(info->endpoint_id().has_value());
transfer_profiler_->OnShareTargetSelected(info->endpoint_id().value());
for (auto& observer : observers_) {
observer.OnShareTargetSelected(share_target);
}
is_connecting_ = true;
InvalidateSendSurfaceState();
// Send process initialized successfully, from now on status updated will be
// sent out via OnOutgoingTransferUpdate().
info->transfer_update_callback()->OnTransferUpdate(
share_target_copy, TransferMetadataBuilder()
.set_status(TransferMetadata::Status::kConnecting)
.build());
CreatePayloads(std::move(share_target_copy),
base::BindOnce(&NearbySharingServiceImpl::OnCreatePayloads,
weak_ptr_factory_.GetWeakPtr(),
std::move(*endpoint_info)));
return StatusCodes::kOk;
}
void NearbySharingServiceImpl::Accept(
const ShareTarget& share_target,
StatusCodesCallback status_codes_callback) {
ShareTargetInfo* info = GetShareTargetInfo(share_target);
if (!info || !info->connection()) {
RecordNearbyShareError(NearbyShareError::kAcceptUnknownShareTarget);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": Accept invoked for unknown share target";
std::move(status_codes_callback).Run(StatusCodes::kOutOfOrderApiCall);
return;
}
std::optional<std::pair<ShareTarget, TransferMetadata>> metadata =
share_target.is_incoming ? last_incoming_metadata_
: last_outgoing_metadata_;
if (!metadata || metadata->second.status() !=
TransferMetadata::Status::kAwaitingLocalConfirmation) {
RecordNearbyShareError(
NearbyShareError::kAcceptNotAwaitingLocalConfirmation);
std::move(status_codes_callback).Run(StatusCodes::kOutOfOrderApiCall);
return;
}
is_waiting_to_record_accept_to_transfer_start_metric_ =
share_target.is_incoming;
for (auto& observer : observers_) {
observer.OnTransferAccepted(share_target);
}
// This should probably always evaluate to true, since a sender will
// never accept a transfer.
DCHECK(share_target.is_incoming);
if (share_target.is_incoming) {
incoming_share_accepted_timestamp_ = base::TimeTicks::Now();
CHECK(info->endpoint_id().has_value());
transfer_profiler_->OnTransferAccepted(info->endpoint_id().value());
ReceivePayloads(share_target, std::move(status_codes_callback));
return;
}
std::move(status_codes_callback).Run(SendPayloads(share_target));
}
void NearbySharingServiceImpl::Reject(
const ShareTarget& share_target,
StatusCodesCallback status_codes_callback) {
ShareTargetInfo* info = GetShareTargetInfo(share_target);
if (!info || !info->connection()) {
RecordNearbyShareError(NearbyShareError::kRejectUnknownShareTarget);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": Reject invoked for unknown share target";
std::move(status_codes_callback).Run(StatusCodes::kOutOfOrderApiCall);
return;
}
NearbyConnection* connection = info->connection();
base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&NearbySharingServiceImpl::CloseConnection,
weak_ptr_factory_.GetWeakPtr(), share_target),
kIncomingRejectionDelay);
connection->SetDisconnectionListener(
base::BindOnce(&NearbySharingServiceImpl::UnregisterShareTarget,
weak_ptr_factory_.GetWeakPtr(), share_target));
WriteResponse(*connection, sharing::nearby::ConnectionResponseFrame::REJECT);
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Successfully wrote a rejection response frame";
if (info->transfer_update_callback()) {
info->transfer_update_callback()->OnTransferUpdate(
share_target, TransferMetadataBuilder()
.set_status(TransferMetadata::Status::kRejected)
.build());
}
std::move(status_codes_callback).Run(StatusCodes::kOk);
}
void NearbySharingServiceImpl::Cancel(
const ShareTarget& share_target,
StatusCodesCallback status_codes_callback) {
CD_LOG(INFO, Feature::NS) << __func__ << ": User cancelled transfer";
locally_cancelled_share_target_ids_.insert(share_target.id);
DoCancel(share_target, std::move(status_codes_callback),
/*is_initiator_of_cancellation=*/true);
}
void NearbySharingServiceImpl::DoCancel(
ShareTarget share_target,
StatusCodesCallback status_codes_callback,
bool is_initiator_of_cancellation) {
ShareTargetInfo* info = GetShareTargetInfo(share_target);
if (!info || !info->endpoint_id()) {
RecordNearbyShareError(NearbyShareError::kCancelUnknownShareTarget);
CD_LOG(ERROR, Feature::NS)
<< __func__
<< ": Cancel invoked for unknown share target, returning "
"kOutOfOrderApiCall";
// Make sure to clean up files just in case.
RemoveIncomingPayloads(share_target);
std::move(status_codes_callback).Run(StatusCodes::kOutOfOrderApiCall);
return;
}
// For metrics.
all_cancelled_share_target_ids_.insert(share_target.id);
// Cancel all ongoing payload transfers before invoking the transfer update
// callback. Invoking the transfer update callback first could result in
// payload cleanup before we have a chance to cancel the payload via Nearby
// Connections, and the payload tracker might not receive the expected
// cancellation signals. Also, note that there might not be any ongoing
// payload transfer, for example, if a connection has not been established
// yet.
for (int64_t attachment_id : share_target.GetAttachmentIds()) {
std::optional<int64_t> payload_id = GetAttachmentPayloadId(attachment_id);
if (payload_id) {
nearby_connections_manager_->Cancel(*payload_id);
}
}
// Inform the user that the transfer has been cancelled before disconnecting
// because subsequent disconnections might be interpreted as failure. The
// TransferUpdateDecorator will ignore subsequent statuses in favor of this
// cancelled status. Note that the transfer update callback might have already
// been invoked as a result of the payload cancellations above, but again,
// superfluous status updates are handled gracefully by the
// TransferUpdateDecorator.
if (info->transfer_update_callback()) {
info->transfer_update_callback()->OnTransferUpdate(
share_target, TransferMetadataBuilder()
.set_status(TransferMetadata::Status::kCancelled)
.build());
}
// If a connection exists, close the connection. Note: The initiator of a
// cancellation waits for a short delay before closing the connection,
// allowing for final processing by the other device. Otherwise, disconnect
// from endpoint id directly. Note: A share attempt can be cancelled by the
// user before a connection is fully established, in which case,
// info->connection() will be null.
if (info->connection()) {
if (is_initiator_of_cancellation) {
info->connection()->SetDisconnectionListener(
base::BindOnce(&NearbySharingServiceImpl::UnregisterShareTarget,
weak_ptr_factory_.GetWeakPtr(), share_target));
base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&NearbySharingServiceImpl::CloseConnection,
weak_ptr_factory_.GetWeakPtr(), share_target),
kInitiatorCancelDelay);
WriteCancel(*info->connection());
} else {
info->connection()->Close();
}
} else {
nearby_connections_manager_->Disconnect(*info->endpoint_id());
UnregisterShareTarget(share_target);
}
std::move(status_codes_callback).Run(StatusCodes::kOk);
}
bool NearbySharingServiceImpl::DidLocalUserCancelTransfer(
const ShareTarget& share_target) {
return base::Contains(locally_cancelled_share_target_ids_, share_target.id);
}
void NearbySharingServiceImpl::Open(const ShareTarget& share_target,
StatusCodesCallback status_codes_callback) {
std::move(status_codes_callback).Run(StatusCodes::kOk);
}
void NearbySharingServiceImpl::OpenURL(GURL url) {
DCHECK(profile_);
ash::NewWindowDelegate::GetPrimary()->OpenUrl(
url, ash::NewWindowDelegate::OpenUrlFrom::kUserInteraction,
ash::NewWindowDelegate::Disposition::kNewForegroundTab);
}
void NearbySharingServiceImpl::SetArcTransferCleanupCallback(
base::OnceCallback<void()> callback) {
// In the case where multiple Nearby Share sessions are started, successive
// Nearby Share bubbles shown will prevent the user from sharing while the
// initial bubble is still active. For the successive bubble(s), we want to
// make sure only the original cleanup callback is valid.
// Also in the following case:
// 1. CrOS starts a receive transfer.
// 2. ARC starts a send transfer and |arc_transfer_cleanup_callback_| is set
// erroneously if |is_transferring_| check is missing.
// As multiple transfers cannot occur at the same time, a "Can't Share" error
// will occur. When the transfer in [1] finishes and another ARC Nearby Share
// session starts, the |arc_transfer_cleanup_callback_| can't be set if a
// value is already set to ensure all clean up is performed. Hence, check if
// not |is_transferring_| before setting |arc_transfer_cleanup_callback_|.
if (!is_transferring_ && arc_transfer_cleanup_callback_.is_null()) {
arc_transfer_cleanup_callback_ = std::move(callback);
}
}
NearbyNotificationDelegate* NearbySharingServiceImpl::GetNotificationDelegate(
const std::string& notification_id) {
if (!nearby_notification_manager_) {
return nullptr;
}
return nearby_notification_manager_->GetNotificationDelegate(notification_id);
}
void NearbySharingServiceImpl::RecordFastInitiationNotificationUsage(
bool success) {
fast_initiation_scanning_metrics_->RecordUsage(success);
}
NearbyShareSettings* NearbySharingServiceImpl::GetSettings() {
return &settings_;
}
NearbyShareHttpNotifier* NearbySharingServiceImpl::GetHttpNotifier() {
return &nearby_share_http_notifier_;
}
NearbyShareLocalDeviceDataManager*
NearbySharingServiceImpl::GetLocalDeviceDataManager() {
return local_device_data_manager_.get();
}
NearbyShareContactManager* NearbySharingServiceImpl::GetContactManager() {
return contact_manager_.get();
}
NearbyShareCertificateManager*
NearbySharingServiceImpl::GetCertificateManager() {
return certificate_manager_.get();
}
NearbyNotificationManager* NearbySharingServiceImpl::GetNotificationManager() {
return nearby_notification_manager_.get();
}
void NearbySharingServiceImpl::OnNearbyProcessStopped(
NearbyProcessShutdownReason shutdown_reason) {
DCHECK(process_reference_);
CD_LOG(INFO, Feature::NS)
<< __func__ << ": Shutdown reason: " << shutdown_reason;
CleanupAfterNearbyProcessStopped();
ClearForegroundReceiveSurfaces();
RestartNearbyProcessIfAppropriate(shutdown_reason);
InvalidateSurfaceState();
for (auto& observer : observers_) {
observer.OnNearbyProcessStopped();
}
}
void NearbySharingServiceImpl::CleanupAfterNearbyProcessStopped() {
if (process_reference_) {
process_reference_.reset();
}
SetInHighVisibility(false);
endpoint_discovery_weak_ptr_factory_.InvalidateWeakPtrs();
endpoint_discovery_events_ = base::queue<base::OnceClosure>();
ClearOutgoingShareTargetInfoMap();
incoming_share_target_info_map_.clear();
discovered_advertisements_to_retry_map_.clear();
foreground_send_transfer_callbacks_.Clear();
background_send_transfer_callbacks_.Clear();
foreground_send_discovery_callbacks_.Clear();
background_send_discovery_callbacks_.Clear();
last_incoming_metadata_.reset();
last_outgoing_metadata_.reset();
attachment_info_map_.clear();
locally_cancelled_share_target_ids_.clear();
mutual_acceptance_timeout_alarm_.Cancel();
disconnection_timeout_alarms_.clear();
is_scanning_ = false;
is_transferring_ = false;
is_receiving_files_ = false;
is_sending_files_ = false;
is_connecting_ = false;
advertising_power_level_ = NearbyConnectionsManager::PowerLevel::kUnknown;
process_shutdown_pending_timer_.Stop();
certificate_download_during_discovery_timer_.Stop();
rotate_background_advertisement_timer_.Stop();
if (arc_transfer_cleanup_callback_) {
// Cleanup send transfer resources where the user started ARC Nearby Share
// but did not complete (i.e. cancel, abort, utility process stopped, etc.)
// prior to shutdown.
std::move(arc_transfer_cleanup_callback_).Run();
}
}
void NearbySharingServiceImpl::RestartNearbyProcessIfAppropriate(
NearbyProcessShutdownReason shutdown_reason) {
if (!ShouldRestartNearbyProcess(shutdown_reason)) {
return;
}
CD_LOG(INFO, Feature::NS)
<< __func__ << ": Attempting to restart nearby process after shutdown: "
<< shutdown_reason;
BindToNearbyProcess();
// Track the number of process shutdowns that occur in a fixed time window.
recent_nearby_process_unexpected_shutdown_count_++;
if (!clear_recent_nearby_process_shutdown_count_timer_.IsRunning()) {
clear_recent_nearby_process_shutdown_count_timer_.Start(
FROM_HERE, kClearNearbyProcessUnexpectedShutdownCountDelay,
base::BindOnce(&NearbySharingServiceImpl::
ClearRecentNearbyProcessUnexpectedShutdownCount,
weak_ptr_factory_.GetWeakPtr()));
}
}
bool NearbySharingServiceImpl::ShouldRestartNearbyProcess(
NearbyProcessShutdownReason shutdown_reason) {
// Ensure Nearby Share is still enabled.
if (!settings_.GetEnabled()) {
CD_LOG(INFO, Feature::NS)
<< __func__
<< ": Choosing to not restart process because Nearby Share is "
"disabled.";
return false;
}
// Check if the current shutdown reason is one which we want to restart after.
switch (shutdown_reason) {
case NearbyProcessShutdownReason::kNormal:
return false;
case NearbyProcessShutdownReason::kCrash:
case NearbyProcessShutdownReason::kConnectionsMojoPipeDisconnection:
case NearbyProcessShutdownReason::kPresenceMojoPipeDisconnection:
case NearbyProcessShutdownReason::kDecoderMojoPipeDisconnection:
break;
}
// Check if the process shutdown count is above the allowed threshold.
if (recent_nearby_process_unexpected_shutdown_count_ >
NearbySharingServiceImpl::
kMaxRecentNearbyProcessUnexpectedShutdownCount) {
RecordNearbyShareError(NearbyShareError::kMaxNearbyProcessRestart);
CD_LOG(WARNING, Feature::NS)
<< __func__
<< ": Choosing to not restart process because the recent stop "
"count has exceeded the threshold.";
return false;
}
return true;
}
void NearbySharingServiceImpl::
ClearRecentNearbyProcessUnexpectedShutdownCount() {
recent_nearby_process_unexpected_shutdown_count_ = 0;
}
void NearbySharingServiceImpl::BindToNearbyProcess() {
if (process_reference_ || !settings_.GetEnabled()) {
RecordNearbyShareError(
NearbyShareError::kBindToNearbyProcessReferenceExistsOrDisabled);
return;
}
process_reference_ = process_manager_->GetNearbyProcessReference(
base::BindOnce(&NearbySharingServiceImpl::OnNearbyProcessStopped,
base::Unretained(this)));
if (!process_reference_) {
RecordNearbyShareError(
NearbyShareError::kBindToNearbyProcessFailedToGetReference);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": Failed to get a reference to the nearby process.";
}
}
sharing::mojom::NearbySharingDecoder*
NearbySharingServiceImpl::GetNearbySharingDecoder() {
BindToNearbyProcess();
if (!process_reference_) {
return nullptr;
}
sharing::mojom::NearbySharingDecoder* decoder =
process_reference_->GetNearbySharingDecoder().get();
if (!decoder) {
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": Failed to get decoder from process reference.";
}
return decoder;
}
void NearbySharingServiceImpl::OnIncomingConnectionAccepted(
const std::string& endpoint_id,
const std::vector<uint8_t>& endpoint_info,
NearbyConnection* connection) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(connection);
DCHECK(process_reference_);
sharing::mojom::NearbySharingDecoder* decoder = GetNearbySharingDecoder();
if (!decoder) {
RecordNearbyShareError(
NearbyShareError::kOnIncomingConnectionAcceptedFailedToGetDecoder);
return;
}
// Sync down data from Nearby server when the receiving flow starts, making
// our best effort to have fresh contact and certificate data. There is no
// need to wait for these calls to finish. The periodic server requests will
// typically be sufficient, but we don't want the user to be blocked for hours
// waiting for a periodic sync.
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Downloading local device data, contacts, and certificates from "
<< "Nearby server at start of receiving flow.";
local_device_data_manager_->DownloadDeviceData();
contact_manager_->DownloadContacts();
certificate_manager_->DownloadPublicCertificates();
ShareTarget placeholder_share_target;
placeholder_share_target.is_incoming = true;
ShareTargetInfo& share_target_info =
GetOrCreateShareTargetInfo(placeholder_share_target, endpoint_id);
share_target_info.set_connection(connection);
connection->SetDisconnectionListener(
base::BindOnce(&NearbySharingServiceImpl::RefreshUIOnDisconnection,
weak_ptr_factory_.GetWeakPtr(), placeholder_share_target));
decoder->DecodeAdvertisement(
endpoint_info,
base::BindOnce(&NearbySharingServiceImpl::OnIncomingAdvertisementDecoded,
weak_ptr_factory_.GetWeakPtr(), endpoint_id,
std::move(placeholder_share_target)));
}
void NearbySharingServiceImpl::OnNetworkChanged(
net::NetworkChangeNotifier::ConnectionType type) {
CD_LOG(VERBOSE, Feature::NS) << __func__ << ": ConnectionType = " << type;
on_network_changed_delay_timer_.Reset();
}
void NearbySharingServiceImpl::FlushMojoForTesting() {
settings_receiver_.FlushForTesting();
}
void NearbySharingServiceImpl::OnEnabledChanged(bool enabled) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
RecordNearbyShareEnabledMetric(GetNearbyShareEnabledState(prefs_));
if (settings_.IsOnboardingComplete()) {
base::UmaHistogramBoolean("Nearby.Share.EnabledStateChanged", enabled);
}
if (enabled) {
CD_LOG(VERBOSE, Feature::NS) << __func__ << ": Nearby sharing enabled!";
local_device_data_manager_->Start();
contact_manager_->Start();
certificate_manager_->Start();
BindToNearbyProcess();
} else {
CD_LOG(VERBOSE, Feature::NS) << __func__ << ": Nearby sharing disabled!";
StopAdvertising();
StopScanning();
nearby_connections_manager_->Shutdown();
local_device_data_manager_->Stop();
contact_manager_->Stop();
certificate_manager_->Stop();
process_reference_.reset();
}
UpdateVisibilityReminderTimer(/*reset_timestamp=*/false);
InvalidateSurfaceState();
}
void NearbySharingServiceImpl::OnFastInitiationNotificationStateChanged(
nearby_share::mojom::FastInitiationNotificationState state) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Fast Initiation Notification state: " << state;
// Runs through a series of checks to determine if background scanning should
// be started or stopped.
InvalidateReceiveSurfaceState();
}
void NearbySharingServiceImpl::OnDeviceNameChanged(
const std::string& device_name) {
CD_LOG(INFO, Feature::NS)
<< __func__ << ": Nearby sharing device name changed";
// TODO(vecore): handle device name change
}
void NearbySharingServiceImpl::OnDataUsageChanged(
nearby_share::mojom::DataUsage data_usage) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
CD_LOG(INFO, Feature::NS)
<< __func__ << ": Nearby sharing data usage changed to " << data_usage;
StopAdvertisingAndInvalidateSurfaceState();
}
void NearbySharingServiceImpl::OnVisibilityChanged(
nearby_share::mojom::Visibility new_visibility) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
CD_LOG(INFO, Feature::NS)
<< __func__ << ": Nearby sharing visibility changed to "
<< new_visibility;
UpdateVisibilityReminderTimer(/*reset_timestamp=*/true);
StopAdvertisingAndInvalidateSurfaceState();
}
void NearbySharingServiceImpl::OnAllowedContactsChanged(
const std::vector<std::string>& allowed_contacts) {
CD_LOG(INFO, Feature::NS)
<< __func__ << ": Nearby sharing visible contacts changed";
// TODO(vecore): handle visible contacts change
}
void NearbySharingServiceImpl::OnPublicCertificatesDownloaded() {
if (!is_scanning_ || discovered_advertisements_to_retry_map_.empty()) {
return;
}
CD_LOG(INFO, Feature::NS)
<< __func__ << ": Public certificates downloaded while scanning. "
<< "Retrying decryption with "
<< discovered_advertisements_to_retry_map_.size()
<< " previously discovered advertisements.";
const auto map_copy = discovered_advertisements_to_retry_map_;
discovered_advertisements_to_retry_map_.clear();
for (const auto& id_info_pair : map_copy) {
OnEndpointDiscovered(id_info_pair.first, id_info_pair.second);
}
}
void NearbySharingServiceImpl::OnPrivateCertificatesChanged() {
// If we are currently advertising, restart advertising using the updated
// private certificates.
if (rotate_background_advertisement_timer_.IsRunning()) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Private certificates changed; rotating background advertisement.";
rotate_background_advertisement_timer_.FireNow();
}
}
void NearbySharingServiceImpl::OnEndpointDiscovered(
const std::string& endpoint_id,
const std::vector<uint8_t>& endpoint_info) {
AddEndpointDiscoveryEvent(
base::BindOnce(&NearbySharingServiceImpl::HandleEndpointDiscovered,
base::Unretained(this), endpoint_id, endpoint_info));
}
void NearbySharingServiceImpl::OnEndpointLost(const std::string& endpoint_id) {
AddEndpointDiscoveryEvent(
base::BindOnce(&NearbySharingServiceImpl::HandleEndpointLost,
base::Unretained(this), endpoint_id));
}
void NearbySharingServiceImpl::OnInitialMedium(const std::string& endpoint_id,
const Medium medium) {
// Our |share_target_map_| is populated in CreateShareTarget. This
// is deterministically called *before* this method when sending,
// and *after* this method when receiving. In other words, we can
// expect to *not* record the initial medium when receiving.
// We determined this acceptable as the initial medium when receiving
// will always be Bluetooth, until other mediums are supported (Wifi LAN
// can be an initial medium when sending due to mDNS discovery.)
if (!share_target_map_.contains(endpoint_id)) {
return;
}
RecordNearbyShareInitialConnectionMedium(medium);
auto share_target = share_target_map_[endpoint_id];
for (auto& observer : observers_) {
observer.OnInitialMedium(share_target, medium);
}
}
void NearbySharingServiceImpl::OnBandwidthUpgrade(
const std::string& endpoint_id,
const Medium medium) {
transfer_profiler_->OnBandwidthUpgrade(endpoint_id, medium);
// This gets triggered when connecting as a receiver.
CHECK(share_target_map_.contains(endpoint_id));
auto share_target = share_target_map_[endpoint_id];
for (auto& observer : observers_) {
observer.OnBandwidthUpgrade(share_target, medium);
}
}
void NearbySharingServiceImpl::OnBandwidthUpgradeV3(
nearby::presence::PresenceDevice remote_device,
const Medium medium) {
// Because `NearbySharingServiceImpl` is currently only consuming V1 APIs from
// `NearbyConnections`, this function is to be left as `NOTIMPLEMENTED()` as
// only Nearby Presence is using V3 APIs.
NOTIMPLEMENTED();
}
void NearbySharingServiceImpl::OnLockStateChanged(bool locked) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Screen lock state changed. (" << locked << ")";
is_screen_locked_ = locked;
// Set visibility to 'Your Devices' if the screen is locked and visibility is
// not Hidden.
nearby_share::mojom::Visibility current_visibility =
settings_.GetVisibility();
if (current_visibility != nearby_share::mojom::Visibility::kNoOne) {
if (locked) {
// Store old visibility setting.
user_visibility_ = current_visibility;
user_allowed_contacts_ = contact_manager_->GetAllowedContacts();
// Set visibility to Your Devices.
settings_.SetVisibility(nearby_share::mojom::Visibility::kYourDevices);
contact_manager_->SetAllowedContacts(std::set<std::string>());
} else {
settings_.SetVisibility(user_visibility_);
contact_manager_->SetAllowedContacts(user_allowed_contacts_);
}
}
InvalidateSurfaceState();
}
void NearbySharingServiceImpl::AdapterPresentChanged(
device::BluetoothAdapter* adapter,
bool present) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Bluetooth present changed: " << present;
InvalidateSurfaceState();
}
void NearbySharingServiceImpl::AdapterPoweredChanged(
device::BluetoothAdapter* adapter,
bool powered) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Bluetooth powered changed: " << powered;
InvalidateSurfaceState();
}
void NearbySharingServiceImpl::
LowEnergyScanSessionHardwareOffloadingStatusChanged(
device::BluetoothAdapter::LowEnergyScanSessionHardwareOffloadingStatus
status) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Bluetooth low energy scan session hardware offloading status : "
<< (status == device::BluetoothAdapter::
LowEnergyScanSessionHardwareOffloadingStatus::kSupported
? "enabled"
: "disabled");
InvalidateSurfaceState();
}
void NearbySharingServiceImpl::SuspendImminent() {
CD_LOG(VERBOSE, Feature::NS) << __func__ << ": Suspend imminent.";
InvalidateSurfaceState();
}
void NearbySharingServiceImpl::SuspendDone() {
CD_LOG(VERBOSE, Feature::NS) << __func__ << ": Suspend done.";
InvalidateSurfaceState();
}
base::ObserverList<TransferUpdateCallback>&
NearbySharingServiceImpl::GetReceiveCallbacksFromState(
ReceiveSurfaceState state) {
switch (state) {
case ReceiveSurfaceState::kForeground:
return foreground_receive_callbacks_;
case ReceiveSurfaceState::kBackground:
return background_receive_callbacks_;
case ReceiveSurfaceState::kUnknown:
NOTREACHED();
}
}
bool NearbySharingServiceImpl::IsVisibleInBackground(
nearby_share::mojom::Visibility visibility) {
return isVisibleForAdvertising(visibility);
}
const std::optional<std::vector<uint8_t>>
NearbySharingServiceImpl::CreateEndpointInfo(
const std::optional<std::string>& device_name) {
std::array<uint8_t, sharing::Advertisement::kSaltSize> salt;
salt = GenerateRandomBytes<sharing::Advertisement::kSaltSize>();
std::array<uint8_t,
sharing::Advertisement::kMetadataEncryptionKeyHashByteSize>
encrypted_key;
encrypted_key = GenerateRandomBytes<
sharing::Advertisement::kMetadataEncryptionKeyHashByteSize>();
nearby_share::mojom::Visibility visibility = settings_.GetVisibility();
if (isVisibleForAdvertising(visibility)) {
std::optional<NearbyShareEncryptedMetadataKey> encrypted_metadata_key =
certificate_manager_->EncryptPrivateCertificateMetadataKey(visibility);
if (encrypted_metadata_key) {
base::span(salt).copy_from(encrypted_metadata_key->salt());
base::span(encrypted_key)
.copy_from(encrypted_metadata_key->encrypted_key());
} else {
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": Failed to encrypt private certificate metadata key "
<< "for advertisement.";
}
}
nearby_share::mojom::ShareTargetType device_type =
nearby_share::mojom::ShareTargetType::kLaptop;
std::unique_ptr<sharing::Advertisement> advertisement =
sharing::Advertisement::NewInstance(salt, encrypted_key, device_type,
device_name);
return advertisement ? std::make_optional(advertisement->ToEndpointInfo())
: std::nullopt;
}
void NearbySharingServiceImpl::GetBluetoothAdapter() {
auto* adapter_factory = device::BluetoothAdapterFactory::Get();
if (!adapter_factory->IsBluetoothSupported()) {
RecordNearbyShareError(NearbyShareError::kGetBluetoothAdapterUnsupported);
return;
}
// Because this will be called from the constructor, GetAdapter() may call
// OnGetBluetoothAdapter() immediately which can cause problems during tests
// since the class is not fully constructed yet.
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(
&device::BluetoothAdapterFactory::GetAdapter,
base::Unretained(adapter_factory),
base::BindOnce(&NearbySharingServiceImpl::OnGetBluetoothAdapter,
weak_ptr_factory_.GetWeakPtr())));
}
void NearbySharingServiceImpl::OnGetBluetoothAdapter(
scoped_refptr<device::BluetoothAdapter> adapter) {
bluetooth_adapter_ = adapter;
bluetooth_adapter_->AddObserver(this);
fast_initiation_scanning_metrics_->SetBluetoothAdapter(adapter);
// TODO(crbug/1147652): The call to update the advertising interval is
// removed to prevent a Bluez crash. We need to either reduce the global
// advertising interval asynchronously and wait for the result or use the
// updated API referenced in the bug which allows setting a per-advertisement
// interval.
// TODO(crbug.com/1132469): This was added to fix an issue where advertising
// was not starting on sign-in. Add a unit test to cover this case.
InvalidateSurfaceState();
}
void NearbySharingServiceImpl::StartFastInitiationAdvertising() {
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Starting fast initiation advertising.";
fast_initiation_advertiser_ =
FastInitiationAdvertiser::Factory::Create(bluetooth_adapter_);
// TODO(crbug/1147652): The call to update the advertising interval is
// removed to prevent a Bluez crash. We need to either reduce the global
// advertising interval asynchronously and wait for the result or use the
// updated API referenced in the bug which allows setting a per-advertisement
// interval.
// TODO(crbug.com/1100686): Determine whether to call StartAdvertising() with
// kNotify or kSilent.
fast_initiation_advertiser_->StartAdvertising(
FastInitiationAdvertiser::FastInitType::kNotify,
base::BindOnce(
&NearbySharingServiceImpl::OnStartFastInitiationAdvertising,
weak_ptr_factory_.GetWeakPtr()),
base::BindOnce(
&NearbySharingServiceImpl::OnStartFastInitiationAdvertisingError,
weak_ptr_factory_.GetWeakPtr()));
}
void NearbySharingServiceImpl::OnStartFastInitiationAdvertising() {
// TODO(hansenmichael): Do not invoke
// |register_send_surface_callback_| until Nearby Connections
// scanning is kicked off.
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Started advertising FastInitiation.";
}
void NearbySharingServiceImpl::OnStartFastInitiationAdvertisingError() {
fast_initiation_advertiser_.reset();
RecordNearbyShareError(
NearbyShareError::kStartFastInitiationAdvertisingFailed);
CD_LOG(ERROR, Feature::NS)
<< __func__ << ": Failed to start FastInitiation advertising.";
}
void NearbySharingServiceImpl::StopFastInitiationAdvertising() {
if (!fast_initiation_advertiser_) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Not advertising FastInitiation, ignoring.";
return;
}
fast_initiation_advertiser_->StopAdvertising(
base::BindOnce(&NearbySharingServiceImpl::OnStopFastInitiationAdvertising,
weak_ptr_factory_.GetWeakPtr()));
}
void NearbySharingServiceImpl::OnStopFastInitiationAdvertising() {
fast_initiation_advertiser_.reset();
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Stopped advertising FastInitiation";
// TODO(crbug/1147652): The call to update the advertising interval is
// removed to prevent a Bluez crash. We need to either reduce the global
// advertising interval asynchronously and wait for the result or use the
// updated API referenced in the bug which allows setting a per-advertisement
// interval.
}
void NearbySharingServiceImpl::AddEndpointDiscoveryEvent(
base::OnceClosure event) {
endpoint_discovery_events_.push(std::move(event));
if (endpoint_discovery_events_.size() == 1u) {
std::move(endpoint_discovery_events_.front()).Run();
}
}
void NearbySharingServiceImpl::HandleEndpointDiscovered(
const std::string& endpoint_id,
const std::vector<uint8_t>& endpoint_info) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": endpoint_id=" << endpoint_id
<< ", endpoint_info=" << base::HexEncode(endpoint_info);
transfer_profiler_->OnEndpointDiscovered(endpoint_id);
if (!is_scanning_) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Ignoring discovered endpoint because we're no longer scanning";
FinishEndpointDiscoveryEvent();
return;
}
sharing::mojom::NearbySharingDecoder* decoder = GetNearbySharingDecoder();
if (!decoder) {
RecordNearbyShareError(
NearbyShareError::HandleEndpointDiscoveredFailedToGetDecoder);
FinishEndpointDiscoveryEvent();
return;
}
decoder->DecodeAdvertisement(
endpoint_info,
base::BindOnce(&NearbySharingServiceImpl::OnOutgoingAdvertisementDecoded,
endpoint_discovery_weak_ptr_factory_.GetWeakPtr(),
endpoint_id, endpoint_info));
}
void NearbySharingServiceImpl::HandleEndpointLost(
const std::string& endpoint_id) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
CD_LOG(VERBOSE, Feature::NS) << __func__ << ": endpoint_id=" << endpoint_id;
transfer_profiler_->OnEndpointLost(endpoint_id);
if (!is_scanning_) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Ignoring lost endpoint because we're no longer scanning";
FinishEndpointDiscoveryEvent();
return;
}
discovered_advertisements_to_retry_map_.erase(endpoint_id);
RemoveOutgoingShareTargetWithEndpointId(endpoint_id);
FinishEndpointDiscoveryEvent();
}
void NearbySharingServiceImpl::FinishEndpointDiscoveryEvent() {
DCHECK(!endpoint_discovery_events_.empty());
DCHECK(endpoint_discovery_events_.front().is_null());
endpoint_discovery_events_.pop();
// Handle the next queued up endpoint discovered/lost event.
if (!endpoint_discovery_events_.empty()) {
DCHECK(!endpoint_discovery_events_.front().is_null());
std::move(endpoint_discovery_events_.front()).Run();
}
}
void NearbySharingServiceImpl::OnOutgoingAdvertisementDecoded(
const std::string& endpoint_id,
const std::vector<uint8_t>& endpoint_info,
sharing::mojom::AdvertisementPtr advertisement) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (!advertisement) {
RecordNearbyShareError(
NearbyShareError::kOutgoingAdvertisementDecodedFailedToParse);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": Failed to parse discovered advertisement.";
FinishEndpointDiscoveryEvent();
return;
}
transfer_profiler_->OnOutgoingEndpointDecoded(endpoint_id);
// Now we will report endpoints met before in NearbyConnectionsManager.
// Check outgoingShareTargetInfoMap first and pass the same shareTarget if we
// found one.
// Looking for the ShareTarget based on endpoint id.
if (outgoing_share_target_map_.find(endpoint_id) !=
outgoing_share_target_map_.end()) {
FinishEndpointDiscoveryEvent();
return;
}
// Once we get the advertisement, the first thing to do is decrypt the
// certificate.
NearbyShareEncryptedMetadataKey encrypted_metadata_key =
AdvertisementToKey(advertisement);
GetCertificateManager()->GetDecryptedPublicCertificate(
std::move(encrypted_metadata_key),
base::BindOnce(&NearbySharingServiceImpl::OnOutgoingDecryptedCertificate,
endpoint_discovery_weak_ptr_factory_.GetWeakPtr(),
endpoint_id, endpoint_info, std::move(advertisement)));
}
void NearbySharingServiceImpl::OnOutgoingDecryptedCertificate(
const std::string& endpoint_id,
const std::vector<uint8_t>& endpoint_info,
sharing::mojom::AdvertisementPtr advertisement,
std::optional<NearbyShareDecryptedPublicCertificate> certificate) {
// Check again for this endpoint id, to avoid race conditions.
if (outgoing_share_target_map_.find(endpoint_id) !=
outgoing_share_target_map_.end()) {
FinishEndpointDiscoveryEvent();
return;
}
// The certificate provides the device name, in order to create a ShareTarget
// to represent this remote device.
std::optional<ShareTarget> share_target = CreateShareTarget(
endpoint_id, std::move(advertisement), std::move(certificate),
/*is_incoming=*/false);
if (!share_target) {
RecordNearbyShareError(
NearbyShareError::
kOutgoingDecryptedCertificateFailedToCreateShareTarget);
CD_LOG(INFO, Feature::NS)
<< __func__ << ": Failed to convert discovered advertisement to share "
<< "target. Ignoring endpoint until next certificate download.";
discovered_advertisements_to_retry_map_[endpoint_id] = endpoint_info;
FinishEndpointDiscoveryEvent();
return;
}
// Update the endpoint id for the share target.
CD_LOG(INFO, Feature::NS)
<< __func__
<< ": An endpoint has been discovered, with an advertisement "
"containing a valid share target.";
// Notifies the user that we discovered a device.
for (ShareTargetDiscoveredCallback& discovery_callback :
foreground_send_discovery_callbacks_) {
discovery_callback.OnShareTargetDiscovered(*share_target);
}
for (ShareTargetDiscoveredCallback& discovery_callback :
background_send_discovery_callbacks_) {
discovery_callback.OnShareTargetDiscovered(*share_target);
}
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Reported OnShareTargetDiscovered "
<< (base::Time::Now() - scanning_start_timestamp_);
// TODO(crbug/1108348) CachingManager should cache known and non-external
// share targets.
FinishEndpointDiscoveryEvent();
}
void NearbySharingServiceImpl::ScheduleCertificateDownloadDuringDiscovery(
size_t download_count) {
if (download_count >= kMaxCertificateDownloadsDuringDiscovery) {
return;
}
certificate_download_during_discovery_timer_.Start(
FROM_HERE, kCertificateDownloadDuringDiscoveryPeriod,
base::BindOnce(&NearbySharingServiceImpl::
OnCertificateDownloadDuringDiscoveryTimerFired,
weak_ptr_factory_.GetWeakPtr(), download_count));
}
void NearbySharingServiceImpl::OnCertificateDownloadDuringDiscoveryTimerFired(
size_t download_count) {
if (!is_scanning_) {
return;
}
if (!discovered_advertisements_to_retry_map_.empty()) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Detected "
<< discovered_advertisements_to_retry_map_.size()
<< " discovered advertisements that could not decrypt any "
<< "public certificates. Re-downloading certificates.";
certificate_manager_->DownloadPublicCertificates();
++download_count;
}
ScheduleCertificateDownloadDuringDiscovery(download_count);
}
bool NearbySharingServiceImpl::IsBluetoothPresent() const {
return bluetooth_adapter_.get() && bluetooth_adapter_->IsPresent();
}
bool NearbySharingServiceImpl::IsBluetoothPowered() const {
return IsBluetoothPresent() && bluetooth_adapter_->IsPowered();
}
bool NearbySharingServiceImpl::HasAvailableAdvertisingMediums() {
// Advertising is currently unsupported unless bluetooth is known to be
// enabled. When Wifi LAN advertising (mDNS) is supported, we also need
// to check network conditions.
net::NetworkChangeNotifier::ConnectionType connection_type =
net::NetworkChangeNotifier::GetConnectionType();
bool hasNetworkConnection =
connection_type ==
net::NetworkChangeNotifier::ConnectionType::CONNECTION_WIFI ||
connection_type ==
net::NetworkChangeNotifier::ConnectionType::CONNECTION_ETHERNET;
return IsBluetoothPowered() ||
(hasNetworkConnection && kIsWifiLanAdvertisingSupported);
}
bool NearbySharingServiceImpl::HasAvailableDiscoveryMediums() {
// Discovery is supported over both Bluetooth and Wifi LAN (mDNS),
// so either of those mediums must be enabled. mDNS discovery
// additionally needs a network connection.
net::NetworkChangeNotifier::ConnectionType connection_type =
net::NetworkChangeNotifier::GetConnectionType();
bool hasNetworkConnection =
connection_type ==
net::NetworkChangeNotifier::ConnectionType::CONNECTION_WIFI ||
connection_type ==
net::NetworkChangeNotifier::ConnectionType::CONNECTION_ETHERNET;
return IsBluetoothPowered() ||
(hasNetworkConnection && ::features::IsNearbyMdnsEnabled());
}
void NearbySharingServiceImpl::InvalidateSurfaceState() {
InvalidateSendSurfaceState();
InvalidateReceiveSurfaceState();
if (process_reference_ && ShouldStopNearbyProcess()) {
// We need to debounce the call to shut down the process in case this state
// is temporary (we don't want to the thrash the process). Any
// advertisement, scanning or transferring will stop this timer from
// triggering.
if (!process_shutdown_pending_timer_.IsRunning()) {
CD_LOG(INFO, Feature::NS)
<< __func__
<< ": Scheduling process shutdown if not needed in 15 seconds";
// NOTE: Using base::Unretained is safe because if shutdown_pending_timer_
// goes out of scope the timer will be cancelled.
process_shutdown_pending_timer_.Start(
FROM_HERE, kProcessShutdownPendingTimerDelay,
base::BindOnce(&NearbySharingServiceImpl::OnProcessShutdownTimerFired,
base::Unretained(this)));
}
} else {
process_shutdown_pending_timer_.Stop();
}
}
bool NearbySharingServiceImpl::ShouldStopNearbyProcess() {
// Nothing to do if we're shutting down the profile.
if (!profile_) {
return false;
}
// We're currently advertising.
if (advertising_power_level_ !=
NearbyConnectionsManager::PowerLevel::kUnknown) {
return false;
}
// We're currently discovering.
if (is_scanning_) {
return false;
}
// We're currently attempting to connect to a remote device.
if (is_connecting_) {
return false;
}
// We're currently sending or receiving a file.
if (is_transferring_) {
return false;
}
// We're not using NearbyConnections, should stop the process.
return true;
}
void NearbySharingServiceImpl::OnProcessShutdownTimerFired() {
if (ShouldStopNearbyProcess() && process_reference_) {
CD_LOG(INFO, Feature::NS)
<< __func__
<< ": Shutdown Process timer fired, releasing process reference";
// Manually firing this callback will handle destroying
// |process_reference_|.
//
// The NearbyProcessManager would ordinarily be responsible for firing this
// callback, but it assumes that is unnecessary if the owner destroys the
// process reference, so we're responsible for calling it to ensure that
// downstream listeners are notified.
OnNearbyProcessStopped(NearbyProcessShutdownReason::kNormal);
}
}
void NearbySharingServiceImpl::InvalidateSendSurfaceState() {
InvalidateScanningState();
InvalidateFastInitiationAdvertising();
}
void NearbySharingServiceImpl::InvalidateScanningState() {
// Nothing to do if we're shutting down the profile.
if (!profile_) {
return;
}
if (power_client_->IsSuspended()) {
StopScanning();
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Stopping discovery because the system is suspended.";
return;
}
// Screen is off. Do no work.
if (is_screen_locked_) {
StopScanning();
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Stopping discovery because the screen is locked.";
return;
}
if (!HasAvailableDiscoveryMediums()) {
StopScanning();
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Stopping scanning because both bluetooth and wifi LAN are "
"disabled.";
return;
}
// Nearby Sharing is disabled. Don't advertise.
if (!settings_.GetEnabled()) {
StopScanning();
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Stopping discovery because Nearby Sharing is disabled.";
return;
}
if (is_transferring_ || is_connecting_) {
StopScanning();
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Stopping discovery because we're currently in the midst of a "
"transfer.";
return;
}
if (foreground_send_transfer_callbacks_.empty()) {
StopScanning();
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Stopping discovery because no scanning surface has been "
"registered.";
return;
}
process_shutdown_pending_timer_.Stop();
// Screen is on, Bluetooth is enabled, and Nearby Sharing is enabled! Start
// discovery.
StartScanning();
}
void NearbySharingServiceImpl::InvalidateFastInitiationAdvertising() {
// Nothing to do if we're shutting down the profile.
if (!profile_) {
return;
}
if (power_client_->IsSuspended()) {
StopFastInitiationAdvertising();
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Stopping fast init advertising because the system is suspended.";
return;
}
// Screen is off. Do no work.
if (is_screen_locked_) {
StopFastInitiationAdvertising();
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Stopping fast init advertising because the screen is locked.";
return;
}
if (!IsBluetoothPowered()) {
StopFastInitiationAdvertising();
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Stopping fast init advertising because both "
"bluetooth is disabled.";
return;
}
// Nearby Sharing is disabled. Don't fast init advertise.
if (!settings_.GetEnabled()) {
StopFastInitiationAdvertising();
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Stopping fast init advertising because Nearby "
"Sharing is disabled.";
return;
}
if (foreground_send_transfer_callbacks_.empty()) {
StopFastInitiationAdvertising();
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Stopping fast init advertising because no send "
"surface is registered.";
return;
}
if (fast_initiation_advertiser_) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Already advertising fast init, ignoring.";
return;
}
process_shutdown_pending_timer_.Stop();
StartFastInitiationAdvertising();
}
void NearbySharingServiceImpl::InvalidateReceiveSurfaceState() {
InvalidateAdvertisingState();
InvalidateFastInitiationScanning();
}
void NearbySharingServiceImpl::InvalidateAdvertisingState() {
// Nothing to do if we're shutting down the profile.
if (!profile_) {
return;
}
if (power_client_->IsSuspended()) {
StopAdvertising();
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Stopping advertising because the system is suspended.";
return;
}
if (!HasAvailableAdvertisingMediums()) {
StopAdvertising();
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Stopping advertising because both bluetooth and wifi LAN are "
"disabled.";
return;
}
// Nearby Sharing is disabled. Don't advertise.
if (!settings_.GetEnabled()) {
StopAdvertising();
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Stopping advertising because Nearby Sharing is disabled.";
return;
}
// We're scanning for other nearby devices. Don't advertise.
if (is_scanning_) {
StopAdvertising();
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Stopping advertising because we're scanning for other devices.";
return;
}
if (is_transferring_) {
StopAdvertising();
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Stopping advertising because we're currently in the midst of "
"a transfer.";
return;
}
if (foreground_receive_callbacks_.empty() &&
background_receive_callbacks_.empty()) {
StopAdvertising();
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Stopping advertising because no receive surface is registered.";
return;
}
if (!IsVisibleInBackground(settings_.GetVisibility()) &&
foreground_receive_callbacks_.empty()) {
StopAdvertising();
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Stopping advertising because no high power receive surface "
"is registered and device is visible to NO_ONE.";
return;
}
process_shutdown_pending_timer_.Stop();
NearbyConnectionsManager::PowerLevel power_level;
if (!foreground_receive_callbacks_.empty()) {
power_level = NearbyConnectionsManager::PowerLevel::kHighPower;
// TODO(crbug/1100367) handle fast init
// } else if (isFastInitDeviceNearby) {
// power_level = NearbyConnectionsManager::PowerLevel::kMediumPower;
} else {
power_level = NearbyConnectionsManager::PowerLevel::kLowPower;
}
nearby_share::mojom::DataUsage data_usage = settings_.GetDataUsage();
if (advertising_power_level_ !=
NearbyConnectionsManager::PowerLevel::kUnknown) {
if (power_level == advertising_power_level_) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Ignoring, already advertising with power level "
<< PowerLevelToString(advertising_power_level_)
<< " and data usage preference " << data_usage;
return;
}
StopAdvertising();
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Restart advertising with power level "
<< PowerLevelToString(power_level) << " and data usage preference "
<< data_usage;
}
std::optional<std::string> device_name;
if (!foreground_receive_callbacks_.empty()) {
device_name = local_device_data_manager_->GetDeviceName();
}
// Starts advertising through Nearby Connections. Caller is expected to ensure
// |listener| remains valid until StopAdvertising is called.
std::optional<std::vector<uint8_t>> endpoint_info =
CreateEndpointInfo(device_name);
if (!endpoint_info) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Unable to advertise since could not parse the "
"endpoint info from the advertisement.";
return;
}
// TODO(crbug/1147652): The call to update the advertising interval is
// removed to prevent a Bluez crash. We need to either reduce the global
// advertising interval asynchronously and wait for the result or use the
// updated API referenced in the bug which allows setting a per-advertisement
// interval.
// TODO(crbug/1155669): This will suppress the system notification that
// alerts the user that their device is discoverable, but it exposes Nearby
// Share logic to external components. We should clean this up with a better
// abstraction.
bool used_device_name = device_name.has_value();
if (used_device_name) {
for (auto& observer : observers_) {
observer.OnHighVisibilityChangeRequested();
}
}
nearby_connections_manager_->StartAdvertising(
*endpoint_info,
/*listener=*/this, power_level, data_usage,
base::BindOnce(&NearbySharingServiceImpl::OnStartAdvertisingResult,
weak_ptr_factory_.GetWeakPtr(), used_device_name));
advertising_power_level_ = power_level;
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": StartAdvertising requested over Nearby Connections: "
<< " power level: " << PowerLevelToString(power_level)
<< " visibility: " << settings_.GetVisibility()
<< " data usage: " << data_usage << " advertise device name?: "
<< (device_name.has_value() ? "yes" : "no");
ScheduleRotateBackgroundAdvertisementTimer();
}
void NearbySharingServiceImpl::StopAdvertising() {
if (advertising_power_level_ ==
NearbyConnectionsManager::PowerLevel::kUnknown) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Not currently advertising, ignoring.";
return;
}
nearby_connections_manager_->StopAdvertising(
base::BindOnce(&NearbySharingServiceImpl::OnStopAdvertisingResult,
weak_ptr_factory_.GetWeakPtr()));
// TODO(crbug/1147652): The call to update the advertising interval is
// removed to prevent a Bluez crash. We need to either reduce the global
// advertising interval asynchronously and wait for the result or use the
// updated API referenced in the bug which allows setting a per-advertisement
// interval.
CD_LOG(VERBOSE, Feature::NS) << __func__ << ": Stop advertising requested";
// Set power level to unknown immediately instead of waiting for the callback.
// In the case of restarting advertising (e.g. turning off high visibility
// with contact-based enabled), StartAdvertising will be called
// immediately after StopAdvertising and will fail if the power level
// indicates already advertising.
advertising_power_level_ = NearbyConnectionsManager::PowerLevel::kUnknown;
}
void NearbySharingServiceImpl::StartScanning() {
DCHECK(profile_);
DCHECK(!power_client_->IsSuspended());
DCHECK(settings_.GetEnabled());
DCHECK(!is_screen_locked_);
DCHECK(HasAvailableDiscoveryMediums());
DCHECK(!foreground_send_transfer_callbacks_.empty());
if (is_scanning_) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": We're currently scanning, ignoring.";
return;
}
scanning_start_timestamp_ = base::Time::Now();
is_scanning_ = true;
InvalidateReceiveSurfaceState();
ClearOutgoingShareTargetInfoMap();
discovered_advertisements_to_retry_map_.clear();
nearby_connections_manager_->StartDiscovery(
/*listener=*/this, settings_.GetDataUsage(),
base::BindOnce(&NearbySharingServiceImpl::OnStartDiscoveryResult,
weak_ptr_factory_.GetWeakPtr()));
InvalidateSendSurfaceState();
CD_LOG(VERBOSE, Feature::NS) << __func__ << ": Scanning has started";
}
NearbySharingService::StatusCodes NearbySharingServiceImpl::StopScanning() {
if (!is_scanning_) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Not currently scanning, ignoring.";
return StatusCodes::kStatusAlreadyStopped;
}
nearby_connections_manager_->StopDiscovery();
is_scanning_ = false;
// TODO(b/313950374): This should really happen when NC actually stops
// discovery, which could happen outside of this function.
for (auto& observer : observers_) {
observer.OnShareTargetDiscoveryStopped();
}
certificate_download_during_discovery_timer_.Stop();
discovered_advertisements_to_retry_map_.clear();
// Note: We don't know if we stopped scanning in preparation to send a file,
// or we stopped because the user left the page. We'll invalidate after a
// short delay.
base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&NearbySharingServiceImpl::InvalidateSurfaceState,
weak_ptr_factory_.GetWeakPtr()),
kInvalidateDelay);
CD_LOG(VERBOSE, Feature::NS) << __func__ << ": Scanning has stopped.";
return StatusCodes::kOk;
}
void NearbySharingServiceImpl::StopAdvertisingAndInvalidateSurfaceState() {
if (advertising_power_level_ !=
NearbyConnectionsManager::PowerLevel::kUnknown) {
StopAdvertising();
}
InvalidateSurfaceState();
}
void NearbySharingServiceImpl::InvalidateFastInitiationScanning() {
bool is_hardware_offloading_supported =
IsBluetoothPresent() &&
FastInitiationScanner::Factory::IsHardwareSupportAvailable(
bluetooth_adapter_.get());
// Hardware offloading support is computed when the bluetooth adapter becomes
// available. We set the hardware supported state on |settings_| to notify the
// UI of state changes. InvalidateFastInitiationScanning gets triggered on
// adapter change events.
settings_.SetIsFastInitiationHardwareSupported(
is_hardware_offloading_supported);
// Nothing to do if we're shutting down the profile.
if (!profile_) {
return;
}
if (fast_initiation_scanner_cooldown_timer_.IsRunning()) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Stopping background scanning due to post-transfer "
"cooldown period";
StopFastInitiationScanning();
return;
}
if (settings_.GetFastInitiationNotificationState() !=
nearby_share::mojom::FastInitiationNotificationState::kEnabled) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Stopping background scanning; fast initiation "
"notification is disabled";
StopFastInitiationScanning();
return;
}
if (GetNearbyShareEnabledState(prefs_) ==
NearbyShareEnabledState::kDisallowedByPolicy) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Stopping background scanning because Nearby Sharing "
"is disallowed by policy ";
StopFastInitiationScanning();
return;
}
if (power_client_->IsSuspended()) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Stopping background scanning because the system is suspended.";
StopFastInitiationScanning();
return;
}
// Screen is off. Do no work.
if (is_screen_locked_) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Stopping background scanning because the screen is locked.";
StopFastInitiationScanning();
return;
}
if (!IsBluetoothPowered()) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Stopping background scanning because bluetooth is powered down.";
StopFastInitiationScanning();
return;
}
// We're scanning for other nearby devices. Don't background scan.
if (is_scanning_) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Stopping background scanning because we're scanning "
"for other devices.";
StopFastInitiationScanning();
return;
}
if (is_transferring_) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Stopping background scanning because we're currently "
"in the midst of "
"a transfer.";
StopFastInitiationScanning();
return;
}
if (advertising_power_level_ ==
NearbyConnectionsManager::PowerLevel::kHighPower) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Stopping background scanning because we're already "
"in high visibility mode.";
StopFastInitiationScanning();
return;
}
if (!is_hardware_offloading_supported) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Stopping background scanning because hardware "
"support is not available or not ready.";
StopFastInitiationScanning();
return;
}
process_shutdown_pending_timer_.Stop();
if (fast_initiation_scanner_) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Ignoring, already background scanning.";
return;
}
StartFastInitiationScanning();
}
void NearbySharingServiceImpl::StartFastInitiationScanning() {
DCHECK(!fast_initiation_scanner_);
CD_LOG(VERBOSE, Feature::NS) << __func__ << ": Starting background scanning.";
fast_initiation_scanner_ =
FastInitiationScanner::Factory::Create(bluetooth_adapter_);
fast_initiation_scanner_->StartScanning(
base::BindRepeating(
&NearbySharingServiceImpl::OnFastInitiationDevicesDetected,
weak_ptr_factory_.GetWeakPtr()),
base::BindRepeating(
&NearbySharingServiceImpl::OnFastInitiationDevicesNotDetected,
weak_ptr_factory_.GetWeakPtr()),
base::BindOnce(&NearbySharingServiceImpl::StopFastInitiationScanning,
weak_ptr_factory_.GetWeakPtr()));
}
void NearbySharingServiceImpl::OnFastInitiationDevicesDetected() {
CD_LOG(VERBOSE, Feature::NS) << __func__;
for (auto& observer : observers_) {
observer.OnFastInitiationDevicesDetected();
}
}
void NearbySharingServiceImpl::OnFastInitiationDevicesNotDetected() {
CD_LOG(VERBOSE, Feature::NS) << __func__;
for (auto& observer : observers_) {
observer.OnFastInitiationDevicesNotDetected();
}
}
void NearbySharingServiceImpl::StopFastInitiationScanning() {
if (!fast_initiation_scanner_) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Ignoring, not background scanning.";
return;
}
fast_initiation_scanner_.reset();
for (auto& observer : observers_) {
observer.OnFastInitiationScanningStopped();
}
CD_LOG(VERBOSE, Feature::NS) << __func__ << ": Stopped background scanning.";
}
void NearbySharingServiceImpl::ScheduleRotateBackgroundAdvertisementTimer() {
uint64_t delayRangeMilliseconds = base::checked_cast<uint64_t>(
kBackgroundAdvertisementRotationDelayMax.InMilliseconds() -
kBackgroundAdvertisementRotationDelayMin.InMilliseconds());
uint64_t delayMilliseconds =
base::RandGenerator(delayRangeMilliseconds) +
base::checked_cast<uint64_t>(
kBackgroundAdvertisementRotationDelayMin.InMilliseconds());
rotate_background_advertisement_timer_.Start(
FROM_HERE,
base::Milliseconds(base::checked_cast<uint64_t>(delayMilliseconds)),
base::BindOnce(
&NearbySharingServiceImpl::OnRotateBackgroundAdvertisementTimerFired,
weak_ptr_factory_.GetWeakPtr()));
}
void NearbySharingServiceImpl::OnRotateBackgroundAdvertisementTimerFired() {
if (!foreground_receive_callbacks_.empty()) {
ScheduleRotateBackgroundAdvertisementTimer();
} else {
StopAdvertising();
InvalidateSurfaceState();
}
}
void NearbySharingServiceImpl::RemoveOutgoingShareTargetWithEndpointId(
const std::string& endpoint_id) {
auto it = outgoing_share_target_map_.find(endpoint_id);
if (it == outgoing_share_target_map_.end()) {
return;
}
// Share target state needs to be cleared before the move below.
share_target_map_.erase(endpoint_id);
transfer_size_map_.erase(endpoint_id);
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Removing (endpoint_id=" << it->first
<< ", share_target.id=" << it->second.id
<< ") from outgoing share target map";
ShareTarget share_target = std::move(it->second);
outgoing_share_target_map_.erase(it);
auto info_it = outgoing_share_target_info_map_.find(share_target.id);
if (info_it != outgoing_share_target_info_map_.end()) {
file_handler_.ReleaseFilePayloads(info_it->second.ExtractFilePayloads());
outgoing_share_target_info_map_.erase(info_it);
}
for (ShareTargetDiscoveredCallback& discovery_callback :
foreground_send_discovery_callbacks_) {
discovery_callback.OnShareTargetLost(share_target);
}
for (ShareTargetDiscoveredCallback& discovery_callback :
background_send_discovery_callbacks_) {
discovery_callback.OnShareTargetLost(share_target);
}
for (auto& observer : observers_) {
observer.OnShareTargetRemoved(share_target);
}
CD_LOG(VERBOSE, Feature::NS) << __func__ << ": Reported OnShareTargetLost";
}
void NearbySharingServiceImpl::OnTransferComplete() {
bool was_sending_files = is_sending_files_;
is_receiving_files_ = false;
is_transferring_ = false;
is_sending_files_ = false;
// Cleanup ARC after send transfer completes since reading from file
// descriptor(s) are done at this point even though there could be Nearby
// Connection frames cached that are not yet sent to the remote device.
if (was_sending_files && arc_transfer_cleanup_callback_) {
std::move(arc_transfer_cleanup_callback_).Run();
}
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": NearbySharing state change transfer finished";
// Files transfer is done! Receivers can immediately cancel, but senders
// should add a short delay to ensure the final in-flight packet(s) make
// it to the remote device.
base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&NearbySharingServiceImpl::InvalidateSurfaceState,
weak_ptr_factory_.GetWeakPtr()),
was_sending_files ? kInvalidateSurfaceStateDelayAfterTransferDone
: base::TimeDelta());
}
void NearbySharingServiceImpl::OnTransferStarted(bool is_incoming) {
is_transferring_ = true;
if (is_incoming) {
is_receiving_files_ = true;
} else {
is_sending_files_ = true;
}
InvalidateSurfaceState();
}
void NearbySharingServiceImpl::ReceivePayloads(
ShareTarget share_target,
StatusCodesCallback status_codes_callback) {
DCHECK(profile_);
mutual_acceptance_timeout_alarm_.Cancel();
base::FilePath download_path =
DownloadPrefs::FromDownloadManager(profile_->GetDownloadManager())
->DownloadPath();
// Register payload path for all valid file payloads.
base::flat_map<int64_t, base::FilePath> valid_file_payloads;
for (auto& file : share_target.file_attachments) {
std::optional<int64_t> payload_id = GetAttachmentPayloadId(file.id());
if (!payload_id) {
CD_LOG(WARNING, Feature::NS)
<< __func__
<< ": Failed to register payload path for attachment id - "
<< file.id();
continue;
}
base::FilePath file_path = download_path.Append(file.file_name());
valid_file_payloads.emplace(file.id(), std::move(file_path));
}
auto aggregated_success = std::make_unique<bool>(true);
bool* aggregated_success_ptr = aggregated_success.get();
if (valid_file_payloads.empty()) {
OnPayloadPathsRegistered(share_target, std::move(aggregated_success),
std::move(status_codes_callback));
return;
}
auto all_paths_registered_callback = base::BarrierClosure(
valid_file_payloads.size(),
base::BindOnce(&NearbySharingServiceImpl::OnPayloadPathsRegistered,
weak_ptr_factory_.GetWeakPtr(), share_target,
std::move(aggregated_success),
std::move(status_codes_callback)));
for (const auto& payload : valid_file_payloads) {
std::optional<int64_t> payload_id = GetAttachmentPayloadId(payload.first);
DCHECK(payload_id);
file_handler_.GetUniquePath(
payload.second,
base::BindOnce(
&NearbySharingServiceImpl::OnUniquePathFetched,
weak_ptr_factory_.GetWeakPtr(), payload.first, *payload_id,
base::BindOnce(
&NearbySharingServiceImpl::OnPayloadPathRegistered,
weak_ptr_factory_.GetWeakPtr(),
base::ScopedClosureRunner(all_paths_registered_callback),
aggregated_success_ptr)));
}
}
NearbySharingService::StatusCodes NearbySharingServiceImpl::SendPayloads(
const ShareTarget& share_target) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Preparing to send payloads to " << share_target.id;
ShareTargetInfo* info = GetShareTargetInfo(share_target);
if (!info || !info->connection()) {
RecordNearbyShareError(NearbyShareError::kSendPayloadsMissingConnection);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": Failed to send payload due to missing connection.";
return StatusCodes::kOutOfOrderApiCall;
}
if (!info->transfer_update_callback()) {
RecordNearbyShareError(
NearbyShareError::kSendPayloadsMissingTransferUpdateCallback);
CD_LOG(WARNING, Feature::NS)
<< __func__
<< ": Failed to send payload due to missing transfer update "
"callback. Disconnecting.";
AbortAndCloseConnectionIfNecessary(
TransferMetadata::Status::kMissingTransferUpdateCallback, share_target);
return StatusCodes::kOutOfOrderApiCall;
}
info->transfer_update_callback()->OnTransferUpdate(
share_target,
TransferMetadataBuilder()
.set_token(info->token())
.set_status(TransferMetadata::Status::kAwaitingRemoteAcceptance)
.build());
if (!info->endpoint_id()) {
RecordNearbyShareError(NearbyShareError::kSendPayloadsMissingEndpointId);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": Failed to send payload due to missing endpoint id.";
AbortAndCloseConnectionIfNecessary(
TransferMetadata::Status::kMissingEndpointId, share_target);
return StatusCodes::kOutOfOrderApiCall;
}
ReceiveConnectionResponse(share_target);
return StatusCodes::kOk;
}
void NearbySharingServiceImpl::OnUniquePathFetched(
int64_t attachment_id,
int64_t payload_id,
base::OnceCallback<void(nearby::connections::mojom::Status)> callback,
base::FilePath path) {
attachment_info_map_[attachment_id].file_path = path;
nearby_connections_manager_->RegisterPayloadPath(payload_id, path,
std::move(callback));
}
void NearbySharingServiceImpl::OnPayloadPathRegistered(
base::ScopedClosureRunner closure_runner,
bool* aggregated_success,
::nearby::connections::mojom::Status status) {
if (status != ::nearby::connections::mojom::Status::kSuccess) {
*aggregated_success = false;
}
}
void NearbySharingServiceImpl::OnPayloadPathsRegistered(
const ShareTarget& share_target,
std::unique_ptr<bool> aggregated_success,
StatusCodesCallback status_codes_callback) {
DCHECK(aggregated_success);
if (!*aggregated_success) {
RecordNearbyShareError(NearbyShareError::kPayloadPathsRegisteredFailed);
CD_LOG(WARNING, Feature::NS)
<< __func__
<< ": Not all payload paths could be registered successfully.";
std::move(status_codes_callback).Run(StatusCodes::kError);
return;
}
ShareTargetInfo* info = GetShareTargetInfo(share_target);
if (!info || !info->connection()) {
RecordNearbyShareError(
NearbyShareError::kPayloadPathsRegisteredUnknownShareTarget);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": Accept invoked for unknown share target";
std::move(status_codes_callback).Run(StatusCodes::kOutOfOrderApiCall);
return;
}
NearbyConnection* connection = info->connection();
if (!info->transfer_update_callback()) {
RecordNearbyShareError(
NearbyShareError::kPayloadPathsRegisteredMissingTransferUpdateCallback);
CD_LOG(WARNING, Feature::NS)
<< __func__
<< ": Accept invoked for share target without transfer "
"update callback. Disconnecting.";
AbortAndCloseConnectionIfNecessary(
TransferMetadata::Status::kMissingTransferUpdateCallback, share_target);
std::move(status_codes_callback).Run(StatusCodes::kOutOfOrderApiCall);
return;
}
info->set_payload_tracker(std::make_unique<PayloadTracker>(
share_target, attachment_info_map_,
base::BindRepeating(&NearbySharingServiceImpl::OnPayloadTransferUpdate,
weak_ptr_factory_.GetWeakPtr())));
// Register status listener for all payloads.
for (int64_t attachment_id : share_target.GetAttachmentIds()) {
std::optional<int64_t> payload_id = GetAttachmentPayloadId(attachment_id);
if (!payload_id) {
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": Failed to retrieve payload for attachment id - "
<< attachment_id;
continue;
}
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Started listening for progress on payload - "
<< *payload_id;
nearby_connections_manager_->RegisterPayloadStatusListener(
*payload_id, info->payload_tracker());
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Accepted incoming files from share target - "
<< share_target.id;
}
WriteResponse(*connection, sharing::nearby::ConnectionResponseFrame::ACCEPT);
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Successfully wrote response frame";
// Receiver event
for (auto& observer : observers_) {
observer.OnTransferStarted(share_target,
transfer_size_map_[info->endpoint_id().value()]);
}
info->transfer_update_callback()->OnTransferUpdate(
share_target,
TransferMetadataBuilder()
.set_status(TransferMetadata::Status::kAwaitingRemoteAcceptance)
.set_token(info->token())
.build());
std::optional<std::string> endpoint_id = info->endpoint_id();
if (endpoint_id) {
// Upgrade bandwidth regardless of advertising visibility because either
// the system or the user has verified the sender's identity; the
// stable identifiers potentially exposed by performing a bandwidth
// upgrade are no longer a concern.
nearby_connections_manager_->UpgradeBandwidth(*endpoint_id);
} else {
RecordNearbyShareError(
NearbyShareError::kPayloadPathsRegisteredMissingEndpointId);
CD_LOG(WARNING, Feature::NS)
<< __func__
<< ": Failed to initiate bandwidth upgrade. No endpoint_id "
"found for target - "
<< share_target.id;
std::move(status_codes_callback).Run(StatusCodes::kOutOfOrderApiCall);
return;
}
std::move(status_codes_callback).Run(StatusCodes::kOk);
}
void NearbySharingServiceImpl::OnOutgoingConnection(
const ShareTarget& share_target,
base::TimeTicks connect_start_time,
NearbyConnection* connection) {
OutgoingShareTargetInfo* info = GetOutgoingShareTargetInfo(share_target);
bool success = info && info->endpoint_id() && connection;
RecordNearbyShareEstablishConnectionMetrics(
success, /*cancelled=*/
base::Contains(all_cancelled_share_target_ids_, share_target.id),
base::TimeTicks::Now() - connect_start_time);
if (!success) {
RecordNearbyShareError(
NearbyShareError::kOutgoingConnectionFailedtoInitiateConnection);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": Failed to initate connection to share target "
<< share_target.id;
AbortAndCloseConnectionIfNecessary(
TransferMetadata::Status::kFailedToInitiateOutgoingConnection,
share_target);
return;
}
info->set_connection(connection);
CHECK(info->endpoint_id().has_value());
transfer_profiler_->OnConnectionEstablished(info->endpoint_id().value());
for (auto& observer : observers_) {
observer.OnShareTargetConnected(share_target);
}
connection->SetDisconnectionListener(base::BindOnce(
&NearbySharingServiceImpl::OnOutgoingConnectionDisconnected,
weak_ptr_factory_.GetWeakPtr(), share_target));
std::optional<std::string> four_digit_token =
ToFourDigitString(nearby_connections_manager_->GetRawAuthenticationToken(
*info->endpoint_id()));
RunPairedKeyVerification(
share_target, *info->endpoint_id(),
base::BindOnce(
&NearbySharingServiceImpl::OnOutgoingConnectionKeyVerificationDone,
weak_ptr_factory_.GetWeakPtr(), share_target,
std::move(four_digit_token)));
}
void NearbySharingServiceImpl::SendIntroduction(
const ShareTarget& share_target,
std::optional<std::string> four_digit_token) {
// We successfully connected! Now lets build up Payloads for all the files we
// want to send them. We won't send any just yet, but we'll send the Payload
// IDs in our our introduction frame so that they know what to expect if they
// accept.
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Preparing to send introduction to " << share_target.id;
ShareTargetInfo* info = GetShareTargetInfo(share_target);
if (!info || !info->connection()) {
RecordNearbyShareError(
NearbyShareError::kSendIntroductionFailedToGetShareTarget);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": No NearbyConnection tied to " << share_target.id;
return;
}
NearbyConnection* connection = info->connection();
if (!info->transfer_update_callback()) {
RecordNearbyShareError(
NearbyShareError::kSendIntroductionMissingTransferUpdateCallback);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": No transfer update callback, disconnecting.";
AbortAndCloseConnectionIfNecessary(
TransferMetadata::Status::kMissingTransferUpdateCallback, share_target);
return;
}
if (foreground_send_transfer_callbacks_.empty() &&
background_send_transfer_callbacks_.empty()) {
RecordNearbyShareError(
NearbyShareError::kSendIntroductionNoSendTransferCallbacks);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": No transfer callbacks, disconnecting.";
connection->Close();
return;
}
// Build the introduction.
auto introduction = std::make_unique<sharing::nearby::IntroductionFrame>();
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Sending attachments to " << share_target.id;
// Write introduction of file payloads.
int64_t transfer_size = 0;
for (const auto& file : share_target.file_attachments) {
std::optional<int64_t> payload_id = GetAttachmentPayloadId(file.id());
if (!payload_id) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Skipping unknown file attachment";
continue;
}
auto* file_metadata = introduction->add_file_metadata();
file_metadata->set_id(file.id());
file_metadata->set_name(file.file_name());
file_metadata->set_payload_id(*payload_id);
file_metadata->set_type(sharing::ConvertFileMetadataType(file.type()));
file_metadata->set_mime_type(file.mime_type());
file_metadata->set_size(file.size());
transfer_size += file.size();
}
// Write introduction of text payloads.
for (const auto& text : share_target.text_attachments) {
std::optional<int64_t> payload_id = GetAttachmentPayloadId(text.id());
if (!payload_id) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Skipping unknown text attachment";
continue;
}
auto* text_metadata = introduction->add_text_metadata();
text_metadata->set_id(text.id());
text_metadata->set_text_title(text.text_title());
text_metadata->set_type(sharing::ConvertTextMetadataType(text.type()));
text_metadata->set_size(text.size());
text_metadata->set_payload_id(*payload_id);
transfer_size += text.size();
}
if (introduction->file_metadata_size() == 0 &&
introduction->text_metadata_size() == 0) {
RecordNearbyShareError(NearbyShareError::kSendIntroductionNoPayloads);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": No payloads tied to transfer, disconnecting.";
AbortAndCloseConnectionIfNecessary(
TransferMetadata::Status::kMissingPayloads, share_target);
return;
}
// Write the introduction to the remote device.
sharing::nearby::Frame frame;
frame.set_version(sharing::nearby::Frame::V1);
sharing::nearby::V1Frame* v1_frame = frame.mutable_v1();
v1_frame->set_type(sharing::nearby::V1Frame::INTRODUCTION);
v1_frame->set_allocated_introduction(introduction.release());
std::vector<uint8_t> data(frame.ByteSizeLong());
frame.SerializeToArray(data.data(), frame.ByteSizeLong());
connection->Write(std::move(data));
// We've successfully written the introduction, so we now have to wait for the
// remote side to accept.
RecordNearbyShareTimeFromInitiateSendToRemoteDeviceNotificationMetric(
base::TimeTicks::Now() - send_attachments_timestamp_);
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Successfully wrote the introduction frame";
CHECK(info->endpoint_id().has_value());
transfer_profiler_->OnIntroductionFrameSent(info->endpoint_id().value());
// Store the file size for use when the transfer actually begins.
transfer_size_map_[info->endpoint_id().value()] = transfer_size;
mutual_acceptance_timeout_alarm_.Reset(base::BindOnce(
&NearbySharingServiceImpl::OnOutgoingMutualAcceptanceTimeout,
weak_ptr_factory_.GetWeakPtr(), share_target));
base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE, base::BindOnce(mutual_acceptance_timeout_alarm_.callback()),
kReadResponseFrameTimeout);
info->transfer_update_callback()->OnTransferUpdate(
share_target,
TransferMetadataBuilder()
.set_status(TransferMetadata::Status::kAwaitingLocalConfirmation)
.set_token(four_digit_token)
.build());
}
void NearbySharingServiceImpl::CreatePayloads(
ShareTarget share_target,
base::OnceCallback<void(ShareTarget, bool)> callback) {
OutgoingShareTargetInfo* info = GetOutgoingShareTargetInfo(share_target);
if (!info || !share_target.has_attachments()) {
RecordNearbyShareError(NearbyShareError::kCreatePayloadsNoAttachments);
std::move(callback).Run(std::move(share_target), /*success=*/false);
return;
}
if (!info->file_payloads().empty() || !info->text_payloads().empty()) {
// We may have already created the payloads in the case of retry, so we can
// skip this step.
RecordNearbyShareError(
NearbyShareError::kCreatePayloadsNoFileOrTextPayloads);
std::move(callback).Run(std::move(share_target), /*success=*/false);
return;
}
info->set_text_payloads(CreateTextPayloads(share_target.text_attachments));
if (share_target.file_attachments.empty()) {
std::move(callback).Run(std::move(share_target), /*success=*/true);
return;
}
std::vector<base::FilePath> file_paths;
for (const FileAttachment& attachment : share_target.file_attachments) {
if (!attachment.file_path()) {
RecordNearbyShareError(
NearbyShareError::kCreatePayloadsFilePayloadWithoutPath);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": Got file attachment without path";
std::move(callback).Run(std::move(share_target), /*success=*/false);
return;
}
file_paths.push_back(*attachment.file_path());
}
file_handler_.OpenFiles(
std::move(file_paths),
base::BindOnce(&NearbySharingServiceImpl::OnOpenFiles,
weak_ptr_factory_.GetWeakPtr(), std::move(share_target),
std::move(callback)));
}
void NearbySharingServiceImpl::OnCreatePayloads(
std::vector<uint8_t> endpoint_info,
ShareTarget share_target,
bool success) {
OutgoingShareTargetInfo* info = GetOutgoingShareTargetInfo(share_target);
bool has_payloads = info && (!info->text_payloads().empty() ||
!info->file_payloads().empty());
if (!success || !has_payloads || !info->endpoint_id()) {
RecordNearbyShareError(NearbyShareError::kOnCreatePayloadsFailed);
CD_LOG(WARNING, Feature::NS)
<< __func__
<< ": Failed to send file to remote ShareTarget. Failed to "
"create payloads.";
if (info && info->transfer_update_callback()) {
info->transfer_update_callback()->OnTransferUpdate(
share_target,
TransferMetadataBuilder()
.set_status(TransferMetadata::Status::kMediaUnavailable)
.build());
}
return;
}
std::optional<std::vector<uint8_t>> bluetooth_mac_address =
GetBluetoothMacAddressForShareTarget(share_target);
// For metrics.
all_cancelled_share_target_ids_.clear();
// TODO(crbug.com/1111458): Add preferred transfer type.
nearby_connections_manager_->Connect(
std::move(endpoint_info), *info->endpoint_id(),
std::move(bluetooth_mac_address), settings_.GetDataUsage(),
base::BindOnce(&NearbySharingServiceImpl::OnOutgoingConnection,
weak_ptr_factory_.GetWeakPtr(), share_target,
base::TimeTicks::Now()));
}
void NearbySharingServiceImpl::OnOpenFiles(
ShareTarget share_target,
base::OnceCallback<void(ShareTarget, bool)> callback,
std::vector<NearbyFileHandler::FileInfo> files) {
OutgoingShareTargetInfo* info = GetOutgoingShareTargetInfo(share_target);
const bool files_open_success =
(files.size() == share_target.file_attachments.size());
RecordNearbySharePayloadFileOperationMetrics(
profile_, share_target, PayloadFileOperation::kOpen, files_open_success);
if (!info || !files_open_success) {
RecordNearbyShareError(NearbyShareError::kOnOpenFilesFailed);
std::move(callback).Run(std::move(share_target), /*success=*/false);
return;
}
std::vector<nearby::connections::mojom::PayloadPtr> payloads;
payloads.reserve(files.size());
for (size_t i = 0; i < files.size(); ++i) {
FileAttachment& attachment = share_target.file_attachments[i];
attachment.set_size(files[i].size);
base::File& file = files[i].file;
int64_t payload_id = GeneratePayloadId();
SetAttachmentPayloadId(attachment, payload_id);
payloads.push_back(nearby::connections::mojom::Payload::New(
payload_id,
nearby::connections::mojom::PayloadContent::NewFile(
nearby::connections::mojom::FilePayload::New(std::move(file)))));
}
info->set_file_payloads(std::move(payloads));
std::move(callback).Run(std::move(share_target), /*success=*/true);
}
std::vector<nearby::connections::mojom::PayloadPtr>
NearbySharingServiceImpl::CreateTextPayloads(
const std::vector<TextAttachment>& attachments) {
std::vector<nearby::connections::mojom::PayloadPtr> payloads;
payloads.reserve(attachments.size());
for (const TextAttachment& attachment : attachments) {
const std::string& body = attachment.text_body();
std::vector<uint8_t> bytes(body.begin(), body.end());
int64_t payload_id = GeneratePayloadId();
SetAttachmentPayloadId(attachment, payload_id);
payloads.push_back(nearby::connections::mojom::Payload::New(
payload_id,
nearby::connections::mojom::PayloadContent::NewBytes(
nearby::connections::mojom::BytesPayload::New(std::move(bytes)))));
}
return payloads;
}
void NearbySharingServiceImpl::WriteResponse(
NearbyConnection& connection,
sharing::nearby::ConnectionResponseFrame::Status status) {
sharing::nearby::Frame frame;
frame.set_version(sharing::nearby::Frame::V1);
sharing::nearby::V1Frame* v1_frame = frame.mutable_v1();
v1_frame->set_type(sharing::nearby::V1Frame::RESPONSE);
v1_frame->mutable_connection_response()->set_status(status);
std::vector<uint8_t> data(frame.ByteSizeLong());
frame.SerializeToArray(data.data(), frame.ByteSizeLong());
connection.Write(std::move(data));
}
void NearbySharingServiceImpl::WriteCancel(NearbyConnection& connection) {
CD_LOG(INFO, Feature::NS) << __func__ << ": Writing cancel frame.";
sharing::nearby::Frame frame;
frame.set_version(sharing::nearby::Frame::V1);
sharing::nearby::V1Frame* v1_frame = frame.mutable_v1();
v1_frame->set_type(sharing::nearby::V1Frame::CANCEL);
std::vector<uint8_t> data(frame.ByteSizeLong());
frame.SerializeToArray(data.data(), frame.ByteSizeLong());
connection.Write(std::move(data));
}
void NearbySharingServiceImpl::Fail(const ShareTarget& share_target,
TransferMetadata::Status status) {
ShareTargetInfo* info = GetShareTargetInfo(share_target);
if (!info || !info->connection()) {
RecordNearbyShareError(NearbyShareError::kFailUnknownShareTarget);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": Fail invoked for unknown share target.";
return;
}
NearbyConnection* connection = info->connection();
base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&NearbySharingServiceImpl::CloseConnection,
weak_ptr_factory_.GetWeakPtr(), share_target),
kIncomingRejectionDelay);
connection->SetDisconnectionListener(
base::BindOnce(&NearbySharingServiceImpl::UnregisterShareTarget,
weak_ptr_factory_.GetWeakPtr(), share_target));
// Send response to remote device.
sharing::nearby::ConnectionResponseFrame::Status response_status;
switch (status) {
case TransferMetadata::Status::kNotEnoughSpace:
response_status =
sharing::nearby::ConnectionResponseFrame::NOT_ENOUGH_SPACE;
break;
case TransferMetadata::Status::kUnsupportedAttachmentType:
response_status =
sharing::nearby::ConnectionResponseFrame::UNSUPPORTED_ATTACHMENT_TYPE;
break;
case TransferMetadata::Status::kTimedOut:
response_status = sharing::nearby::ConnectionResponseFrame::TIMED_OUT;
break;
default:
response_status = sharing::nearby::ConnectionResponseFrame::UNKNOWN;
break;
}
WriteResponse(*connection, response_status);
if (info->transfer_update_callback()) {
info->transfer_update_callback()->OnTransferUpdate(
share_target, TransferMetadataBuilder().set_status(status).build());
}
}
void NearbySharingServiceImpl::OnIncomingAdvertisementDecoded(
const std::string& endpoint_id,
ShareTarget placeholder_share_target,
sharing::mojom::AdvertisementPtr advertisement) {
NearbyConnection* connection = GetConnection(placeholder_share_target);
if (!connection) {
RecordNearbyShareError(
NearbyShareError::kIncomingAdvertisementDecodedInvalidConnection);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": Invalid connection for endoint id - " << endpoint_id;
return;
}
if (!advertisement) {
RecordNearbyShareError(
NearbyShareError::kIncomingAdvertisementDecodedFailedToParse);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": Failed to parse incoming connection from endpoint - "
<< endpoint_id << ", disconnecting.";
AbortAndCloseConnectionIfNecessary(
TransferMetadata::Status::kDecodeAdvertisementFailed,
placeholder_share_target);
return;
}
transfer_profiler_->OnIncomingEndpointDecoded(endpoint_id,
IsInHighVisibility());
NearbyShareEncryptedMetadataKey encrypted_metadata_key =
AdvertisementToKey(advertisement);
GetCertificateManager()->GetDecryptedPublicCertificate(
std::move(encrypted_metadata_key),
base::BindOnce(&NearbySharingServiceImpl::OnIncomingDecryptedCertificate,
weak_ptr_factory_.GetWeakPtr(), endpoint_id,
std::move(advertisement),
std::move(placeholder_share_target)));
}
void NearbySharingServiceImpl::OnIncomingTransferUpdate(
const ShareTarget& share_target,
const TransferMetadata& metadata) {
// kInProgress status is logged extensively elsewhere so avoid the spam.
if (metadata.status() != TransferMetadata::Status::kInProgress) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Nearby Share service: "
<< "Incoming transfer update for share target with ID "
<< share_target.id << ": "
<< TransferMetadata::StatusToString(metadata.status());
}
if (metadata.status() != TransferMetadata::Status::kCancelled &&
metadata.status() != TransferMetadata::Status::kRejected) {
last_incoming_metadata_ =
std::make_pair(share_target, TransferMetadataBuilder::Clone(metadata)
.set_is_original(false)
.build());
} else {
last_incoming_metadata_ = std::nullopt;
}
// Failed or cancelled transfers result in the progress being set to 0.
if (!metadata.is_final_status()) {
for (auto& observer : observers_) {
observer.OnTransferUpdated(share_target, metadata.progress());
}
}
if (metadata.is_final_status()) {
RecordNearbyShareTransferFinalStatusMetric(
&feature_usage_metrics_,
/*is_incoming=*/true, share_target.type, metadata.status(),
share_target.is_known, share_target.for_self_share, is_screen_locked_);
ShareTargetInfo* info = GetShareTargetInfo(share_target);
CHECK(info->endpoint_id().has_value());
transfer_profiler_->OnReceiveComplete(info->endpoint_id().value(),
metadata.status());
for (auto& observer : observers_) {
observer.OnTransferCompleted(share_target, metadata.status());
}
OnTransferComplete();
if (metadata.status() != TransferMetadata::Status::kComplete) {
// For any type of failure, lets make sure any pending files get cleaned
// up.
RemoveIncomingPayloads(share_target);
}
} else if (metadata.status() ==
TransferMetadata::Status::kAwaitingLocalConfirmation) {
OnTransferStarted(/*is_incoming=*/true);
}
base::ObserverList<TransferUpdateCallback>& transfer_callbacks =
foreground_receive_callbacks_.empty() ? background_receive_callbacks_
: foreground_receive_callbacks_;
for (TransferUpdateCallback& callback : transfer_callbacks) {
callback.OnTransferUpdate(share_target, metadata);
}
}
void NearbySharingServiceImpl::OnOutgoingTransferUpdate(
const ShareTarget& share_target,
const TransferMetadata& metadata) {
// kInProgress status is logged extensively elsewhere so avoid the spam.
if (metadata.status() != TransferMetadata::Status::kInProgress) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Nearby Share service: "
<< "Outgoing transfer update for share target with ID "
<< share_target.id << ": "
<< TransferMetadata::StatusToString(metadata.status());
}
// Failed or cancelled transfers result in the progress being set to 0.
if (!metadata.is_final_status()) {
for (auto& observer : observers_) {
observer.OnTransferUpdated(share_target, metadata.progress());
}
}
if (metadata.is_final_status()) {
is_connecting_ = false;
RecordNearbyShareTransferFinalStatusMetric(
&feature_usage_metrics_,
/*is_incoming=*/false, share_target.type, metadata.status(),
share_target.is_known, share_target.for_self_share, is_screen_locked_);
ShareTargetInfo* info = GetShareTargetInfo(share_target);
CHECK(info->endpoint_id().has_value());
transfer_profiler_->OnSendComplete(info->endpoint_id().value(),
metadata.status());
for (auto& observer : observers_) {
observer.OnTransferCompleted(share_target, metadata.status());
}
OnTransferComplete();
} else if (metadata.status() == TransferMetadata::Status::kMediaDownloading ||
metadata.status() ==
TransferMetadata::Status::kAwaitingLocalConfirmation) {
is_connecting_ = false;
OnTransferStarted(/*is_incoming=*/false);
}
bool has_foreground_send_surface =
!foreground_send_transfer_callbacks_.empty();
base::ObserverList<TransferUpdateCallback>& transfer_callbacks =
has_foreground_send_surface ? foreground_send_transfer_callbacks_
: background_send_transfer_callbacks_;
for (TransferUpdateCallback& callback : transfer_callbacks) {
callback.OnTransferUpdate(share_target, metadata);
}
if (has_foreground_send_surface && metadata.is_final_status()) {
last_outgoing_metadata_ = std::nullopt;
} else {
last_outgoing_metadata_ =
std::make_pair(share_target, TransferMetadataBuilder::Clone(metadata)
.set_is_original(false)
.build());
}
}
void NearbySharingServiceImpl::CloseConnection(
const ShareTarget& share_target) {
NearbyConnection* connection = GetConnection(share_target);
if (!connection) {
RecordNearbyShareError(NearbyShareError::kCloseConnectionInvalidConnection);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": Invalid connection for target - " << share_target.id;
return;
}
connection->Close();
}
void NearbySharingServiceImpl::OnIncomingDecryptedCertificate(
const std::string& endpoint_id,
sharing::mojom::AdvertisementPtr advertisement,
ShareTarget placeholder_share_target,
std::optional<NearbyShareDecryptedPublicCertificate> certificate) {
NearbyConnection* connection = GetConnection(placeholder_share_target);
if (!connection) {
RecordNearbyShareError(
NearbyShareError::kIncomingDecryptedCertificateInvalidConnection);
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Invalid connection for endpoint id - " << endpoint_id;
return;
}
// Remove placeholder share target since we are creating the actual share
// target below.
incoming_share_target_info_map_.erase(placeholder_share_target.id);
std::optional<ShareTarget> share_target = CreateShareTarget(
endpoint_id, advertisement, std::move(certificate), /*is_incoming=*/true);
if (!share_target) {
RecordNearbyShareError(
NearbyShareError::
kIncomingDecryptedCertificateFailedToCreateShareTarget);
CD_LOG(WARNING, Feature::NS)
<< __func__
<< ": Failed to convert advertisement to share target for "
"incoming connection, disconnecting";
AbortAndCloseConnectionIfNecessary(
TransferMetadata::Status::kMissingShareTarget,
placeholder_share_target);
return;
}
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Received incoming connection from " << share_target->id;
for (auto& observer : observers_) {
observer.OnShareTargetConnected(share_target.value());
}
ShareTargetInfo* share_target_info = GetShareTargetInfo(*share_target);
DCHECK(share_target_info);
share_target_info->set_connection(connection);
share_target_info->set_transfer_update_callback(
std::make_unique<TransferUpdateDecorator>(base::BindRepeating(
&NearbySharingServiceImpl::OnIncomingTransferUpdate,
weak_ptr_factory_.GetWeakPtr())));
connection->SetDisconnectionListener(
base::BindOnce(&NearbySharingServiceImpl::UnregisterShareTarget,
weak_ptr_factory_.GetWeakPtr(), *share_target));
std::optional<std::string> four_digit_token = ToFourDigitString(
nearby_connections_manager_->GetRawAuthenticationToken(endpoint_id));
RunPairedKeyVerification(
*share_target, endpoint_id,
base::BindOnce(
&NearbySharingServiceImpl::OnIncomingConnectionKeyVerificationDone,
weak_ptr_factory_.GetWeakPtr(), *share_target,
std::move(four_digit_token)));
}
void NearbySharingServiceImpl::RunPairedKeyVerification(
const ShareTarget& share_target,
const std::string& endpoint_id,
base::OnceCallback<void(
PairedKeyVerificationRunner::PairedKeyVerificationResult)> callback) {
DCHECK(profile_);
std::optional<std::vector<uint8_t>> token =
nearby_connections_manager_->GetRawAuthenticationToken(endpoint_id);
if (!token) {
RecordNearbyShareError(
NearbyShareError::
kRunPairedKeyVerificationFailedToReadAuthenticationToken);
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Failed to read authentication token from endpoint - "
<< endpoint_id;
std::move(callback).Run(
PairedKeyVerificationRunner::PairedKeyVerificationResult::kFail);
return;
}
ShareTargetInfo* share_target_info = GetShareTargetInfo(share_target);
DCHECK(share_target_info);
share_target_info->set_frames_reader(std::make_unique<IncomingFramesReader>(
process_manager_, share_target_info->connection()));
bool restrict_to_contacts =
features::IsRestrictToContactsEnabled() && share_target.is_incoming &&
advertising_power_level_ !=
NearbyConnectionsManager::PowerLevel::kHighPower;
share_target_info->set_key_verification_runner(
std::make_unique<PairedKeyVerificationRunner>(
share_target, endpoint_id, *token, share_target_info->connection(),
share_target_info->certificate(), GetCertificateManager(),
settings_.GetVisibility(), restrict_to_contacts,
share_target_info->frames_reader(), kReadFramesTimeout));
share_target_info->key_verification_runner()->Run(std::move(callback));
}
void NearbySharingServiceImpl::OnIncomingConnectionKeyVerificationDone(
ShareTarget share_target,
std::optional<std::string> four_digit_token,
PairedKeyVerificationRunner::PairedKeyVerificationResult result) {
ShareTargetInfo* info = GetShareTargetInfo(share_target);
if (!info || !info->connection() || !info->endpoint_id()) {
RecordNearbyShareError(
NearbyShareError::
kIncomingConnectionKeyVerificationInvalidConnectionOrEndpointId);
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Invalid connection or endpoint id";
return;
}
switch (result) {
case PairedKeyVerificationRunner::PairedKeyVerificationResult::kFail:
RecordNearbyShareError(
NearbyShareError::kIncomingConnectionKeyVerificationFailed);
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Paired key handshake failed for target "
<< share_target.id << ". Disconnecting.";
AbortAndCloseConnectionIfNecessary(
TransferMetadata::Status::kPairedKeyVerificationFailed, share_target);
return;
case PairedKeyVerificationRunner::PairedKeyVerificationResult::kSuccess:
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Paired key handshake succeeded for target - "
<< share_target.id;
CHECK(info->endpoint_id().has_value());
transfer_profiler_->OnPairedKeyHandshakeComplete(
info->endpoint_id().value());
// Upgrade bandwidth regardless of advertising visibility because the
// sender's identity has been confirmed; the stable identifiers
// potentially exposed by performing a bandwidth upgrade are no longer a
// concern.
nearby_connections_manager_->UpgradeBandwidth(*info->endpoint_id());
ReceiveIntroduction(share_target, /*four_digit_token=*/std::nullopt);
break;
case PairedKeyVerificationRunner::PairedKeyVerificationResult::kUnable:
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Unable to verify paired key encryption when "
"receiving connection from target - "
<< share_target.id;
CHECK(info->endpoint_id().has_value());
transfer_profiler_->OnPairedKeyHandshakeComplete(
info->endpoint_id().value());
if (advertising_power_level_ ==
NearbyConnectionsManager::PowerLevel::kHighPower) {
// Upgrade bandwidth if advertising at high-visibility. Bandwidth
// upgrades may expose stable identifiers, but this isn't a concern
// here because high-visibility already leaks the device name.
nearby_connections_manager_->UpgradeBandwidth(*info->endpoint_id());
}
if (four_digit_token) {
info->set_token(*four_digit_token);
}
ReceiveIntroduction(share_target, std::move(four_digit_token));
break;
case PairedKeyVerificationRunner::PairedKeyVerificationResult::kUnknown:
RecordNearbyShareError(
NearbyShareError::kIncomingConnectionKeyVerificationUnknownResult);
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Unknown PairedKeyVerificationResult for target "
<< share_target.id << ". Disconnecting.";
AbortAndCloseConnectionIfNecessary(
TransferMetadata::Status::kPairedKeyVerificationFailed, share_target);
break;
}
}
void NearbySharingServiceImpl::OnOutgoingConnectionKeyVerificationDone(
const ShareTarget& share_target,
std::optional<std::string> four_digit_token,
PairedKeyVerificationRunner::PairedKeyVerificationResult result) {
ShareTargetInfo* info = GetShareTargetInfo(share_target);
if (!info || !info->connection()) {
RecordNearbyShareError(
NearbyShareError::kOutgoingConnectionKeyVerificationMissingConnection);
return;
}
if (!info->transfer_update_callback()) {
RecordNearbyShareError(
NearbyShareError::
kOutgoingConnectionKeyVerificationMissingTransferUpdateCallback);
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": No transfer update callback. Disconnecting.";
AbortAndCloseConnectionIfNecessary(
TransferMetadata::Status::kMissingTransferUpdateCallback, share_target);
return;
}
// TODO(crbug.com/1119279): Check if we need to set this to false for
// Advanced Protection users.
bool sender_skips_confirmation = true;
switch (result) {
case PairedKeyVerificationRunner::PairedKeyVerificationResult::kFail:
RecordNearbyShareError(
NearbyShareError::kOutgoingConnectionKeyVerificationFailed);
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Paired key handshake failed for target "
<< share_target.id << ". Disconnecting.";
AbortAndCloseConnectionIfNecessary(
TransferMetadata::Status::kPairedKeyVerificationFailed, share_target);
return;
case PairedKeyVerificationRunner::PairedKeyVerificationResult::kSuccess:
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Paired key handshake succeeded for target - "
<< share_target.id;
SendIntroduction(share_target, /*four_digit_token=*/std::nullopt);
SendPayloads(share_target);
return;
case PairedKeyVerificationRunner::PairedKeyVerificationResult::kUnable:
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Unable to verify paired key encryption when "
"initating connection to target - "
<< share_target.id;
if (four_digit_token) {
info->set_token(*four_digit_token);
}
if (sender_skips_confirmation) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Sender-side verification is disabled. Skipping "
"token comparison with "
<< share_target.id;
SendIntroduction(share_target, /*four_digit_token=*/std::nullopt);
SendPayloads(share_target);
} else {
SendIntroduction(share_target, std::move(four_digit_token));
}
return;
case PairedKeyVerificationRunner::PairedKeyVerificationResult::kUnknown:
RecordNearbyShareError(
NearbyShareError::kOutgoingConnectionKeyVerificationUnknownResult);
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Unknown PairedKeyVerificationResult for target "
<< share_target.id << ". Disconnecting.";
AbortAndCloseConnectionIfNecessary(
TransferMetadata::Status::kPairedKeyVerificationFailed, share_target);
break;
}
}
void NearbySharingServiceImpl::RefreshUIOnDisconnection(
ShareTarget share_target) {
ShareTargetInfo* info = GetShareTargetInfo(share_target);
if (info && info->transfer_update_callback()) {
info->transfer_update_callback()->OnTransferUpdate(
share_target,
TransferMetadataBuilder()
.set_status(
TransferMetadata::Status::kAwaitingRemoteAcceptanceFailed)
.build());
}
UnregisterShareTarget(share_target);
}
void NearbySharingServiceImpl::ReceiveIntroduction(
ShareTarget share_target,
std::optional<std::string> four_digit_token) {
CD_LOG(INFO, Feature::NS)
<< __func__ << ": Receiving introduction from " << share_target.id;
ShareTargetInfo* info = GetShareTargetInfo(share_target);
DCHECK(info && info->connection());
CHECK(info->endpoint_id().has_value());
transfer_profiler_->OnIntroductionFrameReceived(info->endpoint_id().value());
info->frames_reader()->ReadFrame(
sharing::mojom::V1Frame::Tag::kIntroduction,
base::BindOnce(&NearbySharingServiceImpl::OnReceivedIntroduction,
weak_ptr_factory_.GetWeakPtr(), std::move(share_target),
std::move(four_digit_token)),
kReadFramesTimeout);
}
void NearbySharingServiceImpl::OnReceivedIntroduction(
ShareTarget share_target,
std::optional<std::string> four_digit_token,
std::optional<sharing::mojom::V1FramePtr> frame) {
ShareTargetInfo* info = GetShareTargetInfo(share_target);
if (!info || !info->connection()) {
RecordNearbyShareError(
NearbyShareError::kReceivedIntroductionMissingConnection);
CD_LOG(WARNING, Feature::NS)
<< __func__
<< ": Ignore received introduction, due to no connection established.";
return;
}
DCHECK(profile_);
if (!frame) {
RecordNearbyShareError(NearbyShareError::kReceivedIntroductionInvalidFrame);
AbortAndCloseConnectionIfNecessary(
TransferMetadata::Status::kInvalidIntroductionFrame, share_target);
CD_LOG(WARNING, Feature::NS) << __func__ << ": Invalid introduction frame";
return;
}
CD_LOG(INFO, Feature::NS)
<< __func__ << ": Successfully read the introduction frame.";
base::CheckedNumeric<int64_t> file_size_sum(0);
int64_t transfer_size = 0;
sharing::mojom::IntroductionFramePtr introduction_frame =
std::move((*frame)->get_introduction());
for (const auto& file : introduction_frame->file_metadata) {
if (file->size <= 0) {
RecordNearbyShareError(
NearbyShareError::kReceivedIntroductionInvalidAttachmentSize);
Fail(share_target, TransferMetadata::Status::kUnsupportedAttachmentType);
CD_LOG(WARNING, Feature::NS)
<< __func__
<< ": Ignore introduction, due to invalid attachment size";
return;
}
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Found file attachment: id=" << file->id
<< ", type= " << file->type << ", size=" << file->size
<< ", payload_id=" << file->payload_id
<< ", mime_type=" << file->mime_type;
FileAttachment attachment(file->id, file->size, file->name, file->mime_type,
file->type);
SetAttachmentPayloadId(attachment, file->payload_id);
share_target.file_attachments.push_back(std::move(attachment));
file_size_sum += file->size;
transfer_size += file->size;
if (!file_size_sum.IsValid()) {
RecordNearbyShareError(
NearbyShareError::kReceivedIntroductionTotalFileSizeOverflow);
Fail(share_target, TransferMetadata::Status::kNotEnoughSpace);
CD_LOG(WARNING, Feature::NS)
<< __func__
<< ": Ignoring introduction, total file size overflowed "
"64 bit integer.";
return;
}
}
for (const auto& text : introduction_frame->text_metadata) {
transfer_size += text->size;
if (text->size <= 0) {
RecordNearbyShareError(
NearbyShareError::kReceivedIntroductionInvalidTextAttachmentSize);
Fail(share_target, TransferMetadata::Status::kUnsupportedAttachmentType);
CD_LOG(WARNING, Feature::NS)
<< __func__
<< ": Ignore introduction, due to invalid attachment size";
return;
}
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Found text attachment: id=" << text->id
<< ", type= " << text->type << ", size=" << text->size
<< ", payload_id=" << text->payload_id;
TextAttachment attachment(text->id, text->type, text->text_title,
text->size);
SetAttachmentPayloadId(attachment, text->payload_id);
share_target.text_attachments.push_back(std::move(attachment));
}
for (const auto& wifi_credentials :
introduction_frame->wifi_credentials_metadata) {
if (wifi_credentials->ssid.empty()) {
RecordNearbyShareError(
NearbyShareError::kReceivedIntroductionInvalidWifiSSID);
Fail(share_target, TransferMetadata::Status::kUnsupportedAttachmentType);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": Ignore introduction, due to invalid Wi-Fi SSID";
return;
}
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Found Wi-Fi Credentials: id=" << wifi_credentials->id
<< ", payload_id=" << wifi_credentials->payload_id
<< ", security_type=" << wifi_credentials->security_type;
WifiCredentialsAttachment attachment(wifi_credentials->id,
wifi_credentials->security_type,
wifi_credentials->ssid);
SetAttachmentPayloadId(attachment, wifi_credentials->payload_id);
share_target.wifi_credentials_attachments.push_back(std::move(attachment));
}
if (!share_target.has_attachments()) {
RecordNearbyShareError(
NearbyShareError::kReceivedIntroductionShareTargetNoAttachment);
CD_LOG(WARNING, Feature::NS)
<< __func__
<< ": No attachment is found for this share target. It can "
"be result of unrecognizable attachment type";
Fail(share_target, TransferMetadata::Status::kUnsupportedAttachmentType);
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": We don't support the attachments sent by the sender. "
"We have informed "
<< share_target.id;
return;
}
if (file_size_sum.ValueOrDie() == 0) {
OnStorageCheckCompleted(std::move(share_target),
std::move(four_digit_token),
/*is_out_of_storage=*/false);
return;
}
CHECK(info->endpoint_id().has_value());
transfer_size_map_[info->endpoint_id().value()] = transfer_size;
base::FilePath download_path =
DownloadPrefs::FromDownloadManager(profile_->GetDownloadManager())
->DownloadPath();
base::ThreadPool::PostTaskAndReplyWithResult(
FROM_HERE, {base::MayBlock()},
base::BindOnce(&IsOutOfStorage, std::move(download_path),
file_size_sum.ValueOrDie(), free_disk_space_for_testing_),
base::BindOnce(&NearbySharingServiceImpl::OnStorageCheckCompleted,
weak_ptr_factory_.GetWeakPtr(), std::move(share_target),
std::move(four_digit_token)));
}
void NearbySharingServiceImpl::ReceiveConnectionResponse(
ShareTarget share_target) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Receiving response frame from " << share_target.id;
ShareTargetInfo* info = GetShareTargetInfo(share_target);
DCHECK(info && info->connection());
info->frames_reader()->ReadFrame(
sharing::mojom::V1Frame::Tag::kConnectionResponse,
base::BindOnce(&NearbySharingServiceImpl::OnReceiveConnectionResponse,
weak_ptr_factory_.GetWeakPtr(), std::move(share_target)),
kReadResponseFrameTimeout);
}
void NearbySharingServiceImpl::OnReceiveConnectionResponse(
ShareTarget share_target,
std::optional<sharing::mojom::V1FramePtr> frame) {
OutgoingShareTargetInfo* info = GetOutgoingShareTargetInfo(share_target);
if (!info || !info->connection()) {
RecordNearbyShareError(
NearbyShareError::kReceiveConnectionResponseMissingConnection);
CD_LOG(WARNING, Feature::NS)
<< __func__
<< ": Ignore received connection response, due to no "
"connection established.";
return;
}
if (!info->transfer_update_callback()) {
RecordNearbyShareError(
NearbyShareError::
kReceiveConnectionResponseMissingTransferUpdateCallback);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": No transfer update callback. Disconnecting.";
AbortAndCloseConnectionIfNecessary(
TransferMetadata::Status::kMissingTransferUpdateCallback, share_target);
return;
}
if (!frame) {
RecordNearbyShareError(
NearbyShareError::kReceiveConnectionResponseInvalidFrame);
CD_LOG(WARNING, Feature::NS)
<< __func__
<< ": Failed to read a response from the remote device. Disconnecting.";
AbortAndCloseConnectionIfNecessary(
TransferMetadata::Status::kFailedToReadOutgoingConnectionResponse,
share_target);
return;
}
mutual_acceptance_timeout_alarm_.Cancel();
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Successfully read the connection response frame.";
sharing::mojom::ConnectionResponseFramePtr response =
std::move((*frame)->get_connection_response());
switch (response->status) {
case sharing::mojom::ConnectionResponseFrame::Status::kAccept: {
info->frames_reader()->ReadFrame(
base::BindOnce(&NearbySharingServiceImpl::OnFrameRead,
weak_ptr_factory_.GetWeakPtr(), share_target));
info->transfer_update_callback()->OnTransferUpdate(
share_target, TransferMetadataBuilder()
.set_status(TransferMetadata::Status::kInProgress)
.build());
info->set_payload_tracker(std::make_unique<PayloadTracker>(
share_target, attachment_info_map_,
base::BindRepeating(
&NearbySharingServiceImpl::OnPayloadTransferUpdate,
weak_ptr_factory_.GetWeakPtr())));
for (auto& payload : info->ExtractTextPayloads()) {
nearby_connections_manager_->Send(
*info->endpoint_id(), std::move(payload), info->payload_tracker());
}
for (auto& payload : info->ExtractFilePayloads()) {
nearby_connections_manager_->Send(
*info->endpoint_id(), std::move(payload), info->payload_tracker());
}
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": The connection was accepted. Payloads are now being sent.";
CHECK(info->endpoint_id().has_value());
transfer_profiler_->OnSendStart(info->endpoint_id().value());
// Sender events
for (auto& observer : observers_) {
observer.OnTransferAccepted(share_target);
observer.OnTransferStarted(
share_target, transfer_size_map_[info->endpoint_id().value()]);
}
break;
}
case sharing::mojom::ConnectionResponseFrame::Status::kReject:
AbortAndCloseConnectionIfNecessary(TransferMetadata::Status::kRejected,
share_target);
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": The connection was rejected. The connection has been closed.";
break;
case sharing::mojom::ConnectionResponseFrame::Status::kNotEnoughSpace:
RecordNearbyShareError(
NearbyShareError::kReceiveConnectionResponseNotEnoughSpace);
AbortAndCloseConnectionIfNecessary(
TransferMetadata::Status::kNotEnoughSpace, share_target);
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": The connection was rejected because the remote device "
"does not have enough space for our attachments. The "
"connection has been closed.";
break;
case sharing::mojom::ConnectionResponseFrame::Status::
kUnsupportedAttachmentType:
RecordNearbyShareError(
NearbyShareError::
kReceiveConnectionResponseUnsupportedAttachmentType);
AbortAndCloseConnectionIfNecessary(
TransferMetadata::Status::kUnsupportedAttachmentType, share_target);
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": The connection was rejected because the remote device "
"does not support the attachments we were sending. The "
"connection has been closed.";
break;
case sharing::mojom::ConnectionResponseFrame::Status::kTimedOut:
RecordNearbyShareError(
NearbyShareError::kReceiveConnectionResponseTimedOut);
AbortAndCloseConnectionIfNecessary(TransferMetadata::Status::kTimedOut,
share_target);
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": The connection was rejected because the remote device "
"timed out. The connection has been closed.";
break;
default:
RecordNearbyShareError(
NearbyShareError::kReceiveConnectionResponseConnectionFailed);
AbortAndCloseConnectionIfNecessary(TransferMetadata::Status::kFailed,
share_target);
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": The connection failed. The connection has been closed.";
break;
}
}
void NearbySharingServiceImpl::OnStorageCheckCompleted(
ShareTarget share_target,
std::optional<std::string> four_digit_token,
bool is_out_of_storage) {
if (is_out_of_storage) {
RecordNearbyShareError(
NearbyShareError::kStorageCheckCompletedNotEnoughSpace);
Fail(share_target, TransferMetadata::Status::kNotEnoughSpace);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": Not enough space on the receiver. We have informed "
<< share_target.id;
return;
}
ShareTargetInfo* info = GetShareTargetInfo(share_target);
if (!info || !info->connection()) {
RecordNearbyShareError(
NearbyShareError::kStorageCheckCompletedMissingConnection);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": Invalid connection for share target - "
<< share_target.id;
return;
}
NearbyConnection* connection = info->connection();
if (!info->transfer_update_callback()) {
RecordNearbyShareError(
NearbyShareError::kStorageCheckCompletedMissingTransferUpdateCallback);
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": No transfer update callback. Disconnecting.";
AbortAndCloseConnectionIfNecessary(
TransferMetadata::Status::kMissingTransferUpdateCallback, share_target);
return;
}
mutual_acceptance_timeout_alarm_.Reset(base::BindOnce(
&NearbySharingServiceImpl::OnIncomingMutualAcceptanceTimeout,
weak_ptr_factory_.GetWeakPtr(), share_target));
base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE, base::BindOnce(mutual_acceptance_timeout_alarm_.callback()),
kReadResponseFrameTimeout);
info->transfer_update_callback()->OnTransferUpdate(
share_target,
TransferMetadataBuilder()
.set_status(TransferMetadata::Status::kAwaitingLocalConfirmation)
.set_token(std::move(four_digit_token))
.build());
if (!incoming_share_target_info_map_.count(share_target.id)) {
RecordNearbyShareError(
NearbyShareError::kStorageCheckCompletedNoIncomingShareTarget);
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": IncomingShareTarget not found, disconnecting "
<< share_target.id;
AbortAndCloseConnectionIfNecessary(
TransferMetadata::Status::kMissingShareTarget, share_target);
return;
}
connection->SetDisconnectionListener(base::BindOnce(
&NearbySharingServiceImpl::OnIncomingConnectionDisconnected,
weak_ptr_factory_.GetWeakPtr(), share_target));
auto* frames_reader = info->frames_reader();
if (!frames_reader) {
RecordNearbyShareError(
NearbyShareError::kStorageCheckCompletedNoFramesReader);
CD_LOG(WARNING, Feature::NS)
<< __func__
<< ": Stopped reading further frames, due to no connection "
"established.";
return;
}
// Auto-accept self shares when not in high-visibility mode, unless the
// filetype includes WiFi credentials.
if (share_target.CanAutoAccept() && !IsInHighVisibility()) {
CD_LOG(INFO, Feature::NS) << __func__ << ": Auto-accepting self share.";
Accept(share_target, base::DoNothing());
} else {
CD_LOG(INFO, Feature::NS) << __func__ << ": Can't auto-accept transfer.";
}
frames_reader->ReadFrame(
base::BindOnce(&NearbySharingServiceImpl::OnFrameRead,
weak_ptr_factory_.GetWeakPtr(), std::move(share_target)));
}
void NearbySharingServiceImpl::OnFrameRead(
ShareTarget share_target,
std::optional<sharing::mojom::V1FramePtr> frame) {
if (!frame) {
// This is the case when the connection has been closed since we wait
// indefinitely for incoming frames.
return;
}
sharing::mojom::V1FramePtr v1_frame = std::move(*frame);
switch (v1_frame->which()) {
case sharing::mojom::V1Frame::Tag::kCancelFrame:
CD_LOG(INFO, Feature::NS)
<< __func__ << ": Read the cancel frame, closing connection";
DoCancel(share_target, base::DoNothing(),
/*is_initiator_of_cancellation=*/false);
break;
case sharing::mojom::V1Frame::Tag::kCertificateInfo:
HandleCertificateInfoFrame(v1_frame->get_certificate_info());
break;
default:
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Discarding unknown frame of type";
break;
}
ShareTargetInfo* info = GetShareTargetInfo(share_target);
if (!info || !info->frames_reader()) {
RecordNearbyShareError(NearbyShareError::kFrameReadNoFrameReader);
CD_LOG(WARNING, Feature::NS)
<< __func__
<< ": Stopped reading further frames, due to no connection "
"established.";
return;
}
info->frames_reader()->ReadFrame(
base::BindOnce(&NearbySharingServiceImpl::OnFrameRead,
weak_ptr_factory_.GetWeakPtr(), std::move(share_target)));
}
void NearbySharingServiceImpl::HandleCertificateInfoFrame(
const sharing::mojom::CertificateInfoFramePtr& certificate_frame) {
DCHECK(certificate_frame);
// TODO(crbug.com/1113858): Allow saving certificates from remote devices.
}
void NearbySharingServiceImpl::OnIncomingConnectionDisconnected(
const ShareTarget& share_target) {
ShareTargetInfo* info = GetShareTargetInfo(share_target);
if (info && info->transfer_update_callback()) {
info->transfer_update_callback()->OnTransferUpdate(
share_target,
TransferMetadataBuilder()
.set_status(TransferMetadata::Status::kUnexpectedDisconnection)
.build());
}
UnregisterShareTarget(share_target);
}
void NearbySharingServiceImpl::OnOutgoingConnectionDisconnected(
const ShareTarget& share_target) {
ShareTargetInfo* info = GetShareTargetInfo(share_target);
if (info && info->transfer_update_callback()) {
info->transfer_update_callback()->OnTransferUpdate(
share_target,
TransferMetadataBuilder()
.set_status(TransferMetadata::Status::kUnexpectedDisconnection)
.build());
}
UnregisterShareTarget(share_target);
}
void NearbySharingServiceImpl::OnIncomingMutualAcceptanceTimeout(
const ShareTarget& share_target) {
DCHECK(share_target.is_incoming);
RecordNearbyShareError(NearbyShareError::kIncomingMutualAcceptanceTimeout);
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Incoming mutual acceptance timed out, closing connection for "
<< share_target.id;
Fail(share_target, TransferMetadata::Status::kTimedOut);
}
void NearbySharingServiceImpl::OnOutgoingMutualAcceptanceTimeout(
const ShareTarget& share_target) {
DCHECK(!share_target.is_incoming);
RecordNearbyShareError(NearbyShareError::kOutgoingMutualAcceptanceTimeout);
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Outgoing mutual acceptance timed out, closing connection for "
<< share_target.id;
AbortAndCloseConnectionIfNecessary(TransferMetadata::Status::kTimedOut,
share_target);
}
std::optional<ShareTarget> NearbySharingServiceImpl::CreateShareTarget(
const std::string& endpoint_id,
const sharing::mojom::AdvertisementPtr& advertisement,
std::optional<NearbyShareDecryptedPublicCertificate> certificate,
bool is_incoming) {
DCHECK(advertisement);
if (!advertisement->device_name && !certificate) {
RecordNearbyShareError(
NearbyShareError::kCreateShareTargetFailedToRetreivePublicCertificate);
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Failed to retrieve public certificate for contact "
"only advertisement.";
return std::nullopt;
}
std::optional<std::string> device_name =
GetDeviceName(advertisement, certificate);
if (!device_name) {
RecordNearbyShareError(
NearbyShareError::kCreateShareTargetFailedToRetreiveDeviceName);
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Failed to retrieve device name for advertisement.";
return std::nullopt;
}
ShareTarget target;
target.type = advertisement->device_type;
target.device_name = std::move(*device_name);
target.is_incoming = is_incoming;
target.device_id = GetDeviceId(endpoint_id, certificate);
target.for_self_share = certificate && certificate->for_self_share();
ShareTargetInfo& info = GetOrCreateShareTargetInfo(target, endpoint_id);
if (certificate) {
if (certificate->unencrypted_metadata().has_full_name()) {
target.full_name = certificate->unencrypted_metadata().full_name();
}
if (certificate->unencrypted_metadata().has_icon_url()) {
target.image_url = GURL(certificate->unencrypted_metadata().icon_url());
}
target.is_known = true;
info.set_certificate(std::move(*certificate));
}
share_target_map_[endpoint_id] = target;
for (auto& observer : observers_) {
observer.OnShareTargetAdded(target);
}
return target;
}
void NearbySharingServiceImpl::OnPayloadTransferUpdate(
ShareTarget share_target,
TransferMetadata metadata) {
bool is_in_progress =
metadata.status() == TransferMetadata::Status::kInProgress;
if (is_in_progress && share_target.is_incoming &&
is_waiting_to_record_accept_to_transfer_start_metric_) {
RecordNearbyShareTimeFromLocalAcceptToTransferStartMetric(
base::TimeTicks::Now() - incoming_share_accepted_timestamp_);
is_waiting_to_record_accept_to_transfer_start_metric_ = false;
}
// kInProgress status is logged extensively elsewhere so avoid the spam.
if (!is_in_progress) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Nearby Share service: "
<< "Payload transfer update for share target with ID "
<< share_target.id << ": "
<< TransferMetadata::StatusToString(metadata.status());
}
if (metadata.status() == TransferMetadata::Status::kComplete &&
share_target.is_incoming) {
if (!OnIncomingPayloadsComplete(share_target)) {
metadata = TransferMetadataBuilder()
.set_status(TransferMetadata::Status::kIncompletePayloads)
.build();
// Reset file paths for file attachments.
for (auto& file : share_target.file_attachments) {
file.set_file_path(std::nullopt);
}
// Reset body of text attachments.
for (auto& text : share_target.text_attachments) {
text.set_text_body(std::string());
}
}
fast_initiation_scanner_cooldown_timer_.Start(
FROM_HERE, kFastInitiationScannerCooldown,
base::BindRepeating(
&NearbySharingServiceImpl::InvalidateFastInitiationScanning,
base::Unretained(this)));
}
// Make sure to call this before calling Disconnect or we risk losing some
// transfer updates in the receive case due to the Disconnect call cleaning up
// share targets.
ShareTargetInfo* info = GetShareTargetInfo(share_target);
if (info && info->transfer_update_callback()) {
info->transfer_update_callback()->OnTransferUpdate(share_target, metadata);
}
// Cancellation has its own disconnection strategy, possibly adding a delay
// before disconnection to provide the other party time to process the
// cancellation.
if (TransferMetadata::IsFinalStatus(metadata.status()) &&
metadata.status() != TransferMetadata::Status::kCancelled) {
if (share_target.has_attachments() &&
share_target.file_attachments.size()) {
// For file payloads, the |PayloadTracker| callback for updates is
// |OnTransferUpdate| which will set status |kComplete| if payload reading
// is successful.
const bool files_read_success =
(metadata.status() == TransferMetadata::Status::kComplete);
RecordNearbySharePayloadFileOperationMetrics(profile_, share_target,
PayloadFileOperation::kRead,
files_read_success);
}
Disconnect(share_target, metadata);
}
}
bool NearbySharingServiceImpl::OnIncomingPayloadsComplete(
ShareTarget& share_target) {
DCHECK(share_target.is_incoming);
ShareTargetInfo* info = GetShareTargetInfo(share_target);
if (!info || !info->connection()) {
RecordNearbyShareError(
NearbyShareError::kIncomingPayloadsCompleteMissingConnection);
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Connection not found for target - "
<< share_target.id;
return false;
}
NearbyConnection* connection = info->connection();
connection->SetDisconnectionListener(
base::BindOnce(&NearbySharingServiceImpl::UnregisterShareTarget,
weak_ptr_factory_.GetWeakPtr(), share_target));
for (auto& file : share_target.file_attachments) {
AttachmentInfo& attachment_info = attachment_info_map_[file.id()];
std::optional<int64_t> payload_id = attachment_info.payload_id;
if (!payload_id) {
RecordNearbyShareError(
NearbyShareError::kIncomingPayloadsCompleteMissingPayloadId);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": No payload id found for file - " << file.id();
return false;
}
nearby::connections::mojom::Payload* incoming_payload =
nearby_connections_manager_->GetIncomingPayload(*payload_id);
if (!incoming_payload || !incoming_payload->content ||
!incoming_payload->content->is_file()) {
RecordNearbyShareError(
NearbyShareError::kIncomingPayloadsCompleteMissingPayload);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": No payload found for file - " << file.id();
return false;
}
file.set_file_path(attachment_info.file_path);
}
for (auto& text : share_target.text_attachments) {
AttachmentInfo& attachment_info = attachment_info_map_[text.id()];
std::optional<int64_t> payload_id = attachment_info.payload_id;
if (!payload_id) {
RecordNearbyShareError(
NearbyShareError::kIncomingPayloadsCompleteMissingTextPayloadId);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": No payload id found for text - " << text.id();
return false;
}
nearby::connections::mojom::Payload* incoming_payload =
nearby_connections_manager_->GetIncomingPayload(*payload_id);
if (!incoming_payload || !incoming_payload->content ||
!incoming_payload->content->is_bytes()) {
RecordNearbyShareError(
NearbyShareError::kIncomingPayloadsCompleteMissingTextPayload);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": No payload found for text - " << text.id();
return false;
}
std::vector<uint8_t>& bytes = incoming_payload->content->get_bytes()->bytes;
if (bytes.empty()) {
RecordNearbyShareError(
NearbyShareError::kIncomingPayloadsCompleteTextPayloadEmptyBytes);
CD_LOG(WARNING, Feature::NS)
<< __func__
<< ": Incoming bytes is empty for text payload with payload_id - "
<< *payload_id;
return false;
}
std::string text_body(bytes.begin(), bytes.end());
text.set_text_body(text_body);
attachment_info.text_body = std::move(text_body);
}
for (auto& wifi_credentials : share_target.wifi_credentials_attachments) {
AttachmentInfo& attachment_info =
attachment_info_map_[wifi_credentials.id()];
std::optional<int64_t> payload_id = attachment_info.payload_id;
if (!payload_id) {
RecordNearbyShareError(
NearbyShareError::kIncomingPayloadsCompleteMissingWifiPayloadId);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": No payload id found for wifi credentials - "
<< wifi_credentials.id();
return false;
}
nearby::connections::mojom::Payload* incoming_payload =
nearby_connections_manager_->GetIncomingPayload(*payload_id);
if (!incoming_payload || !incoming_payload->content ||
!incoming_payload->content->is_bytes()) {
RecordNearbyShareError(
NearbyShareError::kIncomingPayloadsCompleteMissingWifiPayload);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": No payload found for Wi-Fi credentials - "
<< wifi_credentials.id();
return false;
}
const std::vector<uint8_t>& bytes =
incoming_payload->content->get_bytes()->bytes;
if (bytes.empty()) {
RecordNearbyShareError(
NearbyShareError::kIncomingPayloadsCompleteWifiPayloadEmptyBytes);
CD_LOG(WARNING, Feature::NS)
<< __func__
<< ": Incoming bytes is empty for Wi-Fi password with payload_id - "
<< *payload_id;
return false;
}
sharing::nearby::WifiCredentials credentials_proto;
if (!credentials_proto.ParseFromArray(bytes.data(), bytes.size())) {
RecordNearbyShareError(
NearbyShareError::kIncomingPayloadsCompleteWifiFailedToParse);
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": Failed to parse Wi-Fi credentials proto.";
return false;
}
if (credentials_proto.password().empty()) {
RecordNearbyShareError(
NearbyShareError::kIncomingPayloadsCompleteWifiNoPassword);
CD_LOG(WARNING, Feature::NS) << __func__ << ": No Wi-Fi password found.";
return false;
}
if (credentials_proto.has_hidden_ssid() &&
credentials_proto.hidden_ssid()) {
RecordNearbyShareError(
NearbyShareError::kIncomingPayloadsCompleteWifiHiddenNetwork);
CD_LOG(WARNING, Feature::NS) << __func__ << ": Network is hidden.";
return false;
}
std::string wifi_password(credentials_proto.password());
wifi_credentials.set_wifi_password(wifi_password);
// Automatically set up the Wi-Fi network for the user.
wifi_network_handler_->ConfigureWifiNetwork(wifi_credentials,
base::DoNothing());
}
return true;
}
void NearbySharingServiceImpl::RemoveIncomingPayloads(
ShareTarget share_target) {
if (!share_target.is_incoming) {
return;
}
CD_LOG(INFO, Feature::NS)
<< __func__
<< ": Cleaning up payloads due to transfer cancelled or failure.";
nearby_connections_manager_->ClearIncomingPayloads();
std::vector<base::FilePath> files_for_deletion;
for (const auto& file : share_target.file_attachments) {
auto it = attachment_info_map_.find(file.id());
if (it == attachment_info_map_.end()) {
continue;
}
files_for_deletion.push_back(it->second.file_path);
}
file_handler_.DeleteFilesFromDisk(std::move(files_for_deletion));
}
void NearbySharingServiceImpl::Disconnect(const ShareTarget& share_target,
TransferMetadata metadata) {
ShareTargetInfo* share_target_info = GetShareTargetInfo(share_target);
if (!share_target_info) {
RecordNearbyShareError(
NearbyShareError::kDisconnectFailedToGetShareTargetInfo);
CD_LOG(WARNING, Feature::NS)
<< __func__
<< ": Failed to disconnect. No share target info found for target - "
<< share_target.id;
return;
}
std::optional<std::string> endpoint_id = share_target_info->endpoint_id();
if (!endpoint_id) {
RecordNearbyShareError(NearbyShareError::kDisconnectMissingEndpointId);
CD_LOG(WARNING, Feature::NS)
<< __func__
<< ": Failed to disconnect. No endpoint id found for share target - "
<< share_target.id;
return;
}
// Failed to send or receive. No point in continuing, so disconnect
// immediately.
if (metadata.status() != TransferMetadata::Status::kComplete) {
if (share_target_info->connection()) {
share_target_info->connection()->Close();
} else {
nearby_connections_manager_->Disconnect(*endpoint_id);
}
return;
}
// Files received successfully. Receivers can immediately cancel.
if (share_target.is_incoming) {
if (share_target_info->connection()) {
share_target_info->connection()->Close();
} else {
nearby_connections_manager_->Disconnect(*endpoint_id);
}
return;
}
// Disconnect after a timeout to make sure any pending payloads are sent.
auto timer = std::make_unique<base::CancelableOnceClosure>(base::BindOnce(
&NearbySharingServiceImpl::OnDisconnectingConnectionTimeout,
weak_ptr_factory_.GetWeakPtr(), *endpoint_id));
base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE, timer->callback(), kOutgoingDisconnectionDelay);
disconnection_timeout_alarms_[*endpoint_id] = std::move(timer);
// Stop the disconnection timeout if the connection has been closed already.
if (share_target_info->connection()) {
share_target_info->connection()->SetDisconnectionListener(base::BindOnce(
&NearbySharingServiceImpl::OnDisconnectingConnectionDisconnected,
weak_ptr_factory_.GetWeakPtr(), share_target, *endpoint_id));
}
}
void NearbySharingServiceImpl::OnDisconnectingConnectionTimeout(
const std::string& endpoint_id) {
disconnection_timeout_alarms_.erase(endpoint_id);
nearby_connections_manager_->Disconnect(endpoint_id);
}
void NearbySharingServiceImpl::OnDisconnectingConnectionDisconnected(
const ShareTarget& share_target,
const std::string& endpoint_id) {
disconnection_timeout_alarms_.erase(endpoint_id);
UnregisterShareTarget(share_target);
}
ShareTargetInfo& NearbySharingServiceImpl::GetOrCreateShareTargetInfo(
const ShareTarget& share_target,
const std::string& endpoint_id) {
if (share_target.is_incoming) {
auto& info = incoming_share_target_info_map_[share_target.id];
info.set_endpoint_id(endpoint_id);
return info;
} else {
// We need to explicitly remove any previous share target for
// |endpoint_id| if one exists, notifying observers that a share target is
// lost.
const auto it = outgoing_share_target_map_.find(endpoint_id);
if (it != outgoing_share_target_map_.end() &&
it->second.id != share_target.id) {
RemoveOutgoingShareTargetWithEndpointId(endpoint_id);
}
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Adding (endpoint_id=" << endpoint_id
<< ", share_target_id=" << share_target.id
<< ") to outgoing share target map";
outgoing_share_target_map_.insert_or_assign(endpoint_id, share_target);
auto& info = outgoing_share_target_info_map_[share_target.id];
info.set_endpoint_id(endpoint_id);
return info;
}
}
ShareTargetInfo* NearbySharingServiceImpl::GetShareTargetInfo(
const ShareTarget& share_target) {
if (share_target.is_incoming) {
return GetIncomingShareTargetInfo(share_target);
} else {
return GetOutgoingShareTargetInfo(share_target);
}
}
IncomingShareTargetInfo* NearbySharingServiceImpl::GetIncomingShareTargetInfo(
const ShareTarget& share_target) {
auto it = incoming_share_target_info_map_.find(share_target.id);
if (it == incoming_share_target_info_map_.end()) {
return nullptr;
}
return &it->second;
}
OutgoingShareTargetInfo* NearbySharingServiceImpl::GetOutgoingShareTargetInfo(
const ShareTarget& share_target) {
auto it = outgoing_share_target_info_map_.find(share_target.id);
if (it == outgoing_share_target_info_map_.end()) {
return nullptr;
}
return &it->second;
}
NearbyConnection* NearbySharingServiceImpl::GetConnection(
const ShareTarget& share_target) {
ShareTargetInfo* share_target_info = GetShareTargetInfo(share_target);
return share_target_info ? share_target_info->connection() : nullptr;
}
std::optional<std::vector<uint8_t>>
NearbySharingServiceImpl::GetBluetoothMacAddressForShareTarget(
const ShareTarget& share_target) {
ShareTargetInfo* info = GetShareTargetInfo(share_target);
if (!info) {
RecordNearbyShareError(
NearbyShareError::
kGetBluetoothMacAddressForShareTargetNoShareTargetInfo);
CD_LOG(ERROR, Feature::NS) << __func__ << ": No ShareTargetInfo found for "
<< "share target id: " << share_target.id;
return std::nullopt;
}
const std::optional<NearbyShareDecryptedPublicCertificate>& certificate =
info->certificate();
if (!certificate) {
RecordNearbyShareError(
NearbyShareError::
kGetBluetoothMacAddressForShareTargetNoDecryptedPublicCertificate);
CD_LOG(ERROR, Feature::NS)
<< __func__ << ": No decrypted public certificate found for "
<< "share target id: " << share_target.id;
return std::nullopt;
}
return GetBluetoothMacAddressFromCertificate(*certificate);
}
void NearbySharingServiceImpl::ClearOutgoingShareTargetInfoMap() {
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Clearing outgoing share target map.";
while (!outgoing_share_target_map_.empty()) {
RemoveOutgoingShareTargetWithEndpointId(
/*endpoint_id=*/outgoing_share_target_map_.begin()->first);
}
DCHECK(outgoing_share_target_map_.empty());
DCHECK(outgoing_share_target_info_map_.empty());
}
void NearbySharingServiceImpl::SetAttachmentPayloadId(
const Attachment& attachment,
int64_t payload_id) {
attachment_info_map_[attachment.id()].payload_id = payload_id;
}
std::optional<int64_t> NearbySharingServiceImpl::GetAttachmentPayloadId(
int64_t attachment_id) {
auto it = attachment_info_map_.find(attachment_id);
if (it == attachment_info_map_.end()) {
return std::nullopt;
}
return it->second.payload_id;
}
void NearbySharingServiceImpl::UnregisterShareTarget(
const ShareTarget& share_target) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Unregistering share target - " << share_target.id;
// For metrics.
all_cancelled_share_target_ids_.erase(share_target.id);
if (share_target.is_incoming) {
if (last_incoming_metadata_ &&
last_incoming_metadata_->first.id == share_target.id) {
last_incoming_metadata_.reset();
}
// Clear legacy incoming payloads to release resource.
nearby_connections_manager_->ClearIncomingPayloads();
incoming_share_target_info_map_.erase(share_target.id);
} else {
if (last_outgoing_metadata_ &&
last_outgoing_metadata_->first.id == share_target.id) {
last_outgoing_metadata_.reset();
}
// Find the endpoint id that matches the given share target.
std::optional<std::string> endpoint_id;
auto it = outgoing_share_target_info_map_.find(share_target.id);
if (it != outgoing_share_target_info_map_.end()) {
endpoint_id = it->second.endpoint_id();
}
// Be careful not to clear out the share target info map if a new session
// was started during the cancelation delay.
if (!is_scanning_ && !is_transferring_) {
// TODO(crbug/1108348): Support caching manager by keeping track of the
// share_target/endpoint_id for next time.
ClearOutgoingShareTargetInfoMap();
}
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": Unregister share target: " << share_target.id;
}
mutual_acceptance_timeout_alarm_.Cancel();
}
void NearbySharingServiceImpl::OnStartAdvertisingResult(
bool used_device_name,
NearbyConnectionsManager::ConnectionsStatus status) {
RecordNearbyShareStartAdvertisingResultMetric(
/*is_high_visibility=*/used_device_name, status);
if (status == NearbyConnectionsManager::ConnectionsStatus::kSuccess) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": StartAdvertising over Nearby Connections was successful.";
SetInHighVisibility(used_device_name);
} else {
RecordNearbyShareError(NearbyShareError::kStartAdvertisingFailed);
CD_LOG(ERROR, Feature::NS)
<< __func__ << ": StartAdvertising over Nearby Connections failed: "
<< NearbyConnectionsManager::ConnectionsStatusToString(status);
SetInHighVisibility(false);
for (auto& observer : observers_) {
observer.OnStartAdvertisingFailure();
}
}
}
void NearbySharingServiceImpl::OnStopAdvertisingResult(
NearbyConnectionsManager::ConnectionsStatus status) {
if (status == NearbyConnectionsManager::ConnectionsStatus::kSuccess) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": StopAdvertising over Nearby Connections was successful.";
} else {
RecordNearbyShareError(NearbyShareError::kStopAdvertisingFailed);
CD_LOG(ERROR, Feature::NS)
<< __func__ << ": StopAdvertising over Nearby Connections failed: "
<< NearbyConnectionsManager::ConnectionsStatusToString(status);
}
// The |advertising_power_level_| is set in |StopAdvertising| instead of here
// at the callback because when restarting advertising, |StartAdvertising| is
// called immediately after |StopAdvertising| without waiting for the
// callback. Nearby Connections queues the requests and completes them in
// order, so waiting for Stop to complete is unnecessary, but Start will fail
// if the |advertising_power_level_| indicates we are already advertising.
SetInHighVisibility(false);
}
void NearbySharingServiceImpl::OnStartDiscoveryResult(
NearbyConnectionsManager::ConnectionsStatus status) {
bool success =
status == NearbyConnectionsManager::ConnectionsStatus::kSuccess;
if (success) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": StartDiscovery over Nearby Connections was successful.";
// Periodically download certificates if there are discovered, contact-based
// advertisements that cannot decrypt any currently stored certificates.
ScheduleCertificateDownloadDuringDiscovery(/*attempt_count=*/0);
} else {
RecordNearbyShareError(NearbyShareError::kStartDiscoveryFailed);
CD_LOG(ERROR, Feature::NS)
<< __func__ << ": StartDiscovery over Nearby Connections failed: "
<< NearbyConnectionsManager::ConnectionsStatusToString(status);
}
for (auto& observer : observers_) {
observer.OnStartDiscoveryResult(success);
if (success) {
observer.OnShareTargetDiscoveryStarted();
}
}
}
void NearbySharingServiceImpl::SetInHighVisibility(
bool new_in_high_visibility) {
if (IsInHighVisibility() == new_in_high_visibility) {
return;
}
if (chromeos::features::IsQuickShareV2Enabled()) {
prefs_->SetBoolean(prefs::kNearbySharingInHighVisibilityPrefName,
/*value=*/new_in_high_visibility);
} else {
in_high_visibility_ = new_in_high_visibility;
}
for (auto& observer : observers_) {
observer.OnHighVisibilityChanged(new_in_high_visibility);
}
}
void NearbySharingServiceImpl::AbortAndCloseConnectionIfNecessary(
const TransferMetadata::Status status,
const ShareTarget& share_target) {
TransferMetadata metadata =
TransferMetadataBuilder().set_status(status).build();
ShareTargetInfo* info = GetShareTargetInfo(share_target);
// First invoke the appropriate transfer callback with the final |status|.
if (info && info->transfer_update_callback()) {
info->transfer_update_callback()->OnTransferUpdate(share_target, metadata);
} else if (share_target.is_incoming) {
OnIncomingTransferUpdate(share_target, metadata);
} else {
OnOutgoingTransferUpdate(share_target, metadata);
}
// Close connection if necessary.
if (info && info->connection()) {
// Ensure that the disconnect listener is set to UnregisterShareTarget
// because the other listenrs also try to record a final status metric.
info->connection()->SetDisconnectionListener(
base::BindOnce(&NearbySharingServiceImpl::UnregisterShareTarget,
weak_ptr_factory_.GetWeakPtr(), share_target));
info->connection()->Close();
}
}
void NearbySharingServiceImpl::UpdateVisibilityReminderTimer(
bool reset_timestamp) {
if (!settings_.GetEnabled() ||
!IsVisibleInBackground(settings_.GetVisibility())) {
visibility_reminder_timer_.Stop();
return;
}
if (reset_timestamp ||
prefs_->GetTime(prefs::kNearbySharingNextVisibilityReminderTimePrefName)
.is_null()) {
prefs_->SetTime(prefs::kNearbySharingNextVisibilityReminderTimePrefName,
base::Time::Now() + visibility_reminder_timer_delay_);
}
visibility_reminder_timer_.Start(
FROM_HERE, GetTimeUntilNextVisibilityReminder(),
base::BindOnce(&NearbySharingServiceImpl::OnVisibilityReminderTimerFired,
weak_ptr_factory_.GetWeakPtr()));
}
void NearbySharingServiceImpl::OnVisibilityReminderTimerFired() {
nearby_notification_manager_->ShowVisibilityReminder();
UpdateVisibilityReminderTimer(/*reset_timestamp=*/true);
}
// Calculate the actual time when next visibility reminder will be shown.
base::TimeDelta NearbySharingServiceImpl::GetTimeUntilNextVisibilityReminder() {
base::Time next_visibility_reminder_time =
prefs_->GetTime(prefs::kNearbySharingNextVisibilityReminderTimePrefName);
base::TimeDelta time_until_next_reminder =
next_visibility_reminder_time - base::Time::Now();
// Immediately show visibility reminder if it's already passed 180 days since
// last time user saw the reminder.
return std::max(base::Seconds(0), time_until_next_reminder);
}
|