summaryrefslogtreecommitdiff
path: root/PermissionController/src/com/android/permissioncontroller/permission/service/PermissionControllerServiceModel.kt
blob: 49a465898803224116bbaab76745d7ccc2562e0b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.permissioncontroller.permission.service

import android.content.pm.PackageManager
import android.os.Process
import android.permission.PermissionControllerManager.COUNT_ONLY_WHEN_GRANTED
import android.permission.PermissionControllerManager.COUNT_WHEN_SYSTEM
import android.permission.PermissionControllerManager.HIBERNATION_ELIGIBILITY_UNKNOWN
import androidx.core.util.Consumer
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.Transformations
import com.android.permissioncontroller.DumpableLog
import com.android.permissioncontroller.PermissionControllerProto.PermissionControllerDumpProto
import com.android.permissioncontroller.permission.utils.PermissionMapping
import com.android.permissioncontroller.permission.data.AppPermGroupUiInfoLiveData
import com.android.permissioncontroller.permission.data.HibernationSettingStateLiveData
import com.android.permissioncontroller.permission.data.PackagePermissionsLiveData
import com.android.permissioncontroller.permission.data.SmartUpdateMediatorLiveData
import com.android.permissioncontroller.permission.data.UserPackageInfosLiveData
import com.android.permissioncontroller.permission.data.get
import com.android.permissioncontroller.permission.data.getUnusedPackages
import com.android.permissioncontroller.permission.model.livedatatypes.AppPermGroupUiInfo
import com.android.permissioncontroller.permission.model.livedatatypes.AppPermGroupUiInfo.PermGrantState
import com.android.permissioncontroller.permission.model.livedatatypes.LightPackageInfo
import com.android.permissioncontroller.permission.utils.Utils
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeout
import java.util.function.IntConsumer

/**
 * A model for the PermissionControllerServiceImpl. Handles the data gathering for some methods of
 * ServiceImpl, and supports retrieving data from LiveDatas.
 */
class PermissionControllerServiceModel(private val service: PermissionControllerServiceImpl) {

    private val observedLiveDatas = mutableListOf<LiveData<*>>()

    /**
     * *Must* be used instead of LiveData.observe, in order to allow the lifecycle state to
     * be set to "started" correctly. If the liveData was inactive, create a no op observer, which
     * will survive until the service goes inactive. Will remove the provided observer after one
     * update (one non-stale update, in the case of a SmartUpdateMediatorLiveData).
     *
     * @param liveData The livedata we wish to observe
     * @param onChangedFun The function we wish to be called upon livedata updates
     * @param <T> The type of the livedata and observer
     */
    fun <T> observeAndCheckForLifecycleState(
        liveData: LiveData<T>,
        forceUpdate: Boolean = false,
        onChangedFun: (t: T?) -> Unit
    ) {
        GlobalScope.launch(Main.immediate) {

            if (service.lifecycle.currentState != Lifecycle.State.STARTED) {
                service.setLifecycleToStarted()
            }

            if (!liveData.hasActiveObservers()) {
                observedLiveDatas.add(liveData)
                liveData.observe(service, Observer { })
            }

            if (forceUpdate && liveData is SmartUpdateMediatorLiveData<T>) {
                liveData.update()
            }

            var updated = false
            val observer = object : Observer<T> {
                override fun onChanged(data: T) {
                    if (updated) {
                        return
                    }
                    if ((liveData is SmartUpdateMediatorLiveData<T> && !liveData.isStale) ||
                        liveData !is SmartUpdateMediatorLiveData<T>) {
                        onChangedFun(data)
                        liveData.removeObserver(this)
                        updated = true
                    }
                }
            }

            liveData.observe(service, observer)
        }
    }

    /**
     * Stop observing all currently observed liveDatas
     */
    fun removeObservers() {
        GlobalScope.launch(Main.immediate) {
            for (liveData in observedLiveDatas) {
                liveData.removeObservers(service)
            }

            observedLiveDatas.clear()
        }
    }

