1 /*
2  * Copyright (C) 2021 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.android.server.am;
17 
18 import android.app.ActivityThread;
19 import android.content.ContentResolver;
20 import android.provider.Settings;
21 import android.util.ArrayMap;
22 
23 import com.android.internal.annotations.GuardedBy;
24 import com.android.internal.annotations.VisibleForTesting;
25 
26 import java.security.MessageDigest;
27 import java.security.NoSuchAlgorithmException;
28 
29 /**
30  * To store random utility methods...
31  */
32 public class ActivityManagerUtils {
ActivityManagerUtils()33     private ActivityManagerUtils() {
34     }
35 
36     private static Integer sAndroidIdHash;
37 
38     @GuardedBy("sHashCache")
39     private static final ArrayMap<String, Integer> sHashCache = new ArrayMap<>();
40 
41     private static String sInjectedAndroidId;
42 
43     /** Used by the unit tests to inject an android ID. Do not set in the prod code. */
44     @VisibleForTesting
injectAndroidIdForTest(String androidId)45     static void injectAndroidIdForTest(String androidId) {
46         sInjectedAndroidId = androidId;
47         sAndroidIdHash = null;
48     }
49 
50     /**
51      * Return a hash between [0, MAX_VALUE] generated from the android ID.
52      */
53     @VisibleForTesting
getAndroidIdHash()54     static int getAndroidIdHash() {
55         // No synchronization is required. Double-initialization is fine here.
56         if (sAndroidIdHash == null) {
57             final ContentResolver resolver = ActivityThread.currentApplication()
58                                              .getContentResolver();
59             final String androidId = Settings.Secure.getStringForUser(
60                     resolver,
61                     Settings.Secure.ANDROID_ID,
62                     resolver.getUserId());
63             sAndroidIdHash = getUnsignedHashUnCached(
64                     sInjectedAndroidId != null ? sInjectedAndroidId : androidId);
65         }
66         return sAndroidIdHash;
67     }
68 
69     /**
70      * Return a hash between [0, MAX_VALUE] generated from a package name, using a cache.
71      *
72      * Because all the results are cached, do not use it for dynamically generated strings.
73      */
74     @VisibleForTesting
getUnsignedHashCached(String s)75     static int getUnsignedHashCached(String s) {
76         synchronized (sHashCache) {
77             final Integer cached = sHashCache.get(s);
78             if (cached != null) {
79                 return cached;
80             }
81             final int hash = getUnsignedHashUnCached(s);
82             sHashCache.put(s.intern(), hash);
83             return hash;
84         }
85     }
86 
87     /**
88      * Return a hash between [0, MAX_VALUE] generated from a package name.
89      */
getUnsignedHashUnCached(String s)90     private static int getUnsignedHashUnCached(String s) {
91         try {
92             final MessageDigest digest = MessageDigest.getInstance("SHA-1");
93             digest.update(s.getBytes());
94             return unsignedIntFromBytes(digest.digest());
95         } catch (NoSuchAlgorithmException e) {
96             throw new RuntimeException(e);
97         }
98     }
99 
100     @VisibleForTesting
unsignedIntFromBytes(byte[] longEnoughBytes)101     static int unsignedIntFromBytes(byte[] longEnoughBytes) {
102         return (extractByte(longEnoughBytes, 0)
103                 | extractByte(longEnoughBytes, 1)
104                 | extractByte(longEnoughBytes, 2)
105                 | extractByte(longEnoughBytes, 3))
106                 & 0x7FFF_FFFF;
107     }
108 
extractByte(byte[] bytes, int index)109     private static int extractByte(byte[] bytes, int index) {
110         return (((int) bytes[index]) & 0xFF) << (index * 8);
111     }
112 
113     /**
114      * @return whether a package should be logged, using a random value based on the ANDROID_ID,
115      * with a given sampling rate.
116      */
shouldSamplePackageForAtom(String packageName, float rate)117     public static boolean shouldSamplePackageForAtom(String packageName, float rate) {
118         if (rate <= 0) {
119             return false;
120         }
121         if (rate >= 1) {
122             return true;
123         }
124         final int hash = getUnsignedHashCached(packageName) ^ getAndroidIdHash();
125 
126         return (((double) hash) / Integer.MAX_VALUE) <= rate;
127     }
128 }
129