DefaultPermissionGrantPolicy.java revision bd111589cd5e3cb4e236a3cd84588d9b7f8039ea
1/*
2 * Copyright (C) 2015 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
17package com.android.server.pm.permission;
18
19import static android.os.Process.FIRST_APPLICATION_UID;
20
21import android.Manifest;
22import android.annotation.NonNull;
23import android.annotation.Nullable;
24import android.app.ActivityManager;
25import android.app.DownloadManager;
26import android.app.admin.DevicePolicyManager;
27import android.companion.CompanionDeviceManager;
28import android.content.ComponentName;
29import android.content.Context;
30import android.content.Intent;
31import android.content.pm.ApplicationInfo;
32import android.content.pm.PackageList;
33import android.content.pm.PackageManager;
34import android.content.pm.PackageManagerInternal;
35import android.content.pm.PackageManagerInternal.PackagesProvider;
36import android.content.pm.PackageManagerInternal.SyncAdapterPackagesProvider;
37import android.content.pm.PackageParser;
38import android.content.pm.ProviderInfo;
39import android.content.pm.ResolveInfo;
40import android.media.RingtoneManager;
41import android.net.Uri;
42import android.os.Binder;
43import android.os.Build;
44import android.os.Environment;
45import android.os.Handler;
46import android.os.Looper;
47import android.os.Message;
48import android.os.UserHandle;
49import android.os.storage.StorageManager;
50import android.print.PrintManager;
51import android.provider.CalendarContract;
52import android.provider.ContactsContract;
53import android.provider.MediaStore;
54import android.provider.Telephony.Sms.Intents;
55import android.security.Credentials;
56import android.service.textclassifier.TextClassifierService;
57import android.telephony.TelephonyManager;
58import android.text.TextUtils;
59import android.util.ArrayMap;
60import android.util.ArraySet;
61import android.util.Log;
62import android.util.Slog;
63import android.util.Xml;
64
65import com.android.internal.util.XmlUtils;
66import com.android.server.LocalServices;
67import com.android.server.pm.PackageManagerService;
68
69import org.xmlpull.v1.XmlPullParser;
70import org.xmlpull.v1.XmlPullParserException;
71
72import java.io.BufferedInputStream;
73import java.io.File;
74import java.io.FileInputStream;
75import java.io.IOException;
76import java.io.InputStream;
77import java.util.ArrayList;
78import java.util.Collections;
79import java.util.List;
80import java.util.Map;
81import java.util.Set;
82
83/**
84 * This class is the policy for granting runtime permissions to
85 * platform components and default handlers in the system such
86 * that the device is usable out-of-the-box. For example, the
87 * shell UID is a part of the system and the Phone app should
88 * have phone related permission by default.
89 * <p>
90 * NOTE: This class is at the wrong abstraction level. It is a part of the package manager
91 * service but knows about lots of higher level subsystems. The correct way to do this is
92 * to have an interface defined in the package manager but have the impl next to other
93 * policy stuff like PhoneWindowManager
94 */
95public final class DefaultPermissionGrantPolicy {
96    private static final String TAG = "DefaultPermGrantPolicy"; // must be <= 23 chars
97    private static final boolean DEBUG = false;
98
99    private static final int DEFAULT_FLAGS =
100            PackageManager.MATCH_DIRECT_BOOT_AWARE | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
101                    | PackageManager.MATCH_UNINSTALLED_PACKAGES;
102
103    private static final String AUDIO_MIME_TYPE = "audio/mpeg";
104
105    private static final String TAG_EXCEPTIONS = "exceptions";
106    private static final String TAG_EXCEPTION = "exception";
107    private static final String TAG_PERMISSION = "permission";
108    private static final String ATTR_PACKAGE = "package";
109    private static final String ATTR_NAME = "name";
110    private static final String ATTR_FIXED = "fixed";
111
112    private static final Set<String> PHONE_PERMISSIONS = new ArraySet<>();
113    static {
114        PHONE_PERMISSIONS.add(Manifest.permission.READ_PHONE_STATE);
115        PHONE_PERMISSIONS.add(Manifest.permission.CALL_PHONE);
116        PHONE_PERMISSIONS.add(Manifest.permission.READ_CALL_LOG);
117        PHONE_PERMISSIONS.add(Manifest.permission.WRITE_CALL_LOG);
118        PHONE_PERMISSIONS.add(Manifest.permission.ADD_VOICEMAIL);
119        PHONE_PERMISSIONS.add(Manifest.permission.USE_SIP);
120        PHONE_PERMISSIONS.add(Manifest.permission.PROCESS_OUTGOING_CALLS);
121    }
122
123    private static final Set<String> CONTACTS_PERMISSIONS = new ArraySet<>();
124    static {
125        CONTACTS_PERMISSIONS.add(Manifest.permission.READ_CONTACTS);
126        CONTACTS_PERMISSIONS.add(Manifest.permission.WRITE_CONTACTS);
127        CONTACTS_PERMISSIONS.add(Manifest.permission.GET_ACCOUNTS);
128    }
129
130    private static final Set<String> LOCATION_PERMISSIONS = new ArraySet<>();
131    static {
132        LOCATION_PERMISSIONS.add(Manifest.permission.ACCESS_FINE_LOCATION);
133        LOCATION_PERMISSIONS.add(Manifest.permission.ACCESS_COARSE_LOCATION);
134    }
135
136    private static final Set<String> COARSE_LOCATION_PERMISSIONS = new ArraySet<>();
137    static {
138        COARSE_LOCATION_PERMISSIONS.add(Manifest.permission.ACCESS_COARSE_LOCATION);
139    }
140
141    private static final Set<String> CALENDAR_PERMISSIONS = new ArraySet<>();
142    static {
143        CALENDAR_PERMISSIONS.add(Manifest.permission.READ_CALENDAR);
144        CALENDAR_PERMISSIONS.add(Manifest.permission.WRITE_CALENDAR);
145    }
146
147    private static final Set<String> SMS_PERMISSIONS = new ArraySet<>();
148    static {
149        SMS_PERMISSIONS.add(Manifest.permission.SEND_SMS);
150        SMS_PERMISSIONS.add(Manifest.permission.RECEIVE_SMS);
151        SMS_PERMISSIONS.add(Manifest.permission.READ_SMS);
152        SMS_PERMISSIONS.add(Manifest.permission.RECEIVE_WAP_PUSH);
153        SMS_PERMISSIONS.add(Manifest.permission.RECEIVE_MMS);
154        SMS_PERMISSIONS.add(Manifest.permission.READ_CELL_BROADCASTS);
155    }
156
157    private static final Set<String> MICROPHONE_PERMISSIONS = new ArraySet<>();
158    static {
159        MICROPHONE_PERMISSIONS.add(Manifest.permission.RECORD_AUDIO);
160    }
161
162    private static final Set<String> CAMERA_PERMISSIONS = new ArraySet<>();
163    static {
164        CAMERA_PERMISSIONS.add(Manifest.permission.CAMERA);
165    }
166
167    private static final Set<String> SENSORS_PERMISSIONS = new ArraySet<>();
168    static {
169        SENSORS_PERMISSIONS.add(Manifest.permission.BODY_SENSORS);
170    }
171
172    private static final Set<String> STORAGE_PERMISSIONS = new ArraySet<>();
173    static {
174        STORAGE_PERMISSIONS.add(Manifest.permission.READ_EXTERNAL_STORAGE);
175        STORAGE_PERMISSIONS.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
176    }
177
178    private static final int MSG_READ_DEFAULT_PERMISSION_EXCEPTIONS = 1;
179
180    private static final String ACTION_TRACK = "com.android.fitness.TRACK";
181
182    private final Handler mHandler;
183
184    private PackagesProvider mLocationPackagesProvider;
185    private PackagesProvider mVoiceInteractionPackagesProvider;
186    private PackagesProvider mSmsAppPackagesProvider;
187    private PackagesProvider mDialerAppPackagesProvider;
188    private PackagesProvider mSimCallManagerPackagesProvider;
189    private PackagesProvider mUseOpenWifiAppPackagesProvider;
190    private SyncAdapterPackagesProvider mSyncAdapterPackagesProvider;
191
192    private ArrayMap<String, List<DefaultPermissionGrant>> mGrantExceptions;
193    private final Context mContext;
194    private final Object mLock = new Object();
195    private final PackageManagerInternal mServiceInternal;
196    private final PermissionManagerService mPermissionManager;
197    private final DefaultPermissionGrantedCallback mPermissionGrantedCallback;
198    public interface DefaultPermissionGrantedCallback {
199        /** Callback when permissions have been granted */
200        public void onDefaultRuntimePermissionsGranted(int userId);
201    }
202
203    public DefaultPermissionGrantPolicy(Context context, Looper looper,
204            @Nullable DefaultPermissionGrantedCallback callback,
205            @NonNull PermissionManagerService permissionManager) {
206        mContext = context;
207        mHandler = new Handler(looper) {
208            @Override
209            public void handleMessage(Message msg) {
210                if (msg.what == MSG_READ_DEFAULT_PERMISSION_EXCEPTIONS) {
211                    synchronized (mLock) {
212                        if (mGrantExceptions == null) {
213                            mGrantExceptions = readDefaultPermissionExceptionsLocked();
214                        }
215                    }
216                }
217            }
218        };
219        mPermissionGrantedCallback = callback;
220        mPermissionManager = permissionManager;
221        mServiceInternal = LocalServices.getService(PackageManagerInternal.class);
222    }
223
224    public void setLocationPackagesProvider(PackagesProvider provider) {
225        synchronized (mLock) {
226            mLocationPackagesProvider = provider;
227        }
228    }
229
230    public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
231        synchronized (mLock) {
232            mVoiceInteractionPackagesProvider = provider;
233        }
234    }
235
236    public void setSmsAppPackagesProvider(PackagesProvider provider) {
237        synchronized (mLock) {
238            mSmsAppPackagesProvider = provider;
239        }
240    }
241
242    public void setDialerAppPackagesProvider(PackagesProvider provider) {
243        synchronized (mLock) {
244            mDialerAppPackagesProvider = provider;
245        }
246    }
247
248    public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
249        synchronized (mLock) {
250            mSimCallManagerPackagesProvider = provider;
251        }
252    }
253
254    public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
255        synchronized (mLock) {
256            mUseOpenWifiAppPackagesProvider = provider;
257        }
258    }
259
260    public void setSyncAdapterPackagesProvider(SyncAdapterPackagesProvider provider) {
261        synchronized (mLock) {
262            mSyncAdapterPackagesProvider = provider;
263        }
264    }
265
266    public void grantDefaultPermissions(int userId) {
267        grantPermissionsToSysComponentsAndPrivApps(userId);
268        grantDefaultSystemHandlerPermissions(userId);
269        grantDefaultPermissionExceptions(userId);
270    }
271
272    private void grantRuntimePermissionsForPackage(int userId, PackageParser.Package pkg) {
273        Set<String> permissions = new ArraySet<>();
274        for (String permission :  pkg.requestedPermissions) {
275            final BasePermission bp = mPermissionManager.getPermission(permission);
276            if (bp == null) {
277                continue;
278            }
279            if (bp.isRuntime()) {
280                permissions.add(permission);
281            }
282        }
283        if (!permissions.isEmpty()) {
284            grantRuntimePermissions(pkg, permissions, true, userId);
285        }
286    }
287
288    private void grantAllRuntimePermissions(int userId) {
289        Log.i(TAG, "Granting all runtime permissions for user " + userId);
290        final PackageList packageList = mServiceInternal.getPackageList();
291        for (String packageName : packageList.getPackageNames()) {
292            final PackageParser.Package pkg = mServiceInternal.getPackage(packageName);
293            if (pkg == null) {
294                continue;
295            }
296            grantRuntimePermissionsForPackage(userId, pkg);
297        }
298    }
299
300    public void scheduleReadDefaultPermissionExceptions() {
301        mHandler.sendEmptyMessage(MSG_READ_DEFAULT_PERMISSION_EXCEPTIONS);
302    }
303
304    private void grantPermissionsToSysComponentsAndPrivApps(int userId) {
305        Log.i(TAG, "Granting permissions to platform components for user " + userId);
306        final PackageList packageList = mServiceInternal.getPackageList();
307        for (String packageName : packageList.getPackageNames()) {
308            final PackageParser.Package pkg = mServiceInternal.getPackage(packageName);
309            if (pkg == null) {
310                continue;
311            }
312            if (!isSysComponentOrPersistentPlatformSignedPrivApp(pkg)
313                    || !doesPackageSupportRuntimePermissions(pkg)
314                    || pkg.requestedPermissions.isEmpty()) {
315                continue;
316            }
317            grantRuntimePermissionsForPackage(userId, pkg);
318        }
319    }
320
321    private void grantDefaultSystemHandlerPermissions(int userId) {
322        Log.i(TAG, "Granting permissions to default platform handlers for user " + userId);
323
324        final PackagesProvider locationPackagesProvider;
325        final PackagesProvider voiceInteractionPackagesProvider;
326        final PackagesProvider smsAppPackagesProvider;
327        final PackagesProvider dialerAppPackagesProvider;
328        final PackagesProvider simCallManagerPackagesProvider;
329        final PackagesProvider useOpenWifiAppPackagesProvider;
330        final SyncAdapterPackagesProvider syncAdapterPackagesProvider;
331
332        synchronized (mLock) {
333            locationPackagesProvider = mLocationPackagesProvider;
334            voiceInteractionPackagesProvider = mVoiceInteractionPackagesProvider;
335            smsAppPackagesProvider = mSmsAppPackagesProvider;
336            dialerAppPackagesProvider = mDialerAppPackagesProvider;
337            simCallManagerPackagesProvider = mSimCallManagerPackagesProvider;
338            useOpenWifiAppPackagesProvider = mUseOpenWifiAppPackagesProvider;
339            syncAdapterPackagesProvider = mSyncAdapterPackagesProvider;
340        }
341
342        String[] voiceInteractPackageNames = (voiceInteractionPackagesProvider != null)
343                ? voiceInteractionPackagesProvider.getPackages(userId) : null;
344        String[] locationPackageNames = (locationPackagesProvider != null)
345                ? locationPackagesProvider.getPackages(userId) : null;
346        String[] smsAppPackageNames = (smsAppPackagesProvider != null)
347                ? smsAppPackagesProvider.getPackages(userId) : null;
348        String[] dialerAppPackageNames = (dialerAppPackagesProvider != null)
349                ? dialerAppPackagesProvider.getPackages(userId) : null;
350        String[] simCallManagerPackageNames = (simCallManagerPackagesProvider != null)
351                ? simCallManagerPackagesProvider.getPackages(userId) : null;
352        String[] useOpenWifiAppPackageNames = (useOpenWifiAppPackagesProvider != null)
353                ? useOpenWifiAppPackagesProvider.getPackages(userId) : null;
354        String[] contactsSyncAdapterPackages = (syncAdapterPackagesProvider != null) ?
355                syncAdapterPackagesProvider.getPackages(ContactsContract.AUTHORITY, userId) : null;
356        String[] calendarSyncAdapterPackages = (syncAdapterPackagesProvider != null) ?
357                syncAdapterPackagesProvider.getPackages(CalendarContract.AUTHORITY, userId) : null;
358
359        // Installer
360        final String installerPackageName = mServiceInternal.getKnownPackageName(
361                PackageManagerInternal.PACKAGE_INSTALLER, userId);
362        PackageParser.Package installerPackage = getSystemPackage(installerPackageName);
363        if (installerPackage != null
364                && doesPackageSupportRuntimePermissions(installerPackage)) {
365            grantRuntimePermissions(installerPackage, STORAGE_PERMISSIONS, true, userId);
366        }
367
368        // Verifier
369        final String verifierPackageName = mServiceInternal.getKnownPackageName(
370                PackageManagerInternal.PACKAGE_VERIFIER, userId);
371        PackageParser.Package verifierPackage = getSystemPackage(verifierPackageName);
372        if (verifierPackage != null
373                && doesPackageSupportRuntimePermissions(verifierPackage)) {
374            grantRuntimePermissions(verifierPackage, STORAGE_PERMISSIONS, true, userId);
375            grantRuntimePermissions(verifierPackage, PHONE_PERMISSIONS, false, userId);
376            grantRuntimePermissions(verifierPackage, SMS_PERMISSIONS, false, userId);
377        }
378
379        // SetupWizard
380        final String setupWizardPackageName = mServiceInternal.getKnownPackageName(
381                PackageManagerInternal.PACKAGE_SETUP_WIZARD, userId);
382        PackageParser.Package setupPackage = getSystemPackage(setupWizardPackageName);
383        if (setupPackage != null
384                && doesPackageSupportRuntimePermissions(setupPackage)) {
385            grantRuntimePermissions(setupPackage, PHONE_PERMISSIONS, userId);
386            grantRuntimePermissions(setupPackage, CONTACTS_PERMISSIONS, userId);
387            grantRuntimePermissions(setupPackage, LOCATION_PERMISSIONS, userId);
388            grantRuntimePermissions(setupPackage, CAMERA_PERMISSIONS, userId);
389        }
390
391        // Camera
392        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
393        PackageParser.Package cameraPackage = getDefaultSystemHandlerActivityPackage(
394                cameraIntent, userId);
395        if (cameraPackage != null
396                && doesPackageSupportRuntimePermissions(cameraPackage)) {
397            grantRuntimePermissions(cameraPackage, CAMERA_PERMISSIONS, userId);
398            grantRuntimePermissions(cameraPackage, MICROPHONE_PERMISSIONS, userId);
399            grantRuntimePermissions(cameraPackage, STORAGE_PERMISSIONS, userId);
400        }
401
402        // Media provider
403        PackageParser.Package mediaStorePackage = getDefaultProviderAuthorityPackage(
404                MediaStore.AUTHORITY, userId);
405        if (mediaStorePackage != null) {
406            grantRuntimePermissions(mediaStorePackage, STORAGE_PERMISSIONS, true, userId);
407            grantRuntimePermissions(mediaStorePackage, PHONE_PERMISSIONS, true, userId);
408        }
409
410        // Downloads provider
411        PackageParser.Package downloadsPackage = getDefaultProviderAuthorityPackage(
412                "downloads", userId);
413        if (downloadsPackage != null) {
414            grantRuntimePermissions(downloadsPackage, STORAGE_PERMISSIONS, true, userId);
415        }
416
417        // Downloads UI
418        Intent downloadsUiIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
419        PackageParser.Package downloadsUiPackage = getDefaultSystemHandlerActivityPackage(
420                downloadsUiIntent, userId);
421        if (downloadsUiPackage != null
422                && doesPackageSupportRuntimePermissions(downloadsUiPackage)) {
423            grantRuntimePermissions(downloadsUiPackage, STORAGE_PERMISSIONS, true, userId);
424        }
425
426        // Storage provider
427        PackageParser.Package storagePackage = getDefaultProviderAuthorityPackage(
428                "com.android.externalstorage.documents", userId);
429        if (storagePackage != null) {
430            grantRuntimePermissions(storagePackage, STORAGE_PERMISSIONS, true, userId);
431        }
432
433        // Container service
434        PackageParser.Package containerPackage = getSystemPackage(
435                PackageManagerService.DEFAULT_CONTAINER_PACKAGE);
436        if (containerPackage != null) {
437            grantRuntimePermissions(containerPackage, STORAGE_PERMISSIONS, true, userId);
438        }
439
440        // CertInstaller
441        Intent certInstallerIntent = new Intent(Credentials.INSTALL_ACTION);
442        PackageParser.Package certInstallerPackage = getDefaultSystemHandlerActivityPackage(
443                certInstallerIntent, userId);
444        if (certInstallerPackage != null
445                && doesPackageSupportRuntimePermissions(certInstallerPackage)) {
446            grantRuntimePermissions(certInstallerPackage, STORAGE_PERMISSIONS, true, userId);
447        }
448
449        // Dialer
450        if (dialerAppPackageNames == null) {
451            Intent dialerIntent = new Intent(Intent.ACTION_DIAL);
452            PackageParser.Package dialerPackage = getDefaultSystemHandlerActivityPackage(
453                    dialerIntent, userId);
454            if (dialerPackage != null) {
455                grantDefaultPermissionsToDefaultSystemDialerApp(dialerPackage, userId);
456            }
457        } else {
458            for (String dialerAppPackageName : dialerAppPackageNames) {
459                PackageParser.Package dialerPackage = getSystemPackage(dialerAppPackageName);
460                if (dialerPackage != null) {
461                    grantDefaultPermissionsToDefaultSystemDialerApp(dialerPackage, userId);
462                }
463            }
464        }
465
466        // Sim call manager
467        if (simCallManagerPackageNames != null) {
468            for (String simCallManagerPackageName : simCallManagerPackageNames) {
469                PackageParser.Package simCallManagerPackage =
470                        getSystemPackage(simCallManagerPackageName);
471                if (simCallManagerPackage != null) {
472                    grantDefaultPermissionsToDefaultSimCallManager(simCallManagerPackage,
473                            userId);
474                }
475            }
476        }
477
478        // Use Open Wifi
479        if (useOpenWifiAppPackageNames != null) {
480            for (String useOpenWifiPackageName : useOpenWifiAppPackageNames) {
481                PackageParser.Package useOpenWifiPackage =
482                        getSystemPackage(useOpenWifiPackageName);
483                if (useOpenWifiPackage != null) {
484                    grantDefaultPermissionsToDefaultSystemUseOpenWifiApp(useOpenWifiPackage,
485                            userId);
486                }
487            }
488        }
489
490        // SMS
491        if (smsAppPackageNames == null) {
492            Intent smsIntent = new Intent(Intent.ACTION_MAIN);
493            smsIntent.addCategory(Intent.CATEGORY_APP_MESSAGING);
494            PackageParser.Package smsPackage = getDefaultSystemHandlerActivityPackage(
495                    smsIntent, userId);
496            if (smsPackage != null) {
497               grantDefaultPermissionsToDefaultSystemSmsApp(smsPackage, userId);
498            }
499        } else {
500            for (String smsPackageName : smsAppPackageNames) {
501                PackageParser.Package smsPackage = getSystemPackage(smsPackageName);
502                if (smsPackage != null) {
503                    grantDefaultPermissionsToDefaultSystemSmsApp(smsPackage, userId);
504                }
505            }
506        }
507
508        // Cell Broadcast Receiver
509        Intent cbrIntent = new Intent(Intents.SMS_CB_RECEIVED_ACTION);
510        PackageParser.Package cbrPackage =
511                getDefaultSystemHandlerActivityPackage(cbrIntent, userId);
512        if (cbrPackage != null && doesPackageSupportRuntimePermissions(cbrPackage)) {
513            grantRuntimePermissions(cbrPackage, SMS_PERMISSIONS, userId);
514        }
515
516        // Carrier Provisioning Service
517        Intent carrierProvIntent = new Intent(Intents.SMS_CARRIER_PROVISION_ACTION);
518        PackageParser.Package carrierProvPackage =
519                getDefaultSystemHandlerServicePackage(carrierProvIntent, userId);
520        if (carrierProvPackage != null
521                && doesPackageSupportRuntimePermissions(carrierProvPackage)) {
522            grantRuntimePermissions(carrierProvPackage, SMS_PERMISSIONS, false, userId);
523        }
524
525        // Calendar
526        Intent calendarIntent = new Intent(Intent.ACTION_MAIN);
527        calendarIntent.addCategory(Intent.CATEGORY_APP_CALENDAR);
528        PackageParser.Package calendarPackage = getDefaultSystemHandlerActivityPackage(
529                calendarIntent, userId);
530        if (calendarPackage != null
531                && doesPackageSupportRuntimePermissions(calendarPackage)) {
532            grantRuntimePermissions(calendarPackage, CALENDAR_PERMISSIONS, userId);
533            grantRuntimePermissions(calendarPackage, CONTACTS_PERMISSIONS, userId);
534        }
535
536        // Calendar provider
537        PackageParser.Package calendarProviderPackage = getDefaultProviderAuthorityPackage(
538                CalendarContract.AUTHORITY, userId);
539        if (calendarProviderPackage != null) {
540            grantRuntimePermissions(calendarProviderPackage, CONTACTS_PERMISSIONS, userId);
541            grantRuntimePermissions(calendarProviderPackage, CALENDAR_PERMISSIONS,
542                    true, userId);
543            grantRuntimePermissions(calendarProviderPackage, STORAGE_PERMISSIONS, userId);
544        }
545
546        // Calendar provider sync adapters
547        List<PackageParser.Package> calendarSyncAdapters = getHeadlessSyncAdapterPackages(
548                calendarSyncAdapterPackages, userId);
549        final int calendarSyncAdapterCount = calendarSyncAdapters.size();
550        for (int i = 0; i < calendarSyncAdapterCount; i++) {
551            PackageParser.Package calendarSyncAdapter = calendarSyncAdapters.get(i);
552            if (doesPackageSupportRuntimePermissions(calendarSyncAdapter)) {
553                grantRuntimePermissions(calendarSyncAdapter, CALENDAR_PERMISSIONS, userId);
554            }
555        }
556
557        // Contacts
558        Intent contactsIntent = new Intent(Intent.ACTION_MAIN);
559        contactsIntent.addCategory(Intent.CATEGORY_APP_CONTACTS);
560        PackageParser.Package contactsPackage = getDefaultSystemHandlerActivityPackage(
561                contactsIntent, userId);
562        if (contactsPackage != null
563                && doesPackageSupportRuntimePermissions(contactsPackage)) {
564            grantRuntimePermissions(contactsPackage, CONTACTS_PERMISSIONS, userId);
565            grantRuntimePermissions(contactsPackage, PHONE_PERMISSIONS, userId);
566        }
567
568        // Contacts provider sync adapters
569        List<PackageParser.Package> contactsSyncAdapters = getHeadlessSyncAdapterPackages(
570                contactsSyncAdapterPackages, userId);
571        final int contactsSyncAdapterCount = contactsSyncAdapters.size();
572        for (int i = 0; i < contactsSyncAdapterCount; i++) {
573            PackageParser.Package contactsSyncAdapter = contactsSyncAdapters.get(i);
574            if (doesPackageSupportRuntimePermissions(contactsSyncAdapter)) {
575                grantRuntimePermissions(contactsSyncAdapter, CONTACTS_PERMISSIONS, userId);
576            }
577        }
578
579        // Contacts provider
580        PackageParser.Package contactsProviderPackage = getDefaultProviderAuthorityPackage(
581                ContactsContract.AUTHORITY, userId);
582        if (contactsProviderPackage != null) {
583            grantRuntimePermissions(contactsProviderPackage, CONTACTS_PERMISSIONS,
584                    true, userId);
585            grantRuntimePermissions(contactsProviderPackage, PHONE_PERMISSIONS,
586                    true, userId);
587            grantRuntimePermissions(contactsProviderPackage, STORAGE_PERMISSIONS, userId);
588        }
589
590        // Device provisioning
591        Intent deviceProvisionIntent = new Intent(
592                DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE);
593        PackageParser.Package deviceProvisionPackage =
594                getDefaultSystemHandlerActivityPackage(deviceProvisionIntent, userId);
595        if (deviceProvisionPackage != null
596                && doesPackageSupportRuntimePermissions(deviceProvisionPackage)) {
597            grantRuntimePermissions(deviceProvisionPackage, CONTACTS_PERMISSIONS, userId);
598        }
599
600        // Maps
601        Intent mapsIntent = new Intent(Intent.ACTION_MAIN);
602        mapsIntent.addCategory(Intent.CATEGORY_APP_MAPS);
603        PackageParser.Package mapsPackage = getDefaultSystemHandlerActivityPackage(
604                mapsIntent, userId);
605        if (mapsPackage != null
606                && doesPackageSupportRuntimePermissions(mapsPackage)) {
607            grantRuntimePermissions(mapsPackage, LOCATION_PERMISSIONS, userId);
608        }
609
610        // Gallery
611        Intent galleryIntent = new Intent(Intent.ACTION_MAIN);
612        galleryIntent.addCategory(Intent.CATEGORY_APP_GALLERY);
613        PackageParser.Package galleryPackage = getDefaultSystemHandlerActivityPackage(
614                galleryIntent, userId);
615        if (galleryPackage != null
616                && doesPackageSupportRuntimePermissions(galleryPackage)) {
617            grantRuntimePermissions(galleryPackage, STORAGE_PERMISSIONS, userId);
618        }
619
620        // Email
621        Intent emailIntent = new Intent(Intent.ACTION_MAIN);
622        emailIntent.addCategory(Intent.CATEGORY_APP_EMAIL);
623        PackageParser.Package emailPackage = getDefaultSystemHandlerActivityPackage(
624                emailIntent, userId);
625        if (emailPackage != null
626                && doesPackageSupportRuntimePermissions(emailPackage)) {
627            grantRuntimePermissions(emailPackage, CONTACTS_PERMISSIONS, userId);
628            grantRuntimePermissions(emailPackage, CALENDAR_PERMISSIONS, userId);
629        }
630
631        // Browser
632        PackageParser.Package browserPackage = null;
633        String defaultBrowserPackage = mServiceInternal.getKnownPackageName(
634                PackageManagerInternal.PACKAGE_BROWSER, userId);
635        if (defaultBrowserPackage != null) {
636            browserPackage = getPackage(defaultBrowserPackage);
637        }
638        if (browserPackage == null) {
639            Intent browserIntent = new Intent(Intent.ACTION_MAIN);
640            browserIntent.addCategory(Intent.CATEGORY_APP_BROWSER);
641            browserPackage = getDefaultSystemHandlerActivityPackage(
642                    browserIntent, userId);
643        }
644        if (browserPackage != null
645                && doesPackageSupportRuntimePermissions(browserPackage)) {
646            grantRuntimePermissions(browserPackage, LOCATION_PERMISSIONS, userId);
647        }
648
649        // Voice interaction
650        if (voiceInteractPackageNames != null) {
651            for (String voiceInteractPackageName : voiceInteractPackageNames) {
652                PackageParser.Package voiceInteractPackage = getSystemPackage(
653                        voiceInteractPackageName);
654                if (voiceInteractPackage != null
655                        && doesPackageSupportRuntimePermissions(voiceInteractPackage)) {
656                    grantRuntimePermissions(voiceInteractPackage,
657                            CONTACTS_PERMISSIONS, userId);
658                    grantRuntimePermissions(voiceInteractPackage,
659                            CALENDAR_PERMISSIONS, userId);
660                    grantRuntimePermissions(voiceInteractPackage,
661                            MICROPHONE_PERMISSIONS, userId);
662                    grantRuntimePermissions(voiceInteractPackage,
663                            PHONE_PERMISSIONS, userId);
664                    grantRuntimePermissions(voiceInteractPackage,
665                            SMS_PERMISSIONS, userId);
666                    grantRuntimePermissions(voiceInteractPackage,
667                            LOCATION_PERMISSIONS, userId);
668                }
669            }
670        }
671
672        if (ActivityManager.isLowRamDeviceStatic()) {
673            // Allow voice search on low-ram devices
674            Intent globalSearchIntent = new Intent("android.search.action.GLOBAL_SEARCH");
675            PackageParser.Package globalSearchPickerPackage =
676                getDefaultSystemHandlerActivityPackage(globalSearchIntent, userId);
677
678            if (globalSearchPickerPackage != null
679                    && doesPackageSupportRuntimePermissions(globalSearchPickerPackage)) {
680                grantRuntimePermissions(globalSearchPickerPackage,
681                    MICROPHONE_PERMISSIONS, false, userId);
682                grantRuntimePermissions(globalSearchPickerPackage,
683                    LOCATION_PERMISSIONS, false, userId);
684            }
685        }
686
687        // Voice recognition
688        Intent voiceRecoIntent = new Intent("android.speech.RecognitionService");
689        voiceRecoIntent.addCategory(Intent.CATEGORY_DEFAULT);
690        PackageParser.Package voiceRecoPackage = getDefaultSystemHandlerServicePackage(
691                voiceRecoIntent, userId);
692        if (voiceRecoPackage != null
693                && doesPackageSupportRuntimePermissions(voiceRecoPackage)) {
694            grantRuntimePermissions(voiceRecoPackage, MICROPHONE_PERMISSIONS, userId);
695        }
696
697        // Location
698        if (locationPackageNames != null) {
699            for (String packageName : locationPackageNames) {
700                PackageParser.Package locationPackage = getSystemPackage(packageName);
701                if (locationPackage != null
702                        && doesPackageSupportRuntimePermissions(locationPackage)) {
703                    grantRuntimePermissions(locationPackage, CONTACTS_PERMISSIONS, userId);
704                    grantRuntimePermissions(locationPackage, CALENDAR_PERMISSIONS, userId);
705                    grantRuntimePermissions(locationPackage, MICROPHONE_PERMISSIONS, userId);
706                    grantRuntimePermissions(locationPackage, PHONE_PERMISSIONS, userId);
707                    grantRuntimePermissions(locationPackage, SMS_PERMISSIONS, userId);
708                    grantRuntimePermissions(locationPackage, LOCATION_PERMISSIONS,
709                            true, userId);
710                    grantRuntimePermissions(locationPackage, CAMERA_PERMISSIONS, userId);
711                    grantRuntimePermissions(locationPackage, SENSORS_PERMISSIONS, userId);
712                    grantRuntimePermissions(locationPackage, STORAGE_PERMISSIONS, userId);
713                }
714            }
715        }
716
717        // Music
718        Intent musicIntent = new Intent(Intent.ACTION_VIEW);
719        musicIntent.addCategory(Intent.CATEGORY_DEFAULT);
720        musicIntent.setDataAndType(Uri.fromFile(new File("foo.mp3")),
721                AUDIO_MIME_TYPE);
722        PackageParser.Package musicPackage = getDefaultSystemHandlerActivityPackage(
723                musicIntent, userId);
724        if (musicPackage != null
725                && doesPackageSupportRuntimePermissions(musicPackage)) {
726            grantRuntimePermissions(musicPackage, STORAGE_PERMISSIONS, userId);
727        }
728
729        // Home
730        Intent homeIntent = new Intent(Intent.ACTION_MAIN);
731        homeIntent.addCategory(Intent.CATEGORY_HOME);
732        homeIntent.addCategory(Intent.CATEGORY_LAUNCHER_APP);
733        PackageParser.Package homePackage = getDefaultSystemHandlerActivityPackage(
734                homeIntent, userId);
735        if (homePackage != null
736                && doesPackageSupportRuntimePermissions(homePackage)) {
737            grantRuntimePermissions(homePackage, LOCATION_PERMISSIONS, false, userId);
738        }
739
740        // Watches
741        if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH, 0)) {
742            // Home application on watches
743            Intent wearHomeIntent = new Intent(Intent.ACTION_MAIN);
744            wearHomeIntent.addCategory(Intent.CATEGORY_HOME_MAIN);
745
746            PackageParser.Package wearHomePackage = getDefaultSystemHandlerActivityPackage(
747                    wearHomeIntent, userId);
748
749            if (wearHomePackage != null
750                    && doesPackageSupportRuntimePermissions(wearHomePackage)) {
751                grantRuntimePermissions(wearHomePackage, CONTACTS_PERMISSIONS, false,
752                        userId);
753                grantRuntimePermissions(wearHomePackage, PHONE_PERMISSIONS, true, userId);
754                grantRuntimePermissions(wearHomePackage, MICROPHONE_PERMISSIONS, false,
755                        userId);
756                grantRuntimePermissions(wearHomePackage, LOCATION_PERMISSIONS, false,
757                        userId);
758            }
759
760            // Fitness tracking on watches
761            Intent trackIntent = new Intent(ACTION_TRACK);
762            PackageParser.Package trackPackage = getDefaultSystemHandlerActivityPackage(
763                    trackIntent, userId);
764            if (trackPackage != null
765                    && doesPackageSupportRuntimePermissions(trackPackage)) {
766                grantRuntimePermissions(trackPackage, SENSORS_PERMISSIONS, false, userId);
767                grantRuntimePermissions(trackPackage, LOCATION_PERMISSIONS, false, userId);
768            }
769        }
770
771        // Print Spooler
772        PackageParser.Package printSpoolerPackage = getSystemPackage(
773                PrintManager.PRINT_SPOOLER_PACKAGE_NAME);
774        if (printSpoolerPackage != null
775                && doesPackageSupportRuntimePermissions(printSpoolerPackage)) {
776            grantRuntimePermissions(printSpoolerPackage, LOCATION_PERMISSIONS, true, userId);
777        }
778
779        // EmergencyInfo
780        Intent emergencyInfoIntent = new Intent(TelephonyManager.ACTION_EMERGENCY_ASSISTANCE);
781        PackageParser.Package emergencyInfoPckg = getDefaultSystemHandlerActivityPackage(
782                emergencyInfoIntent, userId);
783        if (emergencyInfoPckg != null
784                && doesPackageSupportRuntimePermissions(emergencyInfoPckg)) {
785            grantRuntimePermissions(emergencyInfoPckg, CONTACTS_PERMISSIONS, true, userId);
786            grantRuntimePermissions(emergencyInfoPckg, PHONE_PERMISSIONS, true, userId);
787        }
788
789        // NFC Tag viewer
790        Intent nfcTagIntent = new Intent(Intent.ACTION_VIEW);
791        nfcTagIntent.setType("vnd.android.cursor.item/ndef_msg");
792        PackageParser.Package nfcTagPkg = getDefaultSystemHandlerActivityPackage(
793                nfcTagIntent, userId);
794        if (nfcTagPkg != null
795                && doesPackageSupportRuntimePermissions(nfcTagPkg)) {
796            grantRuntimePermissions(nfcTagPkg, CONTACTS_PERMISSIONS, false, userId);
797            grantRuntimePermissions(nfcTagPkg, PHONE_PERMISSIONS, false, userId);
798        }
799
800        // Storage Manager
801        Intent storageManagerIntent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
802        PackageParser.Package storageManagerPckg = getDefaultSystemHandlerActivityPackage(
803                storageManagerIntent, userId);
804        if (storageManagerPckg != null
805                && doesPackageSupportRuntimePermissions(storageManagerPckg)) {
806            grantRuntimePermissions(storageManagerPckg, STORAGE_PERMISSIONS, true, userId);
807        }
808
809        // Companion devices
810        PackageParser.Package companionDeviceDiscoveryPackage = getSystemPackage(
811                CompanionDeviceManager.COMPANION_DEVICE_DISCOVERY_PACKAGE_NAME);
812        if (companionDeviceDiscoveryPackage != null
813                && doesPackageSupportRuntimePermissions(companionDeviceDiscoveryPackage)) {
814            grantRuntimePermissions(companionDeviceDiscoveryPackage,
815                    LOCATION_PERMISSIONS, true, userId);
816        }
817
818        // Ringtone Picker
819        Intent ringtonePickerIntent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
820        PackageParser.Package ringtonePickerPackage =
821                getDefaultSystemHandlerActivityPackage(ringtonePickerIntent, userId);
822        if (ringtonePickerPackage != null
823                && doesPackageSupportRuntimePermissions(ringtonePickerPackage)) {
824            grantRuntimePermissions(ringtonePickerPackage,
825                    STORAGE_PERMISSIONS, true, userId);
826        }
827
828        // TextClassifier Service
829        String textClassifierPackageName =
830                mContext.getPackageManager().getSystemTextClassifierPackageName();
831        if (!TextUtils.isEmpty(textClassifierPackageName)) {
832            PackageParser.Package textClassifierPackage =
833                    getSystemPackage(textClassifierPackageName);
834            if (textClassifierPackage != null
835                    && doesPackageSupportRuntimePermissions(textClassifierPackage)) {
836                grantRuntimePermissions(textClassifierPackage, PHONE_PERMISSIONS, true, userId);
837                grantRuntimePermissions(textClassifierPackage, SMS_PERMISSIONS, true, userId);
838                grantRuntimePermissions(textClassifierPackage, CALENDAR_PERMISSIONS, true, userId);
839                grantRuntimePermissions(textClassifierPackage, LOCATION_PERMISSIONS, true, userId);
840                grantRuntimePermissions(textClassifierPackage, CONTACTS_PERMISSIONS, true, userId);
841            }
842        }
843
844        if (mPermissionGrantedCallback != null) {
845            mPermissionGrantedCallback.onDefaultRuntimePermissionsGranted(userId);
846        }
847    }
848
849    private void grantDefaultPermissionsToDefaultSystemDialerApp(
850            PackageParser.Package dialerPackage, int userId) {
851        if (doesPackageSupportRuntimePermissions(dialerPackage)) {
852            boolean isPhonePermFixed =
853                    mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH, 0);
854            grantRuntimePermissions(
855                    dialerPackage, PHONE_PERMISSIONS, isPhonePermFixed, userId);
856            grantRuntimePermissions(dialerPackage, CONTACTS_PERMISSIONS, userId);
857            grantRuntimePermissions(dialerPackage, SMS_PERMISSIONS, userId);
858            grantRuntimePermissions(dialerPackage, MICROPHONE_PERMISSIONS, userId);
859            grantRuntimePermissions(dialerPackage, CAMERA_PERMISSIONS, userId);
860        }
861    }
862
863    private void grantDefaultPermissionsToDefaultSystemSmsApp(
864            PackageParser.Package smsPackage, int userId) {
865        if (doesPackageSupportRuntimePermissions(smsPackage)) {
866            grantRuntimePermissions(smsPackage, PHONE_PERMISSIONS, userId);
867            grantRuntimePermissions(smsPackage, CONTACTS_PERMISSIONS, userId);
868            grantRuntimePermissions(smsPackage, SMS_PERMISSIONS, userId);
869            grantRuntimePermissions(smsPackage, STORAGE_PERMISSIONS, userId);
870            grantRuntimePermissions(smsPackage, MICROPHONE_PERMISSIONS, userId);
871            grantRuntimePermissions(smsPackage, CAMERA_PERMISSIONS, userId);
872        }
873    }
874
875    private void grantDefaultPermissionsToDefaultSystemUseOpenWifiApp(
876            PackageParser.Package useOpenWifiPackage, int userId) {
877        if (doesPackageSupportRuntimePermissions(useOpenWifiPackage)) {
878            grantRuntimePermissions(useOpenWifiPackage, COARSE_LOCATION_PERMISSIONS, userId);
879        }
880    }
881
882    public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
883        Log.i(TAG, "Granting permissions to default sms app for user:" + userId);
884        if (packageName == null) {
885            return;
886        }
887        PackageParser.Package smsPackage = getPackage(packageName);
888        if (smsPackage != null && doesPackageSupportRuntimePermissions(smsPackage)) {
889            grantRuntimePermissions(smsPackage, PHONE_PERMISSIONS, false, true, userId);
890            grantRuntimePermissions(smsPackage, CONTACTS_PERMISSIONS, false, true, userId);
891            grantRuntimePermissions(smsPackage, SMS_PERMISSIONS, false, true, userId);
892            grantRuntimePermissions(smsPackage, STORAGE_PERMISSIONS, false, true, userId);
893            grantRuntimePermissions(smsPackage, MICROPHONE_PERMISSIONS, false, true, userId);
894            grantRuntimePermissions(smsPackage, CAMERA_PERMISSIONS, false, true, userId);
895        }
896    }
897
898    public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
899        Log.i(TAG, "Granting permissions to default dialer app for user:" + userId);
900        if (packageName == null) {
901            return;
902        }
903        PackageParser.Package dialerPackage = getPackage(packageName);
904        if (dialerPackage != null
905                && doesPackageSupportRuntimePermissions(dialerPackage)) {
906            grantRuntimePermissions(dialerPackage, PHONE_PERMISSIONS, false, true, userId);
907            grantRuntimePermissions(dialerPackage, CONTACTS_PERMISSIONS, false, true, userId);
908            grantRuntimePermissions(dialerPackage, SMS_PERMISSIONS, false, true, userId);
909            grantRuntimePermissions(dialerPackage, MICROPHONE_PERMISSIONS, false, true, userId);
910            grantRuntimePermissions(dialerPackage, CAMERA_PERMISSIONS, false, true, userId);
911        }
912    }
913
914    public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
915        Log.i(TAG, "Granting permissions to default Use Open WiFi app for user:" + userId);
916        if (packageName == null) {
917            return;
918        }
919        PackageParser.Package useOpenWifiPackage = getPackage(packageName);
920        if (useOpenWifiPackage != null
921                && doesPackageSupportRuntimePermissions(useOpenWifiPackage)) {
922            grantRuntimePermissions(
923                    useOpenWifiPackage, COARSE_LOCATION_PERMISSIONS, false, true, userId);
924        }
925    }
926
927    private void grantDefaultPermissionsToDefaultSimCallManager(
928            PackageParser.Package simCallManagerPackage, int userId) {
929        Log.i(TAG, "Granting permissions to sim call manager for user:" + userId);
930        if (doesPackageSupportRuntimePermissions(simCallManagerPackage)) {
931            grantRuntimePermissions(simCallManagerPackage, PHONE_PERMISSIONS, userId);
932            grantRuntimePermissions(simCallManagerPackage, MICROPHONE_PERMISSIONS, userId);
933        }
934    }
935
936    public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
937        if (packageName == null) {
938            return;
939        }
940        PackageParser.Package simCallManagerPackage = getPackage(packageName);
941        if (simCallManagerPackage != null) {
942            grantDefaultPermissionsToDefaultSimCallManager(simCallManagerPackage, userId);
943        }
944    }
945
946    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
947        Log.i(TAG, "Granting permissions to enabled carrier apps for user:" + userId);
948        if (packageNames == null) {
949            return;
950        }
951        for (String packageName : packageNames) {
952            PackageParser.Package carrierPackage = getSystemPackage(packageName);
953            if (carrierPackage != null
954                    && doesPackageSupportRuntimePermissions(carrierPackage)) {
955                grantRuntimePermissions(carrierPackage, PHONE_PERMISSIONS, userId);
956                grantRuntimePermissions(carrierPackage, LOCATION_PERMISSIONS, userId);
957                grantRuntimePermissions(carrierPackage, SMS_PERMISSIONS, userId);
958            }
959        }
960    }
961
962    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
963        Log.i(TAG, "Granting permissions to enabled ImsServices for user:" + userId);
964        if (packageNames == null) {
965            return;
966        }
967        for (String packageName : packageNames) {
968            PackageParser.Package imsServicePackage = getSystemPackage(packageName);
969            if (imsServicePackage != null
970                    && doesPackageSupportRuntimePermissions(imsServicePackage)) {
971                grantRuntimePermissions(imsServicePackage, PHONE_PERMISSIONS, userId);
972                grantRuntimePermissions(imsServicePackage, MICROPHONE_PERMISSIONS, userId);
973                grantRuntimePermissions(imsServicePackage, LOCATION_PERMISSIONS, userId);
974                grantRuntimePermissions(imsServicePackage, CAMERA_PERMISSIONS, userId);
975            }
976        }
977    }
978
979    public void grantDefaultPermissionsToDefaultBrowser(String packageName, int userId) {
980        Log.i(TAG, "Granting permissions to default browser for user:" + userId);
981        if (packageName == null) {
982            return;
983        }
984        PackageParser.Package browserPackage = getSystemPackage(packageName);
985        if (browserPackage != null
986                && doesPackageSupportRuntimePermissions(browserPackage)) {
987            grantRuntimePermissions(browserPackage, LOCATION_PERMISSIONS, false, false, userId);
988        }
989    }
990
991    private PackageParser.Package getDefaultSystemHandlerActivityPackage(
992            Intent intent, int userId) {
993        ResolveInfo handler = mServiceInternal.resolveIntent(intent,
994                intent.resolveType(mContext.getContentResolver()), DEFAULT_FLAGS, userId, false);
995        if (handler == null || handler.activityInfo == null) {
996            return null;
997        }
998        if (mServiceInternal.isResolveActivityComponent(handler.activityInfo)) {
999            return null;
1000        }
1001        return getSystemPackage(handler.activityInfo.packageName);
1002    }
1003
1004    private PackageParser.Package getDefaultSystemHandlerServicePackage(
1005            Intent intent, int userId) {
1006        List<ResolveInfo> handlers = mServiceInternal.queryIntentServices(
1007                intent, DEFAULT_FLAGS, Binder.getCallingUid(), userId);
1008        if (handlers == null) {
1009            return null;
1010        }
1011        final int handlerCount = handlers.size();
1012        for (int i = 0; i < handlerCount; i++) {
1013            ResolveInfo handler = handlers.get(i);
1014            PackageParser.Package handlerPackage = getSystemPackage(
1015                    handler.serviceInfo.packageName);
1016            if (handlerPackage != null) {
1017                return handlerPackage;
1018            }
1019        }
1020        return null;
1021    }
1022
1023    private List<PackageParser.Package> getHeadlessSyncAdapterPackages(
1024            String[] syncAdapterPackageNames, int userId) {
1025        List<PackageParser.Package> syncAdapterPackages = new ArrayList<>();
1026
1027        Intent homeIntent = new Intent(Intent.ACTION_MAIN);
1028        homeIntent.addCategory(Intent.CATEGORY_LAUNCHER);
1029
1030        for (String syncAdapterPackageName : syncAdapterPackageNames) {
1031            homeIntent.setPackage(syncAdapterPackageName);
1032
1033            ResolveInfo homeActivity = mServiceInternal.resolveIntent(homeIntent,
1034                    homeIntent.resolveType(mContext.getContentResolver()), DEFAULT_FLAGS,
1035                    userId, false);
1036            if (homeActivity != null) {
1037                continue;
1038            }
1039
1040            PackageParser.Package syncAdapterPackage = getSystemPackage(syncAdapterPackageName);
1041            if (syncAdapterPackage != null) {
1042                syncAdapterPackages.add(syncAdapterPackage);
1043            }
1044        }
1045
1046        return syncAdapterPackages;
1047    }
1048
1049    private PackageParser.Package getDefaultProviderAuthorityPackage(
1050            String authority, int userId) {
1051        ProviderInfo provider =
1052                mServiceInternal.resolveContentProvider(authority, DEFAULT_FLAGS, userId);
1053        if (provider != null) {
1054            return getSystemPackage(provider.packageName);
1055        }
1056        return null;
1057    }
1058
1059    private PackageParser.Package getPackage(String packageName) {
1060        return mServiceInternal.getPackage(packageName);
1061    }
1062
1063    private PackageParser.Package getSystemPackage(String packageName) {
1064        PackageParser.Package pkg = getPackage(packageName);
1065        if (pkg != null && pkg.isSystem()) {
1066            return !isSysComponentOrPersistentPlatformSignedPrivApp(pkg) ? pkg : null;
1067        }
1068        return null;
1069    }
1070
1071    private void grantRuntimePermissions(PackageParser.Package pkg, Set<String> permissions,
1072            int userId) {
1073        grantRuntimePermissions(pkg, permissions, false, false, userId);
1074    }
1075
1076    private void grantRuntimePermissions(PackageParser.Package pkg, Set<String> permissions,
1077            boolean systemFixed, int userId) {
1078        grantRuntimePermissions(pkg, permissions, systemFixed, false, userId);
1079    }
1080
1081    private void grantRuntimePermissions(PackageParser.Package pkg, Set<String> permissions,
1082            boolean systemFixed, boolean ignoreSystemPackage, int userId) {
1083        if (pkg.requestedPermissions.isEmpty()) {
1084            return;
1085        }
1086
1087        List<String> requestedPermissions = pkg.requestedPermissions;
1088        Set<String> grantablePermissions = null;
1089
1090        // In some cases, like for the Phone or SMS app, we grant permissions regardless
1091        // of if the version on the system image declares the permission as used since
1092        // selecting the app as the default for that function the user makes a deliberate
1093        // choice to grant this app the permissions needed to function. For all other
1094        // apps, (default grants on first boot and user creation) we don't grant default
1095        // permissions if the version on the system image does not declare them.
1096        if (!ignoreSystemPackage && pkg.isUpdatedSystemApp()) {
1097            final PackageParser.Package disabledPkg =
1098                    mServiceInternal.getDisabledPackage(pkg.packageName);
1099            if (disabledPkg != null) {
1100                if (disabledPkg.requestedPermissions.isEmpty()) {
1101                    return;
1102                }
1103                if (!requestedPermissions.equals(disabledPkg.requestedPermissions)) {
1104                    grantablePermissions = new ArraySet<>(requestedPermissions);
1105                    requestedPermissions = disabledPkg.requestedPermissions;
1106                }
1107            }
1108        }
1109
1110        final int grantablePermissionCount = requestedPermissions.size();
1111        for (int i = 0; i < grantablePermissionCount; i++) {
1112            String permission = requestedPermissions.get(i);
1113
1114            // If there is a disabled system app it may request a permission the updated
1115            // version ot the data partition doesn't, In this case skip the permission.
1116            if (grantablePermissions != null && !grantablePermissions.contains(permission)) {
1117                continue;
1118            }
1119
1120            if (permissions.contains(permission)) {
1121                final int flags = mServiceInternal.getPermissionFlagsTEMP(
1122                        permission, pkg.packageName, userId);
1123
1124                // If any flags are set to the permission, then it is either set in
1125                // its current state by the system or device/profile owner or the user.
1126                // In all these cases we do not want to clobber the current state.
1127                // Unless the caller wants to override user choices. The override is
1128                // to make sure we can grant the needed permission to the default
1129                // sms and phone apps after the user chooses this in the UI.
1130                if (flags == 0 || ignoreSystemPackage) {
1131                    // Never clobber policy or system.
1132                    final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1133                            | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1134                    if ((flags & fixedFlags) != 0) {
1135                        continue;
1136                    }
1137
1138                    mServiceInternal.grantRuntimePermission(
1139                            pkg.packageName, permission, userId, false);
1140                    if (DEBUG) {
1141                        Log.i(TAG, "Granted " + (systemFixed ? "fixed " : "not fixed ")
1142                                + permission + " to default handler " + pkg.packageName);
1143                    }
1144
1145                    int newFlags = PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1146                    if (systemFixed) {
1147                        newFlags |= PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
1148                    }
1149
1150                    mServiceInternal.updatePermissionFlagsTEMP(permission, pkg.packageName,
1151                            newFlags, newFlags, userId);
1152                }
1153
1154                // If a component gets a permission for being the default handler A
1155                // and also default handler B, we grant the weaker grant form.
1156                if ((flags & PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0
1157                        && (flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0
1158                        && !systemFixed) {
1159                    if (DEBUG) {
1160                        Log.i(TAG, "Granted not fixed " + permission + " to default handler "
1161                                + pkg.packageName);
1162                    }
1163                    mServiceInternal.updatePermissionFlagsTEMP(permission, pkg.packageName,
1164                            PackageManager.FLAG_PERMISSION_SYSTEM_FIXED, 0, userId);
1165                }
1166            }
1167        }
1168    }
1169
1170    private boolean isSysComponentOrPersistentPlatformSignedPrivApp(PackageParser.Package pkg) {
1171        if (UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID) {
1172            return true;
1173        }
1174        if (!pkg.isPrivileged()) {
1175            return false;
1176        }
1177        final PackageParser.Package disabledPkg =
1178                mServiceInternal.getDisabledPackage(pkg.packageName);
1179        if (disabledPkg != null) {
1180            if ((disabledPkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) == 0) {
1181                return false;
1182            }
1183        } else if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) == 0) {
1184            return false;
1185        }
1186        final String systemPackageName = mServiceInternal.getKnownPackageName(
1187                PackageManagerInternal.PACKAGE_SYSTEM, UserHandle.USER_SYSTEM);
1188        final PackageParser.Package systemPackage = getPackage(systemPackageName);
1189        return pkg.mSigningDetails.hasAncestorOrSelf(systemPackage.mSigningDetails)
1190                || systemPackage.mSigningDetails.checkCapability(pkg.mSigningDetails,
1191                        PackageParser.SigningDetails.CertCapabilities.PERMISSION);
1192    }
1193
1194    private void grantDefaultPermissionExceptions(int userId) {
1195        mHandler.removeMessages(MSG_READ_DEFAULT_PERMISSION_EXCEPTIONS);
1196
1197        synchronized (mLock) {
1198            // mGrantExceptions is null only before the first read and then
1199            // it serves as a cache of the default grants that should be
1200            // performed for every user. If there is an entry then the app
1201            // is on the system image and supports runtime permissions.
1202            if (mGrantExceptions == null) {
1203                mGrantExceptions = readDefaultPermissionExceptionsLocked();
1204            }
1205        }
1206
1207        Set<String> permissions = null;
1208        final int exceptionCount = mGrantExceptions.size();
1209        for (int i = 0; i < exceptionCount; i++) {
1210            String packageName = mGrantExceptions.keyAt(i);
1211            PackageParser.Package pkg = getSystemPackage(packageName);
1212            List<DefaultPermissionGrant> permissionGrants = mGrantExceptions.valueAt(i);
1213            final int permissionGrantCount = permissionGrants.size();
1214            for (int j = 0; j < permissionGrantCount; j++) {
1215                DefaultPermissionGrant permissionGrant = permissionGrants.get(j);
1216                if (permissions == null) {
1217                    permissions = new ArraySet<>();
1218                } else {
1219                    permissions.clear();
1220                }
1221                permissions.add(permissionGrant.name);
1222                grantRuntimePermissions(pkg, permissions,
1223                        permissionGrant.fixed, userId);
1224            }
1225        }
1226    }
1227
1228    private File[] getDefaultPermissionFiles() {
1229        ArrayList<File> ret = new ArrayList<File>();
1230        File dir = new File(Environment.getRootDirectory(), "etc/default-permissions");
1231        if (dir.isDirectory() && dir.canRead()) {
1232            Collections.addAll(ret, dir.listFiles());
1233        }
1234        dir = new File(Environment.getVendorDirectory(), "etc/default-permissions");
1235        if (dir.isDirectory() && dir.canRead()) {
1236            Collections.addAll(ret, dir.listFiles());
1237        }
1238        dir = new File(Environment.getOdmDirectory(), "etc/default-permissions");
1239        if (dir.isDirectory() && dir.canRead()) {
1240            Collections.addAll(ret, dir.listFiles());
1241        }
1242        dir = new File(Environment.getProductDirectory(), "etc/default-permissions");
1243        if (dir.isDirectory() && dir.canRead()) {
1244            Collections.addAll(ret, dir.listFiles());
1245        }
1246        // For IoT devices, we check the oem partition for default permissions for each app.
1247        if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_EMBEDDED, 0)) {
1248            dir = new File(Environment.getOemDirectory(), "etc/default-permissions");
1249            if (dir.isDirectory() && dir.canRead()) {
1250                Collections.addAll(ret, dir.listFiles());
1251            }
1252        }
1253        return ret.isEmpty() ? null : ret.toArray(new File[0]);
1254    }
1255
1256    private @NonNull ArrayMap<String, List<DefaultPermissionGrant>>
1257            readDefaultPermissionExceptionsLocked() {
1258        File[] files = getDefaultPermissionFiles();
1259        if (files == null) {
1260            return new ArrayMap<>(0);
1261        }
1262
1263        ArrayMap<String, List<DefaultPermissionGrant>> grantExceptions = new ArrayMap<>();
1264
1265        // Iterate over the files in the directory and scan .xml files
1266        for (File file : files) {
1267            if (!file.getPath().endsWith(".xml")) {
1268                Slog.i(TAG, "Non-xml file " + file
1269                        + " in " + file.getParent() + " directory, ignoring");
1270                continue;
1271            }
1272            if (!file.canRead()) {
1273                Slog.w(TAG, "Default permissions file " + file + " cannot be read");
1274                continue;
1275            }
1276            try (
1277                InputStream str = new BufferedInputStream(new FileInputStream(file))
1278            ) {
1279                XmlPullParser parser = Xml.newPullParser();
1280                parser.setInput(str, null);
1281                parse(parser, grantExceptions);
1282            } catch (XmlPullParserException | IOException e) {
1283                Slog.w(TAG, "Error reading default permissions file " + file, e);
1284            }
1285        }
1286
1287        return grantExceptions;
1288    }
1289
1290    private void parse(XmlPullParser parser, Map<String, List<DefaultPermissionGrant>>
1291            outGrantExceptions) throws IOException, XmlPullParserException {
1292        final int outerDepth = parser.getDepth();
1293        int type;
1294        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1295                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1296            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1297                continue;
1298            }
1299            if (TAG_EXCEPTIONS.equals(parser.getName())) {
1300                parseExceptions(parser, outGrantExceptions);
1301            } else {
1302                Log.e(TAG, "Unknown tag " + parser.getName());
1303            }
1304        }
1305    }
1306
1307    private void parseExceptions(XmlPullParser parser, Map<String, List<DefaultPermissionGrant>>
1308            outGrantExceptions) throws IOException, XmlPullParserException {
1309        final int outerDepth = parser.getDepth();
1310        int type;
1311        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1312                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1313            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1314                continue;
1315            }
1316            if (TAG_EXCEPTION.equals(parser.getName())) {
1317                String packageName = parser.getAttributeValue(null, ATTR_PACKAGE);
1318
1319                List<DefaultPermissionGrant> packageExceptions =
1320                        outGrantExceptions.get(packageName);
1321                if (packageExceptions == null) {
1322                    // The package must be on the system image
1323                    PackageParser.Package pkg = getSystemPackage(packageName);
1324                    if (pkg == null) {
1325                        Log.w(TAG, "Unknown package:" + packageName);
1326                        XmlUtils.skipCurrentTag(parser);
1327                        continue;
1328                    }
1329
1330                    // The package must support runtime permissions
1331                    if (!doesPackageSupportRuntimePermissions(pkg)) {
1332                        Log.w(TAG, "Skipping non supporting runtime permissions package:"
1333                                + packageName);
1334                        XmlUtils.skipCurrentTag(parser);
1335                        continue;
1336                    }
1337                    packageExceptions = new ArrayList<>();
1338                    outGrantExceptions.put(packageName, packageExceptions);
1339                }
1340
1341                parsePermission(parser, packageExceptions);
1342            } else {
1343                Log.e(TAG, "Unknown tag " + parser.getName() + "under <exceptions>");
1344            }
1345        }
1346    }
1347
1348    private void parsePermission(XmlPullParser parser, List<DefaultPermissionGrant>
1349            outPackageExceptions) throws IOException, XmlPullParserException {
1350        final int outerDepth = parser.getDepth();
1351        int type;
1352        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1353                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1354            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1355                continue;
1356            }
1357
1358            if (TAG_PERMISSION.contains(parser.getName())) {
1359                String name = parser.getAttributeValue(null, ATTR_NAME);
1360                if (name == null) {
1361                    Log.w(TAG, "Mandatory name attribute missing for permission tag");
1362                    XmlUtils.skipCurrentTag(parser);
1363                    continue;
1364                }
1365
1366                final boolean fixed = XmlUtils.readBooleanAttribute(parser, ATTR_FIXED);
1367
1368                DefaultPermissionGrant exception = new DefaultPermissionGrant(name, fixed);
1369                outPackageExceptions.add(exception);
1370            } else {
1371                Log.e(TAG, "Unknown tag " + parser.getName() + "under <exception>");
1372            }
1373        }
1374    }
1375
1376    private static boolean doesPackageSupportRuntimePermissions(PackageParser.Package pkg) {
1377        return pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1;
1378    }
1379
1380    private static final class DefaultPermissionGrant {
1381        final String name;
1382        final boolean fixed;
1383
1384        public DefaultPermissionGrant(String name, boolean fixed) {
1385            this.name = name;
1386            this.fixed = fixed;
1387        }
1388    }
1389}
1390