    /**
     * Counts the number of apps that have at least one of a provided list of permissions, subject
     * to the options specified in flags. This data is gathered from a series of LiveData objects.
     *
     * @param permissionNames The list of permission names whose apps we want to count
     * @param flags Flags specifying if we want to count system apps, and count only granted apps
     * @param callback The callback our result will be returned to
     */
    fun onCountPermissionAppsLiveData(
        permissionNames: List<String>,
        flags: Int,
        callback: IntConsumer
    ) {
        val packageInfosLiveData = UserPackageInfosLiveData[Process.myUserHandle()]
        observeAndCheckForLifecycleState(packageInfosLiveData) { packageInfos ->
            onPackagesLoadedForCountPermissionApps(permissionNames, flags, callback,
                packageInfos)
        }
    }

    /**
     * Called upon receiving a list of packages which we want to filter by a list of permissions
     * and flags. Observes the AppPermGroupUiInfoLiveData for every app, and, upon receiving a
     * non-stale update, adds it to the count if it matches the permission list and flags. Will
     * only use the first non-stale update, so if an app is updated after this update, but before
     * execution is complete, the changes will not be reflected until the method is called again.
     *
     * @param permissionNames The list of permission names whose apps we want to count
     * @param flags Flags specifying if we want to count system apps, and count only granted apps
     * @param callback The callback our result will be returned to
     * @param packageInfos The list of LightPackageInfos we want to filter and count
     */
    private fun onPackagesLoadedForCountPermissionApps(
        permissionNames: List<String>,
        flags: Int,
        callback: IntConsumer,
        packageInfos: List<LightPackageInfo>?
    ) {
        if (packageInfos == null) {
            callback.accept(0)
            return
        }

        val countSystem = flags and COUNT_WHEN_SYSTEM != 0
        val countOnlyGranted = flags and COUNT_ONLY_WHEN_GRANTED != 0

        // Store the group of all installed, runtime permissions in permissionNames
        val permToGroup = mutableMapOf<String, String?>()
        for (permName in permissionNames) {
            val permInfo = try {
                service.packageManager.getPermissionInfo(permName, 0)
            } catch (e: PackageManager.NameNotFoundException) {
                continue
            }

            if (Utils.isPermissionDangerousInstalledNotRemoved(permInfo)) {
                permToGroup[permName] = PermissionMapping.getGroupOfPermission(permInfo)
            }
        }

        val uiLiveDatasPerPackage = mutableListOf<MutableSet<AppPermGroupUiInfoLiveData>>()
        var numLiveDatas = 0
        for ((packageName, _, requestedPermissions) in packageInfos) {
            val packageUiLiveDatas = mutableSetOf<AppPermGroupUiInfoLiveData>()
            for (permName in permToGroup.keys) {
                if (requestedPermissions.contains(permName)) {
                    packageUiLiveDatas.add(AppPermGroupUiInfoLiveData[packageName,
                        permToGroup[permName]!!, Process.myUserHandle()])
                }
            }
            if (packageUiLiveDatas.isNotEmpty()) {
                uiLiveDatasPerPackage.add(packageUiLiveDatas)
                numLiveDatas += packageUiLiveDatas.size
            }
        }

        if (numLiveDatas == 0) {
            callback.accept(0)
        }

        var packagesWithPermission = 0
        var numPermAppsChecked = 0

        for (packageUiInfoLiveDatas in uiLiveDatasPerPackage) {
            var packageAdded = false
            // We don't need to check for new packages in between the updates of the ui info live
            // datas, because this method is used primarily for UI, and there is inherent delay
            // when calling this method, due to binder calls, so some staleness is acceptable
            for (packageUiInfoLiveData in packageUiInfoLiveDatas) {
                observeAndCheckForLifecycleState(packageUiInfoLiveData) { uiInfo ->
                    numPermAppsChecked++

                    if (uiInfo != null && uiInfo.shouldShow && (!uiInfo.isSystem || countSystem)) {
                        val granted = uiInfo.permGrantState != PermGrantState.PERMS_DENIED &&
                            uiInfo.permGrantState != PermGrantState.PERMS_ASK
                        if (granted || !countOnlyGranted && !packageAdded) {
                            // The permission might not be granted, but some permissions of the
                            // group are granted. In this case the permission is granted silently
                            // when the app asks for it.
                            // Hence this is as-good-as-granted and we count it.
                            packageAdded = true
                            packagesWithPermission++
                        }
                    }

                    if (numPermAppsChecked == numLiveDatas) {
                        callback.accept(packagesWithPermission)
                    }
                }
            }
        }
    }

