blob: e8f255f4dfc1376ac34c1aa4fa6915bcc4f81e8c [file] [log] [blame]
Jason Monk8f5f7ff2017-10-17 14:12:42 -04001/*
2 * Copyright (C) 2017 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.slice;
18
Jason Monk1918ef72018-03-14 09:20:39 -040019import static android.app.usage.UsageEvents.Event.SLICE_PINNED;
20import static android.app.usage.UsageEvents.Event.SLICE_PINNED_PRIV;
Jason Monke8f8be72018-01-21 10:10:35 -050021import static android.content.ContentProvider.getUriWithoutUserId;
Jason Monk74f5e362017-12-06 08:56:33 -050022import static android.content.ContentProvider.getUserIdFromUri;
23import static android.content.ContentProvider.maybeAddUserId;
Jason Monk3a1d2e972018-01-29 16:58:11 -050024import static android.content.pm.PackageManager.PERMISSION_DENIED;
25import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Jason Monkb715b042018-02-01 15:00:05 -050026import static android.os.Process.SYSTEM_UID;
Jason Monk8f5f7ff2017-10-17 14:12:42 -040027
Jason Monk74f5e362017-12-06 08:56:33 -050028import android.Manifest.permission;
Jason Monke8f8be72018-01-21 10:10:35 -050029import android.app.ActivityManager;
Jason Monk74f5e362017-12-06 08:56:33 -050030import android.app.AppOpsManager;
Jason Monke8f8be72018-01-21 10:10:35 -050031import android.app.ContentProviderHolder;
32import android.app.IActivityManager;
Jason Monk74f5e362017-12-06 08:56:33 -050033import android.app.slice.ISliceManager;
34import android.app.slice.SliceSpec;
Jason Monk1918ef72018-03-14 09:20:39 -040035import android.app.usage.UsageStatsManagerInternal;
Jason Monk68ff6aa2018-01-31 15:51:52 -050036import android.content.BroadcastReceiver;
Jason Monk74f5e362017-12-06 08:56:33 -050037import android.content.ComponentName;
Jason Monkbf3eedc2018-04-05 20:56:42 -040038import android.content.ContentProvider;
Jason Monk7f01f3b2018-05-15 15:46:26 -040039import android.content.ContentResolver;
Jason Monk74f5e362017-12-06 08:56:33 -050040import android.content.Context;
41import android.content.Intent;
Jason Monk68ff6aa2018-01-31 15:51:52 -050042import android.content.IntentFilter;
Jason Monkbf3eedc2018-04-05 20:56:42 -040043import android.content.pm.PackageManager;
Jason Monk74f5e362017-12-06 08:56:33 -050044import android.content.pm.PackageManagerInternal;
Jason Monkda90df72018-07-03 11:21:57 -040045import android.content.pm.ProviderInfo;
Jason Monk74f5e362017-12-06 08:56:33 -050046import android.content.pm.ResolveInfo;
Jason Monk74f5e362017-12-06 08:56:33 -050047import android.net.Uri;
48import android.os.Binder;
49import android.os.Handler;
Jason Monke8f8be72018-01-21 10:10:35 -050050import android.os.IBinder;
Jason Monk74f5e362017-12-06 08:56:33 -050051import android.os.Looper;
52import android.os.Process;
53import android.os.RemoteException;
Jason Monk7f01f3b2018-05-15 15:46:26 -040054import android.os.ResultReceiver;
55import android.os.ShellCallback;
Jason Monk3a1d2e972018-01-29 16:58:11 -050056import android.os.UserHandle;
Jason Monk74f5e362017-12-06 08:56:33 -050057import android.util.ArrayMap;
Jason Monkddb8a962018-01-30 13:27:33 -050058import android.util.Slog;
Jason Monke009a8e2018-05-21 13:36:21 -040059import android.util.SparseArray;
Jason Monkddb8a962018-01-30 13:27:33 -050060import android.util.Xml.Encoding;
Jason Monk74f5e362017-12-06 08:56:33 -050061
62import com.android.internal.annotations.GuardedBy;
63import com.android.internal.annotations.VisibleForTesting;
64import com.android.internal.app.AssistUtils;
65import com.android.internal.util.Preconditions;
66import com.android.server.LocalServices;
67import com.android.server.ServiceThread;
Jason Monk8f5f7ff2017-10-17 14:12:42 -040068import com.android.server.SystemService;
69
Jason Monkddb8a962018-01-30 13:27:33 -050070import org.xmlpull.v1.XmlPullParser;
71import org.xmlpull.v1.XmlPullParserException;
72import org.xmlpull.v1.XmlPullParserFactory;
73import org.xmlpull.v1.XmlSerializer;
74
Jason Monkb715b042018-02-01 15:00:05 -050075import java.io.ByteArrayInputStream;
76import java.io.ByteArrayOutputStream;
Jason Monk7f01f3b2018-05-15 15:46:26 -040077import java.io.FileDescriptor;
Jason Monkddb8a962018-01-30 13:27:33 -050078import java.io.IOException;
Jason Monk74f5e362017-12-06 08:56:33 -050079import java.util.ArrayList;
80import java.util.List;
81import java.util.Objects;
Jason Monke009a8e2018-05-21 13:36:21 -040082import java.util.function.Supplier;
Jason Monk74f5e362017-12-06 08:56:33 -050083
Jason Monk8f5f7ff2017-10-17 14:12:42 -040084public class SliceManagerService extends ISliceManager.Stub {
85
Jason Monk74f5e362017-12-06 08:56:33 -050086 private static final String TAG = "SliceManagerService";
87 private final Object mLock = new Object();
Jason Monk8f5f7ff2017-10-17 14:12:42 -040088
Jason Monk74f5e362017-12-06 08:56:33 -050089 private final Context mContext;
90 private final PackageManagerInternal mPackageManagerInternal;
91 private final AppOpsManager mAppOps;
92 private final AssistUtils mAssistUtils;
93
94 @GuardedBy("mLock")
95 private final ArrayMap<Uri, PinnedSliceState> mPinnedSlicesByUri = new ArrayMap<>();
Jason Monke009a8e2018-05-21 13:36:21 -040096 @GuardedBy("mLock")
97 private final SparseArray<PackageMatchingCache> mAssistantLookup = new SparseArray<>();
98 @GuardedBy("mLock")
99 private final SparseArray<PackageMatchingCache> mHomeLookup = new SparseArray<>();
Jason Monk74f5e362017-12-06 08:56:33 -0500100 private final Handler mHandler;
Jason Monkbf3eedc2018-04-05 20:56:42 -0400101
102 private final SlicePermissionManager mPermissions;
Jason Monk1918ef72018-03-14 09:20:39 -0400103 private final UsageStatsManagerInternal mAppUsageStats;
Jason Monk74f5e362017-12-06 08:56:33 -0500104
105 public SliceManagerService(Context context) {
106 this(context, createHandler().getLooper());
Jason Monk8f5f7ff2017-10-17 14:12:42 -0400107 }
108
Jason Monk74f5e362017-12-06 08:56:33 -0500109 @VisibleForTesting
110 SliceManagerService(Context context, Looper looper) {
111 mContext = context;
112 mPackageManagerInternal = Preconditions.checkNotNull(
113 LocalServices.getService(PackageManagerInternal.class));
114 mAppOps = context.getSystemService(AppOpsManager.class);
115 mAssistUtils = new AssistUtils(context);
116 mHandler = new Handler(looper);
117
Jason Monk1918ef72018-03-14 09:20:39 -0400118 mAppUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Jason Monkddb8a962018-01-30 13:27:33 -0500119
Jason Monkbf3eedc2018-04-05 20:56:42 -0400120 mPermissions = new SlicePermissionManager(mContext, looper);
Jason Monk68ff6aa2018-01-31 15:51:52 -0500121
122 IntentFilter filter = new IntentFilter();
123 filter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED);
124 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
125 filter.addDataScheme("package");
126 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
Jason Monk74f5e362017-12-06 08:56:33 -0500127 }
128
129 /// ----- Lifecycle stuff -----
Jason Monk8f5f7ff2017-10-17 14:12:42 -0400130 private void systemReady() {
131 }
132
Jason Monk74f5e362017-12-06 08:56:33 -0500133 private void onUnlockUser(int userId) {
134 }
135
136 private void onStopUser(int userId) {
137 synchronized (mLock) {
138 mPinnedSlicesByUri.values().removeIf(s -> getUserIdFromUri(s.getUri()) == userId);
139 }
140 }
141
142 /// ----- ISliceManager stuff -----
143 @Override
Jason Monkf88d25e2018-03-06 20:13:24 -0500144 public Uri[] getPinnedSlices(String pkg) {
145 verifyCaller(pkg);
Jason Monk199286b2018-04-12 19:47:50 -0400146 int callingUser = Binder.getCallingUserHandle().getIdentifier();
Jason Monkf88d25e2018-03-06 20:13:24 -0500147 ArrayList<Uri> ret = new ArrayList<>();
148 synchronized (mLock) {
149 for (PinnedSliceState state : mPinnedSlicesByUri.values()) {
150 if (Objects.equals(pkg, state.getPkg())) {
Jason Monk199286b2018-04-12 19:47:50 -0400151 Uri uri = state.getUri();
152 int userId = ContentProvider.getUserIdFromUri(uri, callingUser);
153 if (userId == callingUser) {
154 ret.add(ContentProvider.getUriWithoutUserId(uri));
155 }
Jason Monkf88d25e2018-03-06 20:13:24 -0500156 }
157 }
158 }
159 return ret.toArray(new Uri[ret.size()]);
160 }
161
162 @Override
Jason Monk42e03f82018-03-30 11:26:56 -0400163 public void pinSlice(String pkg, Uri uri, SliceSpec[] specs, IBinder token)
164 throws RemoteException {
Jason Monk74f5e362017-12-06 08:56:33 -0500165 verifyCaller(pkg);
Jason Monk38df2802018-02-22 19:28:12 -0500166 enforceAccess(pkg, uri);
Jason Monk1918ef72018-03-14 09:20:39 -0400167 int user = Binder.getCallingUserHandle().getIdentifier();
168 uri = maybeAddUserId(uri, user);
Jason Monk397f6d82018-04-24 17:01:11 -0400169 String slicePkg = getProviderPkg(uri, user);
170 getOrCreatePinnedSlice(uri, slicePkg).pin(pkg, specs, token);
Jason Monk1918ef72018-03-14 09:20:39 -0400171
Jason Monk1918ef72018-03-14 09:20:39 -0400172 mHandler.post(() -> {
Jason Monk1918ef72018-03-14 09:20:39 -0400173 if (slicePkg != null && !Objects.equals(pkg, slicePkg)) {
174 mAppUsageStats.reportEvent(slicePkg, user,
175 isAssistant(pkg, user) || isDefaultHomeApp(pkg, user)
176 ? SLICE_PINNED_PRIV : SLICE_PINNED);
177 }
178 });
Jason Monk74f5e362017-12-06 08:56:33 -0500179 }
180
181 @Override
Jason Monk38df2802018-02-22 19:28:12 -0500182 public void unpinSlice(String pkg, Uri uri, IBinder token) throws RemoteException {
Jason Monk74f5e362017-12-06 08:56:33 -0500183 verifyCaller(pkg);
Jason Monk38df2802018-02-22 19:28:12 -0500184 enforceAccess(pkg, uri);
Jason Monk74f5e362017-12-06 08:56:33 -0500185 uri = maybeAddUserId(uri, Binder.getCallingUserHandle().getIdentifier());
Jason Monk38df2802018-02-22 19:28:12 -0500186 if (getPinnedSlice(uri).unpin(pkg, token)) {
Jason Monk74f5e362017-12-06 08:56:33 -0500187 removePinnedSlice(uri);
188 }
189 }
190
191 @Override
192 public boolean hasSliceAccess(String pkg) throws RemoteException {
193 verifyCaller(pkg);
194 return hasFullSliceAccess(pkg, Binder.getCallingUserHandle().getIdentifier());
195 }
196
197 @Override
198 public SliceSpec[] getPinnedSpecs(Uri uri, String pkg) throws RemoteException {
199 verifyCaller(pkg);
200 enforceAccess(pkg, uri);
201 return getPinnedSlice(uri).getSpecs();
202 }
203
Jason Monke8f8be72018-01-21 10:10:35 -0500204 @Override
Jason Monkbf3eedc2018-04-05 20:56:42 -0400205 public void grantSlicePermission(String pkg, String toPkg, Uri uri) throws RemoteException {
206 verifyCaller(pkg);
207 int user = Binder.getCallingUserHandle().getIdentifier();
208 enforceOwner(pkg, uri, user);
209 mPermissions.grantSliceAccess(toPkg, user, pkg, user, uri);
210 }
211
212 @Override
213 public void revokeSlicePermission(String pkg, String toPkg, Uri uri) throws RemoteException {
214 verifyCaller(pkg);
215 int user = Binder.getCallingUserHandle().getIdentifier();
216 enforceOwner(pkg, uri, user);
217 mPermissions.revokeSliceAccess(toPkg, user, pkg, user, uri);
218 }
219
220 @Override
Jason Monk42e03f82018-03-30 11:26:56 -0400221 public int checkSlicePermission(Uri uri, String pkg, int pid, int uid,
Jason Monkbf3eedc2018-04-05 20:56:42 -0400222 String[] autoGrantPermissions) {
223 int userId = UserHandle.getUserId(uid);
224 if (pkg == null) {
225 for (String p : mContext.getPackageManager().getPackagesForUid(uid)) {
226 if (checkSlicePermission(uri, p, pid, uid, autoGrantPermissions)
227 == PERMISSION_GRANTED) {
228 return PERMISSION_GRANTED;
229 }
230 }
231 return PERMISSION_DENIED;
232 }
233 if (hasFullSliceAccess(pkg, userId)) {
234 return PackageManager.PERMISSION_GRANTED;
235 }
236 if (mPermissions.hasPermission(pkg, userId, uri)) {
237 return PackageManager.PERMISSION_GRANTED;
238 }
239 if (autoGrantPermissions != null) {
240 // Need to own the Uri to call in with permissions to grant.
241 enforceOwner(pkg, uri, userId);
242 for (String perm : autoGrantPermissions) {
243 if (mContext.checkPermission(perm, pid, uid) == PERMISSION_GRANTED) {
244 int providerUser = ContentProvider.getUserIdFromUri(uri, userId);
245 String providerPkg = getProviderPkg(uri, providerUser);
246 mPermissions.grantSliceAccess(pkg, userId, providerPkg, providerUser, uri);
247 return PackageManager.PERMISSION_GRANTED;
248 }
249 }
250 }
251 // Fallback to allowing uri permissions through.
Jason Monke8f8be72018-01-21 10:10:35 -0500252 if (mContext.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
Jason Monk3a1d2e972018-01-29 16:58:11 -0500253 == PERMISSION_GRANTED) {
Jason Monkbf3eedc2018-04-05 20:56:42 -0400254 return PackageManager.PERMISSION_GRANTED;
Jason Monke8f8be72018-01-21 10:10:35 -0500255 }
Jason Monkbf3eedc2018-04-05 20:56:42 -0400256 return PackageManager.PERMISSION_DENIED;
Jason Monke8f8be72018-01-21 10:10:35 -0500257 }
258
259 @Override
260 public void grantPermissionFromUser(Uri uri, String pkg, String callingPkg, boolean allSlices) {
261 verifyCaller(callingPkg);
262 getContext().enforceCallingOrSelfPermission(permission.MANAGE_SLICE_PERMISSIONS,
263 "Slice granting requires MANAGE_SLICE_PERMISSIONS");
Jason Monkbf3eedc2018-04-05 20:56:42 -0400264 int userId = Binder.getCallingUserHandle().getIdentifier();
Jason Monke8f8be72018-01-21 10:10:35 -0500265 if (allSlices) {
Jason Monkbf3eedc2018-04-05 20:56:42 -0400266 mPermissions.grantFullAccess(pkg, userId);
Jason Monke8f8be72018-01-21 10:10:35 -0500267 } else {
Jason Monkbf3eedc2018-04-05 20:56:42 -0400268 // When granting, grant to all slices in the provider.
269 Uri grantUri = uri.buildUpon()
270 .path("")
271 .build();
272 int providerUser = ContentProvider.getUserIdFromUri(grantUri, userId);
273 String providerPkg = getProviderPkg(grantUri, providerUser);
274 mPermissions.grantSliceAccess(pkg, userId, providerPkg, providerUser, grantUri);
Jason Monkddb8a962018-01-30 13:27:33 -0500275 }
276 long ident = Binder.clearCallingIdentity();
277 try {
278 mContext.getContentResolver().notifyChange(uri, null);
279 } finally {
280 Binder.restoreCallingIdentity(ident);
Jason Monke8f8be72018-01-21 10:10:35 -0500281 }
282 }
283
Jason Monkb715b042018-02-01 15:00:05 -0500284 // Backup/restore interface
285 @Override
286 public byte[] getBackupPayload(int user) {
287 if (Binder.getCallingUid() != SYSTEM_UID) {
288 throw new SecurityException("Caller must be system");
289 }
290 //TODO: http://b/22388012
291 if (user != UserHandle.USER_SYSTEM) {
292 Slog.w(TAG, "getBackupPayload: cannot backup policy for user " + user);
293 return null;
294 }
Jason Monkbf3eedc2018-04-05 20:56:42 -0400295 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
296 try {
297 XmlSerializer out = XmlPullParserFactory.newInstance().newSerializer();
298 out.setOutput(baos, Encoding.UTF_8.name());
299
300 mPermissions.writeBackup(out);
301
302 out.flush();
303 return baos.toByteArray();
304 } catch (IOException | XmlPullParserException e) {
305 Slog.w(TAG, "getBackupPayload: error writing payload for user " + user, e);
Jason Monkb715b042018-02-01 15:00:05 -0500306 }
307 return null;
308 }
309
310 @Override
311 public void applyRestore(byte[] payload, int user) {
312 if (Binder.getCallingUid() != SYSTEM_UID) {
313 throw new SecurityException("Caller must be system");
314 }
315 if (payload == null) {
316 Slog.w(TAG, "applyRestore: no payload to restore for user " + user);
317 return;
318 }
319 //TODO: http://b/22388012
320 if (user != UserHandle.USER_SYSTEM) {
321 Slog.w(TAG, "applyRestore: cannot restore policy for user " + user);
322 return;
323 }
Jason Monkbf3eedc2018-04-05 20:56:42 -0400324 final ByteArrayInputStream bais = new ByteArrayInputStream(payload);
325 try {
326 XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();
327 parser.setInput(bais, Encoding.UTF_8.name());
328 mPermissions.readRestore(parser);
329 } catch (NumberFormatException | XmlPullParserException | IOException e) {
330 Slog.w(TAG, "applyRestore: error reading payload", e);
Jason Monkb715b042018-02-01 15:00:05 -0500331 }
332 }
333
Jason Monk7f01f3b2018-05-15 15:46:26 -0400334 @Override
335 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
336 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
337 new SliceShellCommand(this).exec(this, in, out, err, args, callback, resultReceiver);
338 }
339
Jason Monk74f5e362017-12-06 08:56:33 -0500340 /// ----- internal code -----
Jason Monkbf3eedc2018-04-05 20:56:42 -0400341 private void enforceOwner(String pkg, Uri uri, int user) {
342 if (!Objects.equals(getProviderPkg(uri, user), pkg) || pkg == null) {
343 throw new SecurityException("Caller must own " + uri);
Jason Monk68ff6aa2018-01-31 15:51:52 -0500344 }
Jason Monk68ff6aa2018-01-31 15:51:52 -0500345 }
346
Jason Monk9e3b8642018-01-21 20:54:00 -0500347 protected void removePinnedSlice(Uri uri) {
Jason Monk74f5e362017-12-06 08:56:33 -0500348 synchronized (mLock) {
349 mPinnedSlicesByUri.remove(uri).destroy();
350 }
351 }
352
353 private PinnedSliceState getPinnedSlice(Uri uri) {
354 synchronized (mLock) {
355 PinnedSliceState manager = mPinnedSlicesByUri.get(uri);
356 if (manager == null) {
357 throw new IllegalStateException(String.format("Slice %s not pinned",
358 uri.toString()));
359 }
360 return manager;
361 }
362 }
363
Jason Monkf88d25e2018-03-06 20:13:24 -0500364 private PinnedSliceState getOrCreatePinnedSlice(Uri uri, String pkg) {
Jason Monk74f5e362017-12-06 08:56:33 -0500365 synchronized (mLock) {
366 PinnedSliceState manager = mPinnedSlicesByUri.get(uri);
367 if (manager == null) {
Jason Monkf88d25e2018-03-06 20:13:24 -0500368 manager = createPinnedSlice(uri, pkg);
Jason Monk74f5e362017-12-06 08:56:33 -0500369 mPinnedSlicesByUri.put(uri, manager);
370 }
371 return manager;
372 }
373 }
374
375 @VisibleForTesting
Jason Monkf88d25e2018-03-06 20:13:24 -0500376 protected PinnedSliceState createPinnedSlice(Uri uri, String pkg) {
377 return new PinnedSliceState(this, uri, pkg);
Jason Monk74f5e362017-12-06 08:56:33 -0500378 }
379
380 public Object getLock() {
381 return mLock;
382 }
383
384 public Context getContext() {
385 return mContext;
386 }
387
388 public Handler getHandler() {
389 return mHandler;
390 }
391
Jason Monk3a1d2e972018-01-29 16:58:11 -0500392 protected int checkAccess(String pkg, Uri uri, int uid, int pid) {
Jason Monkbf3eedc2018-04-05 20:56:42 -0400393 return checkSlicePermission(uri, pkg, uid, pid, null);
Jason Monk3a1d2e972018-01-29 16:58:11 -0500394 }
395
Jason Monk1918ef72018-03-14 09:20:39 -0400396 private String getProviderPkg(Uri uri, int user) {
397 long ident = Binder.clearCallingIdentity();
398 try {
Jason Monk1918ef72018-03-14 09:20:39 -0400399 String providerName = getUriWithoutUserId(uri).getAuthority();
Jason Monkda90df72018-07-03 11:21:57 -0400400 ProviderInfo provider = mContext.getPackageManager().resolveContentProviderAsUser(
401 providerName, 0, getUserIdFromUri(uri, user));
402 return provider.packageName;
Jason Monk1918ef72018-03-14 09:20:39 -0400403 } finally {
Jason Monk1918ef72018-03-14 09:20:39 -0400404 Binder.restoreCallingIdentity(ident);
405 }
406 }
407
Jason Monk3a1d2e972018-01-29 16:58:11 -0500408 private void enforceCrossUser(String pkg, Uri uri) {
409 int user = Binder.getCallingUserHandle().getIdentifier();
Jason Monk74f5e362017-12-06 08:56:33 -0500410 if (getUserIdFromUri(uri, user) != user) {
411 getContext().enforceCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS_FULL,
412 "Slice interaction across users requires INTERACT_ACROSS_USERS_FULL");
413 }
414 }
415
Jason Monk3a1d2e972018-01-29 16:58:11 -0500416 private void enforceAccess(String pkg, Uri uri) throws RemoteException {
417 if (checkAccess(pkg, uri, Binder.getCallingUid(), Binder.getCallingPid())
418 != PERMISSION_GRANTED) {
Jason Monkbf3eedc2018-04-05 20:56:42 -0400419 int userId = ContentProvider.getUserIdFromUri(uri,
420 Binder.getCallingUserHandle().getIdentifier());
421 if (!Objects.equals(pkg, getProviderPkg(uri, userId))) {
422 throw new SecurityException("Access to slice " + uri + " is required");
423 }
Jason Monk74f5e362017-12-06 08:56:33 -0500424 }
Jason Monk3a1d2e972018-01-29 16:58:11 -0500425 enforceCrossUser(pkg, uri);
Jason Monk74f5e362017-12-06 08:56:33 -0500426 }
427
428 private void verifyCaller(String pkg) {
429 mAppOps.checkPackage(Binder.getCallingUid(), pkg);
430 }
431
432 private boolean hasFullSliceAccess(String pkg, int userId) {
Jason Monke8f8be72018-01-21 10:10:35 -0500433 long ident = Binder.clearCallingIdentity();
434 try {
435 boolean ret = isDefaultHomeApp(pkg, userId) || isAssistant(pkg, userId)
436 || isGrantedFullAccess(pkg, userId);
437 return ret;
438 } finally {
439 Binder.restoreCallingIdentity(ident);
440 }
Jason Monk74f5e362017-12-06 08:56:33 -0500441 }
442
443 private boolean isAssistant(String pkg, int userId) {
Jason Monke009a8e2018-05-21 13:36:21 -0400444 return getAssistantMatcher(userId).matches(pkg);
Jason Monk74f5e362017-12-06 08:56:33 -0500445 }
446
Jason Monk74f5e362017-12-06 08:56:33 -0500447 private boolean isDefaultHomeApp(String pkg, int userId) {
Jason Monke009a8e2018-05-21 13:36:21 -0400448 return getHomeMatcher(userId).matches(pkg);
449 }
Jason Monke8f8be72018-01-21 10:10:35 -0500450
Jason Monke009a8e2018-05-21 13:36:21 -0400451 private PackageMatchingCache getAssistantMatcher(int userId) {
452 PackageMatchingCache matcher = mAssistantLookup.get(userId);
453 if (matcher == null) {
454 matcher = new PackageMatchingCache(() -> getAssistant(userId));
455 mAssistantLookup.put(userId, matcher);
456 }
457 return matcher;
458 }
459
460 private PackageMatchingCache getHomeMatcher(int userId) {
461 PackageMatchingCache matcher = mHomeLookup.get(userId);
462 if (matcher == null) {
463 matcher = new PackageMatchingCache(() -> getDefaultHome(userId));
464 mHomeLookup.put(userId, matcher);
465 }
466 return matcher;
467 }
468
469 private String getAssistant(int userId) {
470 final ComponentName cn = mAssistUtils.getAssistComponentForUser(userId);
471 if (cn == null) {
472 return null;
473 }
474 return cn.getPackageName();
Jason Monk74f5e362017-12-06 08:56:33 -0500475 }
476
477 // Based on getDefaultHome in ShortcutService.
478 // TODO: Unify if possible
479 @VisibleForTesting
Jason Monk74848ae2018-01-21 17:11:57 -0500480 protected String getDefaultHome(int userId) {
Jason Monk74f5e362017-12-06 08:56:33 -0500481 final long token = Binder.clearCallingIdentity();
482 try {
483 final List<ResolveInfo> allHomeCandidates = new ArrayList<>();
484
485 // Default launcher from package manager.
486 final ComponentName defaultLauncher = mPackageManagerInternal
487 .getHomeActivitiesAsUser(allHomeCandidates, userId);
488
489 ComponentName detected = null;
490 if (defaultLauncher != null) {
491 detected = defaultLauncher;
492 }
493
494 if (detected == null) {
495 // If we reach here, that means it's the first check since the user was created,
496 // and there's already multiple launchers and there's no default set.
497 // Find the system one with the highest priority.
498 // (We need to check the priority too because of FallbackHome in Settings.)
499 // If there's no system launcher yet, then no one can access slices, until
500 // the user explicitly sets one.
501 final int size = allHomeCandidates.size();
502
503 int lastPriority = Integer.MIN_VALUE;
504 for (int i = 0; i < size; i++) {
505 final ResolveInfo ri = allHomeCandidates.get(i);
506 if (!ri.activityInfo.applicationInfo.isSystemApp()) {
507 continue;
508 }
509 if (ri.priority < lastPriority) {
510 continue;
511 }
512 detected = ri.activityInfo.getComponentName();
513 lastPriority = ri.priority;
514 }
515 }
Jason Monke8f8be72018-01-21 10:10:35 -0500516 return detected != null ? detected.getPackageName() : null;
Jason Monk74f5e362017-12-06 08:56:33 -0500517 } finally {
518 Binder.restoreCallingIdentity(token);
519 }
520 }
521
522 private boolean isGrantedFullAccess(String pkg, int userId) {
Jason Monkbf3eedc2018-04-05 20:56:42 -0400523 return mPermissions.hasFullAccess(pkg, userId);
Jason Monk74f5e362017-12-06 08:56:33 -0500524 }
525
526 private static ServiceThread createHandler() {
527 ServiceThread handlerThread = new ServiceThread(TAG,
528 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
529 handlerThread.start();
530 return handlerThread;
Jason Monk8f5f7ff2017-10-17 14:12:42 -0400531 }
532
Jason Monk68ff6aa2018-01-31 15:51:52 -0500533 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
534 @Override
535 public void onReceive(Context context, Intent intent) {
536 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
537 if (userId == UserHandle.USER_NULL) {
538 Slog.w(TAG, "Intent broadcast does not contain user handle: " + intent);
539 return;
540 }
541 Uri data = intent.getData();
542 String pkg = data != null ? data.getSchemeSpecificPart() : null;
543 if (pkg == null) {
544 Slog.w(TAG, "Intent broadcast does not contain package name: " + intent);
545 return;
546 }
547 switch (intent.getAction()) {
548 case Intent.ACTION_PACKAGE_REMOVED:
549 final boolean replacing =
550 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
551 if (!replacing) {
Jason Monkbf3eedc2018-04-05 20:56:42 -0400552 mPermissions.removePkg(pkg, userId);
Jason Monk68ff6aa2018-01-31 15:51:52 -0500553 }
554 break;
555 case Intent.ACTION_PACKAGE_DATA_CLEARED:
Jason Monkbf3eedc2018-04-05 20:56:42 -0400556 mPermissions.removePkg(pkg, userId);
Jason Monk68ff6aa2018-01-31 15:51:52 -0500557 break;
558 }
559 }
560 };
561
Jason Monk7f01f3b2018-05-15 15:46:26 -0400562 public String[] getAllPackagesGranted(String authority) {
563 String pkg = getProviderPkg(new Uri.Builder()
564 .scheme(ContentResolver.SCHEME_CONTENT)
565 .authority(authority)
566 .build(), 0);
567 return mPermissions.getAllPackagesGranted(pkg);
568 }
569
Jason Monke009a8e2018-05-21 13:36:21 -0400570 /**
571 * Holder that caches a package that has access to a slice.
572 */
573 static class PackageMatchingCache {
574
575 private final Supplier<String> mPkgSource;
576 private String mCurrentPkg;
577
578 public PackageMatchingCache(Supplier<String> pkgSource) {
579 mPkgSource = pkgSource;
580 }
581
582 public boolean matches(String pkgCandidate) {
583 if (pkgCandidate == null) return false;
584
585 if (Objects.equals(pkgCandidate, mCurrentPkg)) {
586 return true;
587 }
588 // Failed on cached value, try updating.
589 mCurrentPkg = mPkgSource.get();
590 return Objects.equals(pkgCandidate, mCurrentPkg);
591 }
592 }
593
Jason Monk8f5f7ff2017-10-17 14:12:42 -0400594 public static class Lifecycle extends SystemService {
595 private SliceManagerService mService;
596
597 public Lifecycle(Context context) {
598 super(context);
599 }
600
601 @Override
602 public void onStart() {
603 mService = new SliceManagerService(getContext());
604 publishBinderService(Context.SLICE_SERVICE, mService);
605 }
606
607 @Override
608 public void onBootPhase(int phase) {
609 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
610 mService.systemReady();
611 }
612 }
613
614 @Override
615 public void onUnlockUser(int userHandle) {
616 mService.onUnlockUser(userHandle);
617 }
Jason Monk74f5e362017-12-06 08:56:33 -0500618
619 @Override
620 public void onStopUser(int userHandle) {
621 mService.onStopUser(userHandle);
622 }
Jason Monk8f5f7ff2017-10-17 14:12:42 -0400623 }
Jason Monke8f8be72018-01-21 10:10:35 -0500624
625 private class SliceGrant {
626 private final Uri mUri;
627 private final String mPkg;
Jason Monkddb8a962018-01-30 13:27:33 -0500628 private final int mUserId;
Jason Monke8f8be72018-01-21 10:10:35 -0500629
Jason Monkddb8a962018-01-30 13:27:33 -0500630 public SliceGrant(Uri uri, String pkg, int userId) {
Jason Monke8f8be72018-01-21 10:10:35 -0500631 mUri = uri;
632 mPkg = pkg;
Jason Monkddb8a962018-01-30 13:27:33 -0500633 mUserId = userId;
Jason Monke8f8be72018-01-21 10:10:35 -0500634 }
635
636 @Override
637 public int hashCode() {
638 return mUri.hashCode() + mPkg.hashCode();
639 }
640
641 @Override
642 public boolean equals(Object obj) {
643 if (!(obj instanceof SliceGrant)) return false;
644 SliceGrant other = (SliceGrant) obj;
Jason Monkddb8a962018-01-30 13:27:33 -0500645 return Objects.equals(other.mUri, mUri) && Objects.equals(other.mPkg, mPkg)
646 && (other.mUserId == mUserId);
Jason Monke8f8be72018-01-21 10:10:35 -0500647 }
648 }
Jason Monk8f5f7ff2017-10-17 14:12:42 -0400649}