1/*
2 * Copyright (C) 2014 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;
18
19import android.app.AppGlobals;
20import android.content.ComponentName;
21import android.content.Context;
22import android.content.Intent;
23import android.content.pm.ActivityInfo;
24import android.content.pm.ILauncherApps;
25import android.content.pm.IOnAppsChangedListener;
26import android.content.pm.IPackageManager;
27import android.content.pm.PackageManager;
28import android.content.pm.PackageInfo;
29import android.content.pm.ResolveInfo;
30import android.content.pm.UserInfo;
31import android.graphics.Rect;
32import android.net.Uri;
33import android.os.Binder;
34import android.os.Bundle;
35import android.os.IInterface;
36import android.os.RemoteCallbackList;
37import android.os.RemoteException;
38import android.os.UserHandle;
39import android.os.UserManager;
40import android.provider.Settings;
41import android.util.Log;
42import android.util.Slog;
43
44import com.android.internal.content.PackageMonitor;
45import com.android.server.SystemService;
46
47import java.util.ArrayList;
48import java.util.List;
49
50/**
51 * Service that manages requests and callbacks for launchers that support
52 * managed profiles.
53 */
54
55public class LauncherAppsService extends SystemService {
56
57    private final LauncherAppsImpl mLauncherAppsImpl;
58
59    public LauncherAppsService(Context context) {
60        super(context);
61        mLauncherAppsImpl = new LauncherAppsImpl(context);
62    }
63
64    @Override
65    public void onStart() {
66        publishBinderService(Context.LAUNCHER_APPS_SERVICE, mLauncherAppsImpl);
67    }
68
69    class LauncherAppsImpl extends ILauncherApps.Stub {
70        private static final boolean DEBUG = false;
71        private static final String TAG = "LauncherAppsService";
72        private final Context mContext;
73        private final PackageManager mPm;
74        private final UserManager mUm;
75        private final PackageCallbackList<IOnAppsChangedListener> mListeners
76                = new PackageCallbackList<IOnAppsChangedListener>();
77
78        private MyPackageMonitor mPackageMonitor = new MyPackageMonitor();
79
80        public LauncherAppsImpl(Context context) {
81            mContext = context;
82            mPm = mContext.getPackageManager();
83            mUm = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
84        }
85
86        /*
87         * @see android.content.pm.ILauncherApps#addOnAppsChangedListener(
88         *          android.content.pm.IOnAppsChangedListener)
89         */
90        @Override
91        public void addOnAppsChangedListener(IOnAppsChangedListener listener) throws RemoteException {
92            synchronized (mListeners) {
93                if (DEBUG) {
94                    Log.d(TAG, "Adding listener from " + Binder.getCallingUserHandle());
95                }
96                if (mListeners.getRegisteredCallbackCount() == 0) {
97                    if (DEBUG) {
98                        Log.d(TAG, "Starting package monitoring");
99                    }
100                    startWatchingPackageBroadcasts();
101                }
102                mListeners.unregister(listener);
103                mListeners.register(listener, Binder.getCallingUserHandle());
104            }
105        }
106
107        /*
108         * @see android.content.pm.ILauncherApps#removeOnAppsChangedListener(
109         *          android.content.pm.IOnAppsChangedListener)
110         */
111        @Override
112        public void removeOnAppsChangedListener(IOnAppsChangedListener listener)
113                throws RemoteException {
114            synchronized (mListeners) {
115                if (DEBUG) {
116                    Log.d(TAG, "Removing listener from " + Binder.getCallingUserHandle());
117                }
118                mListeners.unregister(listener);
119                if (mListeners.getRegisteredCallbackCount() == 0) {
120                    stopWatchingPackageBroadcasts();
121                }
122            }
123        }
124
125        /**
126         * Register a receiver to watch for package broadcasts
127         */
128        private void startWatchingPackageBroadcasts() {
129            mPackageMonitor.register(mContext, null, UserHandle.ALL, true);
130        }
131
132        /**
133         * Unregister package broadcast receiver
134         */
135        private void stopWatchingPackageBroadcasts() {
136            if (DEBUG) {
137                Log.d(TAG, "Stopped watching for packages");
138            }
139            mPackageMonitor.unregister();
140        }
141
142        void checkCallbackCount() {
143            synchronized (mListeners) {
144                if (DEBUG) {
145                    Log.d(TAG, "Callback count = " + mListeners.getRegisteredCallbackCount());
146                }
147                if (mListeners.getRegisteredCallbackCount() == 0) {
148                    stopWatchingPackageBroadcasts();
149                }
150            }
151        }
152
153        /**
154         * Checks if the caller is in the same group as the userToCheck.
155         */
156        private void ensureInUserProfiles(UserHandle userToCheck, String message) {
157            final int callingUserId = UserHandle.getCallingUserId();
158            final int targetUserId = userToCheck.getIdentifier();
159
160            if (targetUserId == callingUserId) return;
161
162            long ident = Binder.clearCallingIdentity();
163            try {
164                UserInfo callingUserInfo = mUm.getUserInfo(callingUserId);
165                UserInfo targetUserInfo = mUm.getUserInfo(targetUserId);
166                if (targetUserInfo == null
167                        || targetUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID
168                        || targetUserInfo.profileGroupId != callingUserInfo.profileGroupId) {
169                    throw new SecurityException(message);
170                }
171            } finally {
172                Binder.restoreCallingIdentity(ident);
173            }
174        }
175
176        /**
177         * Checks if the user is enabled.
178         */
179        private boolean isUserEnabled(UserHandle user) {
180            long ident = Binder.clearCallingIdentity();
181            try {
182                UserInfo targetUserInfo = mUm.getUserInfo(user.getIdentifier());
183                return targetUserInfo != null && targetUserInfo.isEnabled();
184            } finally {
185                Binder.restoreCallingIdentity(ident);
186            }
187        }
188
189        @Override
190        public List<ResolveInfo> getLauncherActivities(String packageName, UserHandle user)
191                throws RemoteException {
192            ensureInUserProfiles(user, "Cannot retrieve activities for unrelated profile " + user);
193            if (!isUserEnabled(user)) {
194                return new ArrayList<ResolveInfo>();
195            }
196
197            final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
198            mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
199            mainIntent.setPackage(packageName);
200            long ident = Binder.clearCallingIdentity();
201            try {
202                List<ResolveInfo> apps = mPm.queryIntentActivitiesAsUser(mainIntent, 0 /* flags */,
203                        user.getIdentifier());
204                return apps;
205            } finally {
206                Binder.restoreCallingIdentity(ident);
207            }
208        }
209
210        @Override
211        public ResolveInfo resolveActivity(Intent intent, UserHandle user)
212                throws RemoteException {
213            ensureInUserProfiles(user, "Cannot resolve activity for unrelated profile " + user);
214            if (!isUserEnabled(user)) {
215                return null;
216            }
217
218            long ident = Binder.clearCallingIdentity();
219            try {
220                ResolveInfo app = mPm.resolveActivityAsUser(intent, 0, user.getIdentifier());
221                return app;
222            } finally {
223                Binder.restoreCallingIdentity(ident);
224            }
225        }
226
227        @Override
228        public boolean isPackageEnabled(String packageName, UserHandle user)
229                throws RemoteException {
230            ensureInUserProfiles(user, "Cannot check package for unrelated profile " + user);
231            if (!isUserEnabled(user)) {
232                return false;
233            }
234
235            long ident = Binder.clearCallingIdentity();
236            try {
237                IPackageManager pm = AppGlobals.getPackageManager();
238                PackageInfo info = pm.getPackageInfo(packageName, 0, user.getIdentifier());
239                return info != null && info.applicationInfo.enabled;
240            } finally {
241                Binder.restoreCallingIdentity(ident);
242            }
243        }
244
245        @Override
246        public boolean isActivityEnabled(ComponentName component, UserHandle user)
247                throws RemoteException {
248            ensureInUserProfiles(user, "Cannot check component for unrelated profile " + user);
249            if (!isUserEnabled(user)) {
250                return false;
251            }
252
253            long ident = Binder.clearCallingIdentity();
254            try {
255                IPackageManager pm = AppGlobals.getPackageManager();
256                ActivityInfo info = pm.getActivityInfo(component, 0, user.getIdentifier());
257                return info != null;
258            } finally {
259                Binder.restoreCallingIdentity(ident);
260            }
261        }
262
263        @Override
264        public void startActivityAsUser(ComponentName component, Rect sourceBounds,
265                Bundle opts, UserHandle user) throws RemoteException {
266            ensureInUserProfiles(user, "Cannot start activity for unrelated profile " + user);
267            if (!isUserEnabled(user)) {
268                throw new IllegalStateException("Cannot start activity for disabled profile "  + user);
269            }
270
271            Intent launchIntent = new Intent(Intent.ACTION_MAIN);
272            launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
273            launchIntent.setSourceBounds(sourceBounds);
274            launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
275                    | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
276            launchIntent.setPackage(component.getPackageName());
277
278            long ident = Binder.clearCallingIdentity();
279            try {
280                IPackageManager pm = AppGlobals.getPackageManager();
281                ActivityInfo info = pm.getActivityInfo(component, 0, user.getIdentifier());
282                if (!info.exported) {
283                    throw new SecurityException("Cannot launch non-exported components "
284                            + component);
285                }
286
287                // Check that the component actually has Intent.CATEGORY_LAUCNCHER
288                // as calling startActivityAsUser ignores the category and just
289                // resolves based on the component if present.
290                List<ResolveInfo> apps = mPm.queryIntentActivitiesAsUser(launchIntent,
291                        0 /* flags */, user.getIdentifier());
292                final int size = apps.size();
293                for (int i = 0; i < size; ++i) {
294                    ActivityInfo activityInfo = apps.get(i).activityInfo;
295                    if (activityInfo.packageName.equals(component.getPackageName()) &&
296                            activityInfo.name.equals(component.getClassName())) {
297                        // Found an activity with category launcher that matches
298                        // this component so ok to launch.
299                        launchIntent.setComponent(component);
300                        mContext.startActivityAsUser(launchIntent, opts, user);
301                        return;
302                    }
303                }
304                throw new SecurityException("Attempt to launch activity without "
305                        + " category Intent.CATEGORY_LAUNCHER " + component);
306            } finally {
307                Binder.restoreCallingIdentity(ident);
308            }
309        }
310
311        @Override
312        public void showAppDetailsAsUser(ComponentName component, Rect sourceBounds,
313                Bundle opts, UserHandle user) throws RemoteException {
314            ensureInUserProfiles(user, "Cannot show app details for unrelated profile " + user);
315            if (!isUserEnabled(user)) {
316                throw new IllegalStateException("Cannot show app details for disabled profile "
317                        + user);
318            }
319
320            long ident = Binder.clearCallingIdentity();
321            try {
322                String packageName = component.getPackageName();
323                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
324                        Uri.fromParts("package", packageName, null));
325                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK |
326                        Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
327                intent.setSourceBounds(sourceBounds);
328                mContext.startActivityAsUser(intent, opts, user);
329            } finally {
330                Binder.restoreCallingIdentity(ident);
331            }
332        }
333
334
335        private class MyPackageMonitor extends PackageMonitor {
336
337            /** Checks if user is a profile of or same as listeningUser.
338              * and the user is enabled. */
339            private boolean isEnabledProfileOf(UserHandle user, UserHandle listeningUser,
340                    String debugMsg) {
341                if (user.getIdentifier() == listeningUser.getIdentifier()) {
342                    if (DEBUG) Log.d(TAG, "Delivering msg to same user " + debugMsg);
343                    return true;
344                }
345                long ident = Binder.clearCallingIdentity();
346                try {
347                    UserInfo userInfo = mUm.getUserInfo(user.getIdentifier());
348                    UserInfo listeningUserInfo = mUm.getUserInfo(listeningUser.getIdentifier());
349                    if (userInfo == null || listeningUserInfo == null
350                            || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID
351                            || userInfo.profileGroupId != listeningUserInfo.profileGroupId
352                            || !userInfo.isEnabled()) {
353                        if (DEBUG) {
354                            Log.d(TAG, "Not delivering msg from " + user + " to " + listeningUser + ":"
355                                    + debugMsg);
356                        }
357                        return false;
358                    } else {
359                        if (DEBUG) {
360                            Log.d(TAG, "Delivering msg from " + user + " to " + listeningUser + ":"
361                                    + debugMsg);
362                        }
363                        return true;
364                    }
365                } finally {
366                    Binder.restoreCallingIdentity(ident);
367                }
368            }
369
370            @Override
371            public void onPackageAdded(String packageName, int uid) {
372                UserHandle user = new UserHandle(getChangingUserId());
373                final int n = mListeners.beginBroadcast();
374                for (int i = 0; i < n; i++) {
375                    IOnAppsChangedListener listener = mListeners.getBroadcastItem(i);
376                    UserHandle listeningUser = (UserHandle) mListeners.getBroadcastCookie(i);
377                    if (!isEnabledProfileOf(user, listeningUser, "onPackageAdded")) continue;
378                    try {
379                        listener.onPackageAdded(user, packageName);
380                    } catch (RemoteException re) {
381                        Slog.d(TAG, "Callback failed ", re);
382                    }
383                }
384                mListeners.finishBroadcast();
385
386                super.onPackageAdded(packageName, uid);
387            }
388
389            @Override
390            public void onPackageRemoved(String packageName, int uid) {
391                UserHandle user = new UserHandle(getChangingUserId());
392                final int n = mListeners.beginBroadcast();
393                for (int i = 0; i < n; i++) {
394                    IOnAppsChangedListener listener = mListeners.getBroadcastItem(i);
395                    UserHandle listeningUser = (UserHandle) mListeners.getBroadcastCookie(i);
396                    if (!isEnabledProfileOf(user, listeningUser, "onPackageRemoved")) continue;
397                    try {
398                        listener.onPackageRemoved(user, packageName);
399                    } catch (RemoteException re) {
400                        Slog.d(TAG, "Callback failed ", re);
401                    }
402                }
403                mListeners.finishBroadcast();
404
405                super.onPackageRemoved(packageName, uid);
406            }
407
408            @Override
409            public void onPackageModified(String packageName) {
410                UserHandle user = new UserHandle(getChangingUserId());
411                final int n = mListeners.beginBroadcast();
412                for (int i = 0; i < n; i++) {
413                    IOnAppsChangedListener listener = mListeners.getBroadcastItem(i);
414                    UserHandle listeningUser = (UserHandle) mListeners.getBroadcastCookie(i);
415                    if (!isEnabledProfileOf(user, listeningUser, "onPackageModified")) continue;
416                    try {
417                        listener.onPackageChanged(user, packageName);
418                    } catch (RemoteException re) {
419                        Slog.d(TAG, "Callback failed ", re);
420                    }
421                }
422                mListeners.finishBroadcast();
423
424                super.onPackageModified(packageName);
425            }
426
427            @Override
428            public void onPackagesAvailable(String[] packages) {
429                UserHandle user = new UserHandle(getChangingUserId());
430                final int n = mListeners.beginBroadcast();
431                for (int i = 0; i < n; i++) {
432                    IOnAppsChangedListener listener = mListeners.getBroadcastItem(i);
433                    UserHandle listeningUser = (UserHandle) mListeners.getBroadcastCookie(i);
434                    if (!isEnabledProfileOf(user, listeningUser, "onPackagesAvailable")) continue;
435                    try {
436                        listener.onPackagesAvailable(user, packages, isReplacing());
437                    } catch (RemoteException re) {
438                        Slog.d(TAG, "Callback failed ", re);
439                    }
440                }
441                mListeners.finishBroadcast();
442
443                super.onPackagesAvailable(packages);
444            }
445
446            @Override
447            public void onPackagesUnavailable(String[] packages) {
448                UserHandle user = new UserHandle(getChangingUserId());
449                final int n = mListeners.beginBroadcast();
450                for (int i = 0; i < n; i++) {
451                    IOnAppsChangedListener listener = mListeners.getBroadcastItem(i);
452                    UserHandle listeningUser = (UserHandle) mListeners.getBroadcastCookie(i);
453                    if (!isEnabledProfileOf(user, listeningUser, "onPackagesUnavailable")) continue;
454                    try {
455                        listener.onPackagesUnavailable(user, packages, isReplacing());
456                    } catch (RemoteException re) {
457                        Slog.d(TAG, "Callback failed ", re);
458                    }
459                }
460                mListeners.finishBroadcast();
461
462                super.onPackagesUnavailable(packages);
463            }
464
465        }
466
467        class PackageCallbackList<T extends IInterface> extends RemoteCallbackList<T> {
468            @Override
469            public void onCallbackDied(T callback, Object cookie) {
470                checkCallbackCount();
471            }
472        }
473    }
474}
475