    /**
     * Gets a list of the runtime permission groups which a package requests, and the UI information
     * about those groups. Will only use the first non-stale data for each group, so if an app is
     * updated after this update, but before execution is complete, the changes will not be
     * reflected until the method is called again.
     *
     * @param packageName The package whose permission information we want
     * @param callback The callback which will accept the list of <group name, group UI info> pairs
     */
    fun onGetAppPermissions(
        packageName: String,
        callback: Consumer<List<Pair<String, AppPermGroupUiInfo>>>
    ) {
        val packageGroupsLiveData = PackagePermissionsLiveData[packageName,
            Process.myUserHandle()]
        observeAndCheckForLifecycleState(packageGroupsLiveData) { groups ->
            val groupNames = groups?.keys?.toMutableList() ?: mutableListOf()
            groupNames.remove(PackagePermissionsLiveData.NON_RUNTIME_NORMAL_PERMS)
            val uiInfos = mutableListOf<Pair<String, AppPermGroupUiInfo>>()
            if (groupNames.isEmpty()) {
                callback.accept(uiInfos)
            }
            var numLiveDatasUpdated = 0

            for (groupName in groupNames) {
                // We don't need to check for new packages in between the updates of the ui info
                // live datas, because this method is used primarily for UI, and there is inherent
                // delay when calling this method, due to binder calls, so some staleness is
                // acceptable
                val uiInfoLiveData = AppPermGroupUiInfoLiveData[packageName, groupName,
                    Process.myUserHandle()]
                observeAndCheckForLifecycleState(uiInfoLiveData, forceUpdate = true) { uiInfo ->
                    numLiveDatasUpdated++

                    uiInfo?.let {
                        if (uiInfo.shouldShow) {
                            uiInfos.add(groupName to uiInfo)
                        }
                    }

                    if (numLiveDatasUpdated == groupNames.size) {
                        callback.accept(uiInfos)
                    }
                }
            }
        }
    }

    /**
     * Counts the number of unused, hibernating apps. This data is gathered from a series of
     * LiveData objects.
     *
     * @param callback The callback our result will be returned to
     */
    fun onCountUnusedApps(
        callback: IntConsumer
    ) {
        val unusedAppsCount = Transformations.map(getUnusedPackages()) {
            it?.size ?: 0
        }
        observeAndCheckForLifecycleState(unusedAppsCount) { count -> callback.accept(count ?: 0) }
    }

    /**
     * Gets whether the package is eligible for hibernation. The logic is the same logic used by
     * the app hibernation job when determining which apps to hibernate.
     *
     * @param packageName The package to check eligibility for
     * @param callback The callback the result will be returned to
     */
    fun onGetHibernationEligibility(
        packageName: String,
        callback: IntConsumer
    ) {
        val user = Process.myUserHandle()
        val hibernationSettingLiveData = HibernationSettingStateLiveData[packageName, user]
        observeAndCheckForLifecycleState(hibernationSettingLiveData) { hibernationSettingState ->
            callback.accept(
                hibernationSettingState?.hibernationEligibility ?: HIBERNATION_ELIGIBILITY_UNKNOWN)
        }
    }

    /**
     * Dump state of the permission controller service
     *
     * @return the dump state as a proto
     */
    suspend fun onDump(): PermissionControllerDumpProto {
        // Timeout is less than the timeout used by dumping (10 s)
        return withTimeout(9000) {
            val dumpedLogs = GlobalScope.async(IO) { DumpableLog.get() }

            PermissionControllerDumpProto.newBuilder()
                    .addAllLogs(dumpedLogs.await())
                    .build()
        }
    }
}