blob: c38a89e30807e0e719383d035ae463e2997b4207 [file] [log] [blame]
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001/*
2 * Copyright (C) 2012 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;
18
19import java.io.File;
20import java.io.FileDescriptor;
Dianne Hackborn35654b62013-01-14 17:38:02 -080021import java.io.FileInputStream;
22import java.io.FileNotFoundException;
23import java.io.FileOutputStream;
24import java.io.IOException;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080025import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010026import java.nio.charset.StandardCharsets;
Dianne Hackborn35654b62013-01-14 17:38:02 -080027import java.util.ArrayList;
Svetoslav215b44a2015-08-04 19:03:40 -070028import java.util.Collections;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080029import java.util.HashMap;
Dianne Hackbornc2293022013-02-06 23:14:49 -080030import java.util.Iterator;
Dianne Hackborn35654b62013-01-14 17:38:02 -080031import java.util.List;
Dianne Hackborn607b4142013-08-02 18:10:10 -070032import java.util.Map;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080033
Svet Ganov9cea80cd2016-02-16 11:47:00 -080034import android.Manifest;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -080035import android.app.ActivityManager;
Jason Monk1c7c3192014-06-26 12:52:18 -040036import android.app.ActivityThread;
Svet Ganov2af57082015-07-30 08:44:20 -070037import android.app.AppGlobals;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080038import android.app.AppOpsManager;
39import android.content.Context;
Jason Monk1c7c3192014-06-26 12:52:18 -040040import android.content.pm.ApplicationInfo;
41import android.content.pm.IPackageManager;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080042import android.content.pm.PackageManager;
John Spurlock7b414672014-07-18 13:02:39 -040043import android.media.AudioAttributes;
Dianne Hackborn35654b62013-01-14 17:38:02 -080044import android.os.AsyncTask;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080045import android.os.Binder;
Jason Monk62062992014-05-06 09:55:28 -040046import android.os.Bundle;
Dianne Hackborn35654b62013-01-14 17:38:02 -080047import android.os.Handler;
Dianne Hackbornc2293022013-02-06 23:14:49 -080048import android.os.IBinder;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080049import android.os.Process;
Dianne Hackbornc2293022013-02-06 23:14:49 -080050import android.os.RemoteException;
Dianne Hackborn268e4e32015-11-18 16:29:56 -080051import android.os.ResultReceiver;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080052import android.os.ServiceManager;
Dianne Hackborn268e4e32015-11-18 16:29:56 -080053import android.os.ShellCommand;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080054import android.os.UserHandle;
Svet Ganov6ee871e2015-07-10 14:29:33 -070055import android.os.storage.MountServiceInternal;
Dianne Hackborne98f5db2013-07-17 17:23:25 -070056import android.util.ArrayMap;
John Spurlock1af30c72014-03-10 08:33:35 -040057import android.util.ArraySet;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080058import android.util.AtomicFile;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -080059import android.util.Log;
Ruben Brunk29931bc2016-03-11 00:24:26 -080060import android.util.Pair;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080061import android.util.Slog;
62import android.util.SparseArray;
Svet Ganov2af57082015-07-30 08:44:20 -070063import android.util.SparseIntArray;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080064import android.util.TimeUtils;
Dianne Hackborn35654b62013-01-14 17:38:02 -080065import android.util.Xml;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080066
67import com.android.internal.app.IAppOpsService;
Dianne Hackbornc2293022013-02-06 23:14:49 -080068import com.android.internal.app.IAppOpsCallback;
Svet Ganov6ee871e2015-07-10 14:29:33 -070069import com.android.internal.os.Zygote;
Svet Ganov2af57082015-07-30 08:44:20 -070070import com.android.internal.util.ArrayUtils;
Dianne Hackborn35654b62013-01-14 17:38:02 -080071import com.android.internal.util.FastXmlSerializer;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080072import com.android.internal.util.Preconditions;
Dianne Hackborn35654b62013-01-14 17:38:02 -080073import com.android.internal.util.XmlUtils;
74
Svet Ganov2af57082015-07-30 08:44:20 -070075import libcore.util.EmptyArray;
Dianne Hackborn35654b62013-01-14 17:38:02 -080076import org.xmlpull.v1.XmlPullParser;
77import org.xmlpull.v1.XmlPullParserException;
78import org.xmlpull.v1.XmlSerializer;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080079
80public class AppOpsService extends IAppOpsService.Stub {
81 static final String TAG = "AppOps";
Dianne Hackborn35654b62013-01-14 17:38:02 -080082 static final boolean DEBUG = false;
83
84 // Write at most every 30 minutes.
85 static final long WRITE_DELAY = DEBUG ? 1000 : 30*60*1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080086
87 Context mContext;
88 final AtomicFile mFile;
Dianne Hackborn35654b62013-01-14 17:38:02 -080089 final Handler mHandler;
90
91 boolean mWriteScheduled;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -080092 boolean mFastWriteScheduled;
Dianne Hackborn35654b62013-01-14 17:38:02 -080093 final Runnable mWriteRunner = new Runnable() {
94 public void run() {
95 synchronized (AppOpsService.this) {
96 mWriteScheduled = false;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -080097 mFastWriteScheduled = false;
Dianne Hackborn35654b62013-01-14 17:38:02 -080098 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
99 @Override protected Void doInBackground(Void... params) {
100 writeState();
101 return null;
102 }
103 };
104 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
105 }
106 }
107 };
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800108
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800109 private final SparseArray<UidState> mUidStates = new SparseArray<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800110
Ruben Brunk29931bc2016-03-11 00:24:26 -0800111 /*
112 * These are app op restrictions imposed per user from various parties.
113 *
114 * This is organized as follows:
115 *
116 * ArrayMap w/ mapping:
117 * IBinder (for client imposing restriction) --> SparseArray w/ mapping:
118 * User handle --> Pair containing:
119 * - Array w/ index = AppOp code, value = restricted status boolean
120 * - SparseArray w/ mapping:
121 * AppOp code --> Set of packages that are not restricted for this code
122 *
Ruben Brunk32f0fa42016-03-11 19:07:07 -0800123 * For efficiency, a core assumption here is that the number of per-package exemptions stored
124 * here will be relatively small. If this changes, this data structure should be revisited.
Ruben Brunk29931bc2016-03-11 00:24:26 -0800125 */
126 private final ArrayMap<IBinder, SparseArray<Pair<boolean[], SparseArray<ArraySet<String>>>>>
127 mOpUserRestrictions = new ArrayMap<>();
Jason Monk62062992014-05-06 09:55:28 -0400128
Svet Ganov2af57082015-07-30 08:44:20 -0700129 private static final class UidState {
130 public final int uid;
131 public ArrayMap<String, Ops> pkgOps;
132 public SparseIntArray opModes;
133
134 public UidState(int uid) {
135 this.uid = uid;
136 }
137
138 public void clear() {
139 pkgOps = null;
140 opModes = null;
141 }
142
143 public boolean isDefault() {
144 return (pkgOps == null || pkgOps.isEmpty())
145 && (opModes == null || opModes.size() <= 0);
146 }
147 }
148
Dianne Hackbornc2293022013-02-06 23:14:49 -0800149 public final static class Ops extends SparseArray<Op> {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800150 public final String packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700151 public final UidState uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400152 public final boolean isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800153
Svet Ganov2af57082015-07-30 08:44:20 -0700154 public Ops(String _packageName, UidState _uidState, boolean _isPrivileged) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800155 packageName = _packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700156 uidState = _uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400157 isPrivileged = _isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800158 }
159 }
160
Dianne Hackbornc2293022013-02-06 23:14:49 -0800161 public final static class Op {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700162 public final int uid;
163 public final String packageName;
Svet Ganov99b60432015-06-27 13:15:22 -0700164 public int proxyUid = -1;
165 public String proxyPackageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800166 public final int op;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800167 public int mode;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800168 public int duration;
169 public long time;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800170 public long rejectTime;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800171 public int nesting;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800172
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700173 public Op(int _uid, String _packageName, int _op) {
174 uid = _uid;
175 packageName = _packageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800176 op = _op;
David Braunf5d83192013-09-16 13:43:51 -0700177 mode = AppOpsManager.opToDefaultMode(op);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800178 }
179 }
180
Dianne Hackbornc2293022013-02-06 23:14:49 -0800181 final SparseArray<ArrayList<Callback>> mOpModeWatchers
182 = new SparseArray<ArrayList<Callback>>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700183 final ArrayMap<String, ArrayList<Callback>> mPackageModeWatchers
184 = new ArrayMap<String, ArrayList<Callback>>();
185 final ArrayMap<IBinder, Callback> mModeWatchers
186 = new ArrayMap<IBinder, Callback>();
John Spurlock1af30c72014-03-10 08:33:35 -0400187 final SparseArray<SparseArray<Restriction>> mAudioRestrictions
188 = new SparseArray<SparseArray<Restriction>>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800189
190 public final class Callback implements DeathRecipient {
191 final IAppOpsCallback mCallback;
192
193 public Callback(IAppOpsCallback callback) {
194 mCallback = callback;
195 try {
196 mCallback.asBinder().linkToDeath(this, 0);
197 } catch (RemoteException e) {
198 }
199 }
200
201 public void unlinkToDeath() {
202 mCallback.asBinder().unlinkToDeath(this, 0);
203 }
204
205 @Override
206 public void binderDied() {
207 stopWatchingMode(mCallback);
208 }
209 }
210
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700211 final ArrayMap<IBinder, ClientState> mClients = new ArrayMap<IBinder, ClientState>();
212
213 public final class ClientState extends Binder implements DeathRecipient {
214 final IBinder mAppToken;
215 final int mPid;
216 final ArrayList<Op> mStartedOps;
217
218 public ClientState(IBinder appToken) {
219 mAppToken = appToken;
220 mPid = Binder.getCallingPid();
221 if (appToken instanceof Binder) {
222 // For local clients, there is no reason to track them.
223 mStartedOps = null;
224 } else {
225 mStartedOps = new ArrayList<Op>();
226 try {
227 mAppToken.linkToDeath(this, 0);
228 } catch (RemoteException e) {
229 }
230 }
231 }
232
233 @Override
234 public String toString() {
235 return "ClientState{" +
236 "mAppToken=" + mAppToken +
237 ", " + (mStartedOps != null ? ("pid=" + mPid) : "local") +
238 '}';
239 }
240
241 @Override
242 public void binderDied() {
243 synchronized (AppOpsService.this) {
244 for (int i=mStartedOps.size()-1; i>=0; i--) {
245 finishOperationLocked(mStartedOps.get(i));
246 }
247 mClients.remove(mAppToken);
248 }
249 }
250 }
251
Jeff Brown6f357d32014-01-15 20:40:55 -0800252 public AppOpsService(File storagePath, Handler handler) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800253 mFile = new AtomicFile(storagePath);
Jeff Brown6f357d32014-01-15 20:40:55 -0800254 mHandler = handler;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800255 readState();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800256 }
David Braunf5d83192013-09-16 13:43:51 -0700257
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800258 public void publish(Context context) {
259 mContext = context;
260 ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
261 }
262
Dianne Hackborn514074f2013-02-11 10:52:46 -0800263 public void systemReady() {
264 synchronized (this) {
265 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700266 for (int i = mUidStates.size() - 1; i >= 0; i--) {
267 UidState uidState = mUidStates.valueAt(i);
268
269 String[] packageNames = getPackagesForUid(uidState.uid);
270 if (ArrayUtils.isEmpty(packageNames)) {
271 uidState.clear();
272 mUidStates.removeAt(i);
273 changed = true;
274 continue;
275 }
276
277 ArrayMap<String, Ops> pkgs = uidState.pkgOps;
278 if (pkgs == null) {
279 continue;
280 }
281
Dianne Hackborn514074f2013-02-11 10:52:46 -0800282 Iterator<Ops> it = pkgs.values().iterator();
283 while (it.hasNext()) {
284 Ops ops = it.next();
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700285 int curUid = -1;
Dianne Hackborn514074f2013-02-11 10:52:46 -0800286 try {
Jeff Sharkeycd654482016-01-08 17:42:11 -0700287 curUid = AppGlobals.getPackageManager().getPackageUid(ops.packageName,
288 PackageManager.MATCH_UNINSTALLED_PACKAGES,
Svet Ganov2af57082015-07-30 08:44:20 -0700289 UserHandle.getUserId(ops.uidState.uid));
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700290 } catch (RemoteException ignored) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800291 }
Svet Ganov2af57082015-07-30 08:44:20 -0700292 if (curUid != ops.uidState.uid) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800293 Slog.i(TAG, "Pruning old package " + ops.packageName
Svet Ganov2af57082015-07-30 08:44:20 -0700294 + "/" + ops.uidState + ": new uid=" + curUid);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800295 it.remove();
296 changed = true;
297 }
298 }
Svet Ganov2af57082015-07-30 08:44:20 -0700299
300 if (uidState.isDefault()) {
301 mUidStates.removeAt(i);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800302 }
303 }
304 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800305 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800306 }
307 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700308
309 MountServiceInternal mountServiceInternal = LocalServices.getService(
310 MountServiceInternal.class);
311 mountServiceInternal.addExternalStoragePolicy(
312 new MountServiceInternal.ExternalStorageMountPolicy() {
313 @Override
314 public int getMountMode(int uid, String packageName) {
315 if (Process.isIsolated(uid)) {
316 return Zygote.MOUNT_EXTERNAL_NONE;
317 }
318 if (noteOperation(AppOpsManager.OP_READ_EXTERNAL_STORAGE, uid,
319 packageName) != AppOpsManager.MODE_ALLOWED) {
320 return Zygote.MOUNT_EXTERNAL_NONE;
321 }
322 if (noteOperation(AppOpsManager.OP_WRITE_EXTERNAL_STORAGE, uid,
323 packageName) != AppOpsManager.MODE_ALLOWED) {
324 return Zygote.MOUNT_EXTERNAL_READ;
325 }
326 return Zygote.MOUNT_EXTERNAL_WRITE;
327 }
328
329 @Override
330 public boolean hasExternalStorage(int uid, String packageName) {
331 final int mountMode = getMountMode(uid, packageName);
332 return mountMode == Zygote.MOUNT_EXTERNAL_READ
333 || mountMode == Zygote.MOUNT_EXTERNAL_WRITE;
334 }
335 });
Dianne Hackborn514074f2013-02-11 10:52:46 -0800336 }
337
338 public void packageRemoved(int uid, String packageName) {
339 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700340 UidState uidState = mUidStates.get(uid);
341 if (uidState == null) {
342 return;
343 }
344
345 boolean changed = false;
346
347 // Remove any package state if such.
348 if (uidState.pkgOps != null && uidState.pkgOps.remove(packageName) != null) {
349 changed = true;
350 }
351
352 // If we just nuked the last package state check if the UID is valid.
353 if (changed && uidState.pkgOps.isEmpty()
354 && getPackagesForUid(uid).length <= 0) {
355 mUidStates.remove(uid);
356 }
357
358 if (changed) {
359 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800360 }
361 }
362 }
363
364 public void uidRemoved(int uid) {
365 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700366 if (mUidStates.indexOfKey(uid) >= 0) {
367 mUidStates.remove(uid);
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800368 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800369 }
370 }
371 }
372
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800373 public void shutdown() {
374 Slog.w(TAG, "Writing app ops before shutdown...");
Dianne Hackborn35654b62013-01-14 17:38:02 -0800375 boolean doWrite = false;
376 synchronized (this) {
377 if (mWriteScheduled) {
378 mWriteScheduled = false;
379 doWrite = true;
380 }
381 }
382 if (doWrite) {
383 writeState();
384 }
385 }
386
Dianne Hackborn72e39832013-01-18 18:36:09 -0800387 private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
388 ArrayList<AppOpsManager.OpEntry> resOps = null;
389 if (ops == null) {
390 resOps = new ArrayList<AppOpsManager.OpEntry>();
391 for (int j=0; j<pkgOps.size(); j++) {
392 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800393 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Svet Ganov99b60432015-06-27 13:15:22 -0700394 curOp.rejectTime, curOp.duration, curOp.proxyUid,
395 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800396 }
397 } else {
398 for (int j=0; j<ops.length; j++) {
399 Op curOp = pkgOps.get(ops[j]);
400 if (curOp != null) {
401 if (resOps == null) {
402 resOps = new ArrayList<AppOpsManager.OpEntry>();
403 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800404 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Svet Ganov99b60432015-06-27 13:15:22 -0700405 curOp.rejectTime, curOp.duration, curOp.proxyUid,
406 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800407 }
408 }
409 }
410 return resOps;
411 }
412
Dianne Hackborn35654b62013-01-14 17:38:02 -0800413 @Override
414 public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
415 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
416 Binder.getCallingPid(), Binder.getCallingUid(), null);
417 ArrayList<AppOpsManager.PackageOps> res = null;
418 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700419 final int uidStateCount = mUidStates.size();
420 for (int i = 0; i < uidStateCount; i++) {
421 UidState uidState = mUidStates.valueAt(i);
422 if (uidState.pkgOps == null || uidState.pkgOps.isEmpty()) {
423 continue;
424 }
425 ArrayMap<String, Ops> packages = uidState.pkgOps;
426 final int packageCount = packages.size();
427 for (int j = 0; j < packageCount; j++) {
428 Ops pkgOps = packages.valueAt(j);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800429 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800430 if (resOps != null) {
431 if (res == null) {
432 res = new ArrayList<AppOpsManager.PackageOps>();
433 }
434 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700435 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800436 res.add(resPackage);
437 }
438 }
439 }
440 }
441 return res;
442 }
443
444 @Override
Dianne Hackborn72e39832013-01-18 18:36:09 -0800445 public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
446 int[] ops) {
447 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
448 Binder.getCallingPid(), Binder.getCallingUid(), null);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000449 String resolvedPackageName = resolvePackageName(uid, packageName);
450 if (resolvedPackageName == null) {
451 return Collections.emptyList();
452 }
Dianne Hackborn72e39832013-01-18 18:36:09 -0800453 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000454 Ops pkgOps = getOpsRawLocked(uid, resolvedPackageName, false);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800455 if (pkgOps == null) {
456 return null;
457 }
458 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
459 if (resOps == null) {
460 return null;
461 }
462 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
463 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700464 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800465 res.add(resPackage);
466 return res;
467 }
468 }
469
Dianne Hackborn607b4142013-08-02 18:10:10 -0700470 private void pruneOp(Op op, int uid, String packageName) {
471 if (op.time == 0 && op.rejectTime == 0) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000472 Ops ops = getOpsRawLocked(uid, packageName, false);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700473 if (ops != null) {
474 ops.remove(op.op);
475 if (ops.size() <= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -0700476 UidState uidState = ops.uidState;
477 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700478 if (pkgOps != null) {
479 pkgOps.remove(ops.packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700480 if (pkgOps.isEmpty()) {
481 uidState.pkgOps = null;
482 }
483 if (uidState.isDefault()) {
484 mUidStates.remove(uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700485 }
486 }
487 }
488 }
489 }
490 }
491
Dianne Hackborn72e39832013-01-18 18:36:09 -0800492 @Override
Svet Ganov2af57082015-07-30 08:44:20 -0700493 public void setUidMode(int code, int uid, int mode) {
494 if (Binder.getCallingPid() != Process.myPid()) {
495 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
496 Binder.getCallingPid(), Binder.getCallingUid(), null);
497 }
498 verifyIncomingOp(code);
499 code = AppOpsManager.opToSwitch(code);
500
501 synchronized (this) {
502 final int defaultMode = AppOpsManager.opToDefaultMode(code);
503
504 UidState uidState = getUidStateLocked(uid, false);
505 if (uidState == null) {
506 if (mode == defaultMode) {
507 return;
508 }
509 uidState = new UidState(uid);
510 uidState.opModes = new SparseIntArray();
511 uidState.opModes.put(code, mode);
512 mUidStates.put(uid, uidState);
513 scheduleWriteLocked();
514 } else if (uidState.opModes == null) {
515 if (mode != defaultMode) {
516 uidState.opModes = new SparseIntArray();
517 uidState.opModes.put(code, mode);
518 scheduleWriteLocked();
519 }
520 } else {
521 if (uidState.opModes.get(code) == mode) {
522 return;
523 }
524 if (mode == defaultMode) {
525 uidState.opModes.delete(code);
526 if (uidState.opModes.size() <= 0) {
527 uidState.opModes = null;
528 }
529 } else {
530 uidState.opModes.put(code, mode);
531 }
532 scheduleWriteLocked();
533 }
534 }
535
Svetoslav215b44a2015-08-04 19:03:40 -0700536 String[] uidPackageNames = getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -0700537 ArrayMap<Callback, ArraySet<String>> callbackSpecs = null;
538
riddle_hsu40b300f2015-11-23 13:22:03 +0800539 synchronized (this) {
540 ArrayList<Callback> callbacks = mOpModeWatchers.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -0700541 if (callbacks != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700542 final int callbackCount = callbacks.size();
543 for (int i = 0; i < callbackCount; i++) {
544 Callback callback = callbacks.get(i);
riddle_hsu40b300f2015-11-23 13:22:03 +0800545 ArraySet<String> changedPackages = new ArraySet<>();
546 Collections.addAll(changedPackages, uidPackageNames);
547 callbackSpecs = new ArrayMap<>();
548 callbackSpecs.put(callback, changedPackages);
549 }
550 }
551
552 for (String uidPackageName : uidPackageNames) {
553 callbacks = mPackageModeWatchers.get(uidPackageName);
554 if (callbacks != null) {
555 if (callbackSpecs == null) {
556 callbackSpecs = new ArrayMap<>();
Svet Ganov2af57082015-07-30 08:44:20 -0700557 }
riddle_hsu40b300f2015-11-23 13:22:03 +0800558 final int callbackCount = callbacks.size();
559 for (int i = 0; i < callbackCount; i++) {
560 Callback callback = callbacks.get(i);
561 ArraySet<String> changedPackages = callbackSpecs.get(callback);
562 if (changedPackages == null) {
563 changedPackages = new ArraySet<>();
564 callbackSpecs.put(callback, changedPackages);
565 }
566 changedPackages.add(uidPackageName);
567 }
Svet Ganov2af57082015-07-30 08:44:20 -0700568 }
569 }
570 }
571
572 if (callbackSpecs == null) {
573 return;
574 }
575
576 // There are components watching for mode changes such as window manager
577 // and location manager which are in our process. The callbacks in these
578 // components may require permissions our remote caller does not have.
579 final long identity = Binder.clearCallingIdentity();
580 try {
581 for (int i = 0; i < callbackSpecs.size(); i++) {
582 Callback callback = callbackSpecs.keyAt(i);
583 ArraySet<String> reportedPackageNames = callbackSpecs.valueAt(i);
584 try {
585 if (reportedPackageNames == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700586 callback.mCallback.opChanged(code, uid, null);
Svet Ganov2af57082015-07-30 08:44:20 -0700587 } else {
588 final int reportedPackageCount = reportedPackageNames.size();
589 for (int j = 0; j < reportedPackageCount; j++) {
590 String reportedPackageName = reportedPackageNames.valueAt(j);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700591 callback.mCallback.opChanged(code, uid, reportedPackageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700592 }
593 }
594 } catch (RemoteException e) {
595 Log.w(TAG, "Error dispatching op op change", e);
596 }
597 }
598 } finally {
599 Binder.restoreCallingIdentity(identity);
600 }
601 }
602
603 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800604 public void setMode(int code, int uid, String packageName, int mode) {
Dianne Hackbornb64afe12014-07-22 16:29:04 -0700605 if (Binder.getCallingPid() != Process.myPid()) {
606 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
607 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborn133b9df2014-07-01 13:06:10 -0700608 }
Dianne Hackborn961321f2013-02-05 17:22:41 -0800609 verifyIncomingOp(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800610 ArrayList<Callback> repCbs = null;
611 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800612 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700613 UidState uidState = getUidStateLocked(uid, false);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800614 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800615 if (op != null) {
616 if (op.mode != mode) {
617 op.mode = mode;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800618 ArrayList<Callback> cbs = mOpModeWatchers.get(code);
619 if (cbs != null) {
620 if (repCbs == null) {
621 repCbs = new ArrayList<Callback>();
622 }
623 repCbs.addAll(cbs);
624 }
625 cbs = mPackageModeWatchers.get(packageName);
626 if (cbs != null) {
627 if (repCbs == null) {
628 repCbs = new ArrayList<Callback>();
629 }
630 repCbs.addAll(cbs);
631 }
David Braunf5d83192013-09-16 13:43:51 -0700632 if (mode == AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800633 // If going into the default mode, prune this op
634 // if there is nothing else interesting in it.
Dianne Hackborn607b4142013-08-02 18:10:10 -0700635 pruneOp(op, uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800636 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800637 scheduleFastWriteLocked();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800638 }
639 }
640 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800641 if (repCbs != null) {
Svet Ganov38536112015-05-19 12:45:52 -0700642 // There are components watching for mode changes such as window manager
643 // and location manager which are in our process. The callbacks in these
644 // components may require permissions our remote caller does not have.
645 final long identity = Binder.clearCallingIdentity();
646 try {
647 for (int i = 0; i < repCbs.size(); i++) {
648 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700649 repCbs.get(i).mCallback.opChanged(code, uid, packageName);
Svet Ganov38536112015-05-19 12:45:52 -0700650 } catch (RemoteException e) {
651 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800652 }
Svet Ganov38536112015-05-19 12:45:52 -0700653 } finally {
654 Binder.restoreCallingIdentity(identity);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800655 }
656 }
657 }
658
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700659 private static HashMap<Callback, ArrayList<ChangeRec>> addCallbacks(
660 HashMap<Callback, ArrayList<ChangeRec>> callbacks,
661 int op, int uid, String packageName, ArrayList<Callback> cbs) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700662 if (cbs == null) {
663 return callbacks;
664 }
665 if (callbacks == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700666 callbacks = new HashMap<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700667 }
Svet Ganov2af57082015-07-30 08:44:20 -0700668 boolean duplicate = false;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700669 for (int i=0; i<cbs.size(); i++) {
670 Callback cb = cbs.get(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700671 ArrayList<ChangeRec> reports = callbacks.get(cb);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700672 if (reports == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700673 reports = new ArrayList<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700674 callbacks.put(cb, reports);
Svet Ganov2af57082015-07-30 08:44:20 -0700675 } else {
676 final int reportCount = reports.size();
677 for (int j = 0; j < reportCount; j++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700678 ChangeRec report = reports.get(j);
679 if (report.op == op && report.pkg.equals(packageName)) {
Svet Ganov2af57082015-07-30 08:44:20 -0700680 duplicate = true;
681 break;
682 }
683 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700684 }
Svet Ganov2af57082015-07-30 08:44:20 -0700685 if (!duplicate) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700686 reports.add(new ChangeRec(op, uid, packageName));
Svet Ganov2af57082015-07-30 08:44:20 -0700687 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700688 }
689 return callbacks;
690 }
691
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700692 static final class ChangeRec {
693 final int op;
694 final int uid;
695 final String pkg;
696
697 ChangeRec(int _op, int _uid, String _pkg) {
698 op = _op;
699 uid = _uid;
700 pkg = _pkg;
701 }
702 }
703
Dianne Hackborn607b4142013-08-02 18:10:10 -0700704 @Override
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800705 public void resetAllModes(int reqUserId, String reqPackageName) {
706 final int callingPid = Binder.getCallingPid();
707 final int callingUid = Binder.getCallingUid();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700708 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800709 callingPid, callingUid, null);
710 reqUserId = ActivityManager.handleIncomingUser(callingPid, callingUid, reqUserId,
711 true, true, "resetAllModes", null);
Svet Ganov2af57082015-07-30 08:44:20 -0700712
713 int reqUid = -1;
714 if (reqPackageName != null) {
715 try {
716 reqUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -0700717 reqPackageName, PackageManager.MATCH_UNINSTALLED_PACKAGES, reqUserId);
Svet Ganov2af57082015-07-30 08:44:20 -0700718 } catch (RemoteException e) {
719 /* ignore - local call */
720 }
721 }
722
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700723 HashMap<Callback, ArrayList<ChangeRec>> callbacks = null;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700724 synchronized (this) {
725 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700726 for (int i = mUidStates.size() - 1; i >= 0; i--) {
727 UidState uidState = mUidStates.valueAt(i);
728
729 SparseIntArray opModes = uidState.opModes;
730 if (opModes != null && (uidState.uid == reqUid || reqUid == -1)) {
731 final int uidOpCount = opModes.size();
732 for (int j = uidOpCount - 1; j >= 0; j--) {
733 final int code = opModes.keyAt(j);
734 if (AppOpsManager.opAllowsReset(code)) {
735 opModes.removeAt(j);
736 if (opModes.size() <= 0) {
737 uidState.opModes = null;
738 }
739 for (String packageName : getPackagesForUid(uidState.uid)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700740 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700741 mOpModeWatchers.get(code));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700742 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700743 mPackageModeWatchers.get(packageName));
744 }
745 }
746 }
747 }
748
749 if (uidState.pkgOps == null) {
750 continue;
751 }
752
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800753 if (reqUserId != UserHandle.USER_ALL
Svet Ganov2af57082015-07-30 08:44:20 -0700754 && reqUserId != UserHandle.getUserId(uidState.uid)) {
Alexandra Gherghinad6a98972014-08-04 17:05:34 +0100755 // Skip any ops for a different user
756 continue;
757 }
Svet Ganov2af57082015-07-30 08:44:20 -0700758
759 Map<String, Ops> packages = uidState.pkgOps;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700760 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
761 while (it.hasNext()) {
762 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700763 String packageName = ent.getKey();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800764 if (reqPackageName != null && !reqPackageName.equals(packageName)) {
765 // Skip any ops for a different package
766 continue;
767 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700768 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700769 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700770 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -0700771 if (AppOpsManager.opAllowsReset(curOp.op)
772 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -0700773 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700774 changed = true;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700775 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -0700776 mOpModeWatchers.get(curOp.op));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700777 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -0700778 mPackageModeWatchers.get(packageName));
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700779 if (curOp.time == 0 && curOp.rejectTime == 0) {
780 pkgOps.removeAt(j);
781 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700782 }
783 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700784 if (pkgOps.size() == 0) {
785 it.remove();
786 }
787 }
Svet Ganov2af57082015-07-30 08:44:20 -0700788 if (uidState.isDefault()) {
789 mUidStates.remove(uidState.uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700790 }
791 }
Svet Ganov2af57082015-07-30 08:44:20 -0700792
Dianne Hackborn607b4142013-08-02 18:10:10 -0700793 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800794 scheduleFastWriteLocked();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700795 }
796 }
797 if (callbacks != null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700798 for (Map.Entry<Callback, ArrayList<ChangeRec>> ent : callbacks.entrySet()) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700799 Callback cb = ent.getKey();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700800 ArrayList<ChangeRec> reports = ent.getValue();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700801 for (int i=0; i<reports.size(); i++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700802 ChangeRec rep = reports.get(i);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700803 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700804 cb.mCallback.opChanged(rep.op, rep.uid, rep.pkg);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700805 } catch (RemoteException e) {
806 }
807 }
808 }
809 }
810 }
811
Dianne Hackbornc2293022013-02-06 23:14:49 -0800812 @Override
813 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -0800814 if (callback == null) {
815 return;
816 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800817 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700818 op = (op != AppOpsManager.OP_NONE) ? AppOpsManager.opToSwitch(op) : op;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800819 Callback cb = mModeWatchers.get(callback.asBinder());
820 if (cb == null) {
821 cb = new Callback(callback);
822 mModeWatchers.put(callback.asBinder(), cb);
823 }
824 if (op != AppOpsManager.OP_NONE) {
825 ArrayList<Callback> cbs = mOpModeWatchers.get(op);
826 if (cbs == null) {
827 cbs = new ArrayList<Callback>();
828 mOpModeWatchers.put(op, cbs);
829 }
830 cbs.add(cb);
831 }
832 if (packageName != null) {
833 ArrayList<Callback> cbs = mPackageModeWatchers.get(packageName);
834 if (cbs == null) {
835 cbs = new ArrayList<Callback>();
836 mPackageModeWatchers.put(packageName, cbs);
837 }
838 cbs.add(cb);
839 }
840 }
841 }
842
843 @Override
844 public void stopWatchingMode(IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -0800845 if (callback == null) {
846 return;
847 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800848 synchronized (this) {
849 Callback cb = mModeWatchers.remove(callback.asBinder());
850 if (cb != null) {
851 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700852 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800853 ArrayList<Callback> cbs = mOpModeWatchers.valueAt(i);
854 cbs.remove(cb);
855 if (cbs.size() <= 0) {
856 mOpModeWatchers.removeAt(i);
857 }
858 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700859 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
860 ArrayList<Callback> cbs = mPackageModeWatchers.valueAt(i);
861 cbs.remove(cb);
862 if (cbs.size() <= 0) {
863 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800864 }
865 }
866 }
867 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800868 }
869
870 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700871 public IBinder getToken(IBinder clientToken) {
872 synchronized (this) {
873 ClientState cs = mClients.get(clientToken);
874 if (cs == null) {
875 cs = new ClientState(clientToken);
876 mClients.put(clientToken, cs);
877 }
878 return cs;
879 }
880 }
881
882 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800883 public int checkOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800884 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800885 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000886 String resolvedPackageName = resolvePackageName(uid, packageName);
887 if (resolvedPackageName == null) {
888 return AppOpsManager.MODE_IGNORED;
889 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800890 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000891 if (isOpRestricted(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -0400892 return AppOpsManager.MODE_IGNORED;
893 }
Svet Ganov2af57082015-07-30 08:44:20 -0700894 code = AppOpsManager.opToSwitch(code);
895 UidState uidState = getUidStateLocked(uid, false);
896 if (uidState != null && uidState.opModes != null) {
897 final int uidMode = uidState.opModes.get(code);
898 if (uidMode != AppOpsManager.MODE_ALLOWED) {
899 return uidMode;
900 }
901 }
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000902 Op op = getOpLocked(code, uid, resolvedPackageName, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800903 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -0700904 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800905 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800906 return op.mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800907 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800908 }
909
910 @Override
John Spurlock7b414672014-07-18 13:02:39 -0400911 public int checkAudioOperation(int code, int usage, int uid, String packageName) {
Andrei Stingaceanuefc4a342016-03-22 14:43:01 +0000912 boolean suspended;
913 try {
914 suspended = isPackageSuspendedForUser(packageName, uid);
915 } catch (IllegalArgumentException ex) {
916 // Package not found.
917 suspended = false;
918 }
919
920 if (suspended) {
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000921 Log.i(TAG, "Audio disabled for suspended package=" + packageName + " for uid=" + uid);
922 return AppOpsManager.MODE_IGNORED;
923 }
924
John Spurlock1af30c72014-03-10 08:33:35 -0400925 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -0400926 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -0400927 if (mode != AppOpsManager.MODE_ALLOWED) {
928 return mode;
929 }
930 }
931 return checkOperation(code, uid, packageName);
932 }
933
Andrei Stingaceanu355b2322016-02-12 16:43:51 +0000934 private boolean isPackageSuspendedForUser(String pkg, int uid) {
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000935 try {
Andrei Stingaceanu355b2322016-02-12 16:43:51 +0000936 return AppGlobals.getPackageManager().isPackageSuspendedForUser(
937 pkg, UserHandle.getUserId(uid));
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000938 } catch (RemoteException re) {
939 throw new SecurityException("Could not talk to package manager service");
940 }
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000941 }
942
John Spurlock7b414672014-07-18 13:02:39 -0400943 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
944 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
945 if (usageRestrictions != null) {
946 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -0400947 if (r != null && !r.exceptionPackages.contains(packageName)) {
948 return r.mode;
949 }
950 }
951 return AppOpsManager.MODE_ALLOWED;
952 }
953
954 @Override
John Spurlock7b414672014-07-18 13:02:39 -0400955 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -0400956 String[] exceptionPackages) {
957 verifyIncomingUid(uid);
958 verifyIncomingOp(code);
959 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -0400960 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
961 if (usageRestrictions == null) {
962 usageRestrictions = new SparseArray<Restriction>();
963 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -0400964 }
John Spurlock7b414672014-07-18 13:02:39 -0400965 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -0400966 if (mode != AppOpsManager.MODE_ALLOWED) {
967 final Restriction r = new Restriction();
968 r.mode = mode;
969 if (exceptionPackages != null) {
970 final int N = exceptionPackages.length;
971 r.exceptionPackages = new ArraySet<String>(N);
972 for (int i = 0; i < N; i++) {
973 final String pkg = exceptionPackages[i];
974 if (pkg != null) {
975 r.exceptionPackages.add(pkg.trim());
976 }
977 }
978 }
John Spurlock7b414672014-07-18 13:02:39 -0400979 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -0400980 }
981 }
982 }
983
984 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700985 public int checkPackage(int uid, String packageName) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000986 Preconditions.checkNotNull(packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700987 synchronized (this) {
Dianne Hackborn0fcef842014-09-12 15:38:33 -0700988 if (getOpsRawLocked(uid, packageName, true) != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700989 return AppOpsManager.MODE_ALLOWED;
990 } else {
991 return AppOpsManager.MODE_ERRORED;
992 }
993 }
994 }
995
996 @Override
Svet Ganov99b60432015-06-27 13:15:22 -0700997 public int noteProxyOperation(int code, String proxyPackageName,
998 int proxiedUid, String proxiedPackageName) {
999 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001000 final int proxyUid = Binder.getCallingUid();
1001 String resolveProxyPackageName = resolvePackageName(proxyUid, proxyPackageName);
1002 if (resolveProxyPackageName == null) {
1003 return AppOpsManager.MODE_IGNORED;
1004 }
1005 final int proxyMode = noteOperationUnchecked(code, proxyUid,
1006 resolveProxyPackageName, -1, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001007 if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
1008 return proxyMode;
1009 }
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001010 String resolveProxiedPackageName = resolvePackageName(proxiedUid, proxiedPackageName);
1011 if (resolveProxiedPackageName == null) {
1012 return AppOpsManager.MODE_IGNORED;
1013 }
1014 return noteOperationUnchecked(code, proxiedUid, resolveProxiedPackageName,
1015 proxyMode, resolveProxyPackageName);
Svet Ganov99b60432015-06-27 13:15:22 -07001016 }
1017
1018 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001019 public int noteOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001020 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001021 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001022 String resolvedPackageName = resolvePackageName(uid, packageName);
1023 if (resolvedPackageName == null) {
1024 return AppOpsManager.MODE_IGNORED;
1025 }
1026 return noteOperationUnchecked(code, uid, resolvedPackageName, 0, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001027 }
1028
1029 private int noteOperationUnchecked(int code, int uid, String packageName,
1030 int proxyUid, String proxyPackageName) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001031 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001032 Ops ops = getOpsRawLocked(uid, packageName, true);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001033 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001034 if (DEBUG) Log.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
1035 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001036 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001037 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001038 Op op = getOpLocked(ops, code, true);
Jason Monk1c7c3192014-06-26 12:52:18 -04001039 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001040 return AppOpsManager.MODE_IGNORED;
1041 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001042 if (op.duration == -1) {
1043 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
1044 + " code " + code + " time=" + op.time + " duration=" + op.duration);
1045 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001046 op.duration = 0;
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001047 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001048 UidState uidState = ops.uidState;
1049 if (uidState.opModes != null) {
1050 final int uidMode = uidState.opModes.get(switchCode);
1051 if (uidMode != AppOpsManager.MODE_ALLOWED) {
1052 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1053 + switchCode + " (" + code + ") uid " + uid + " package "
1054 + packageName);
1055 op.rejectTime = System.currentTimeMillis();
1056 return uidMode;
1057 }
1058 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001059 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
1060 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
1061 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1062 + switchCode + " (" + code + ") uid " + uid + " package " + packageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001063 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001064 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001065 }
1066 if (DEBUG) Log.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
1067 + " package " + packageName);
1068 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001069 op.rejectTime = 0;
Svet Ganov99b60432015-06-27 13:15:22 -07001070 op.proxyUid = proxyUid;
1071 op.proxyPackageName = proxyPackageName;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001072 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001073 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001074 }
1075
1076 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001077 public int startOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001078 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001079 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001080 String resolvedPackageName = resolvePackageName(uid, packageName);
1081 if (resolvedPackageName == null) {
1082 return AppOpsManager.MODE_IGNORED;
1083 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001084 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001085 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001086 Ops ops = getOpsRawLocked(uid, resolvedPackageName, true);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001087 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001088 if (DEBUG) Log.d(TAG, "startOperation: no op for code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001089 + " package " + resolvedPackageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001090 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001091 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001092 Op op = getOpLocked(ops, code, true);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001093 if (isOpRestricted(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001094 return AppOpsManager.MODE_IGNORED;
1095 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001096 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001097 UidState uidState = ops.uidState;
1098 if (uidState.opModes != null) {
1099 final int uidMode = uidState.opModes.get(switchCode);
1100 if (uidMode != AppOpsManager.MODE_ALLOWED) {
1101 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1102 + switchCode + " (" + code + ") uid " + uid + " package "
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001103 + resolvedPackageName);
Svet Ganov2af57082015-07-30 08:44:20 -07001104 op.rejectTime = System.currentTimeMillis();
1105 return uidMode;
1106 }
1107 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001108 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
1109 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
1110 if (DEBUG) Log.d(TAG, "startOperation: reject #" + op.mode + " for code "
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001111 + switchCode + " (" + code + ") uid " + uid + " package "
1112 + resolvedPackageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001113 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001114 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001115 }
1116 if (DEBUG) Log.d(TAG, "startOperation: allowing code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001117 + " package " + resolvedPackageName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001118 if (op.nesting == 0) {
1119 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001120 op.rejectTime = 0;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001121 op.duration = -1;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001122 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001123 op.nesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001124 if (client.mStartedOps != null) {
1125 client.mStartedOps.add(op);
1126 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001127 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001128 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001129 }
1130
1131 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001132 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001133 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001134 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001135 String resolvedPackageName = resolvePackageName(uid, packageName);
1136 if (resolvedPackageName == null) {
1137 return;
1138 }
1139 if (!(token instanceof ClientState)) {
1140 return;
1141 }
1142 ClientState client = (ClientState) token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001143 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001144 Op op = getOpLocked(code, uid, resolvedPackageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001145 if (op == null) {
1146 return;
1147 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001148 if (client.mStartedOps != null) {
1149 if (!client.mStartedOps.remove(op)) {
1150 throw new IllegalStateException("Operation not started: uid" + op.uid
1151 + " pkg=" + op.packageName + " op=" + op.op);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001152 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001153 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001154 finishOperationLocked(op);
1155 }
1156 }
1157
Svet Ganovb9d71a62015-04-30 10:38:13 -07001158 @Override
1159 public int permissionToOpCode(String permission) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001160 if (permission == null) {
1161 return AppOpsManager.OP_NONE;
1162 }
Svet Ganovb9d71a62015-04-30 10:38:13 -07001163 return AppOpsManager.permissionToOpCode(permission);
1164 }
1165
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001166 void finishOperationLocked(Op op) {
1167 if (op.nesting <= 1) {
1168 if (op.nesting == 1) {
1169 op.duration = (int)(System.currentTimeMillis() - op.time);
1170 op.time += op.duration;
1171 } else {
1172 Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
1173 + op.packageName + " code " + op.op + " time=" + op.time
1174 + " duration=" + op.duration + " nesting=" + op.nesting);
1175 }
1176 op.nesting = 0;
1177 } else {
1178 op.nesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001179 }
1180 }
1181
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001182 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001183 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001184 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001185 }
1186 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001187 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001188 }
1189 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
1190 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001191 }
1192
Dianne Hackborn961321f2013-02-05 17:22:41 -08001193 private void verifyIncomingOp(int op) {
1194 if (op >= 0 && op < AppOpsManager._NUM_OP) {
1195 return;
1196 }
1197 throw new IllegalArgumentException("Bad operation #" + op);
1198 }
1199
Svet Ganov2af57082015-07-30 08:44:20 -07001200 private UidState getUidStateLocked(int uid, boolean edit) {
1201 UidState uidState = mUidStates.get(uid);
1202 if (uidState == null) {
1203 if (!edit) {
1204 return null;
1205 }
1206 uidState = new UidState(uid);
1207 mUidStates.put(uid, uidState);
1208 }
1209 return uidState;
1210 }
1211
Dianne Hackborn0fcef842014-09-12 15:38:33 -07001212 private Ops getOpsRawLocked(int uid, String packageName, boolean edit) {
Svet Ganov2af57082015-07-30 08:44:20 -07001213 UidState uidState = getUidStateLocked(uid, edit);
1214 if (uidState == null) {
1215 return null;
1216 }
1217
1218 if (uidState.pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001219 if (!edit) {
1220 return null;
1221 }
Svet Ganov2af57082015-07-30 08:44:20 -07001222 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001223 }
Svet Ganov2af57082015-07-30 08:44:20 -07001224
1225 Ops ops = uidState.pkgOps.get(packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001226 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001227 if (!edit) {
1228 return null;
1229 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001230 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001231 // This is the first time we have seen this package name under this uid,
1232 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -08001233 if (uid != 0) {
1234 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001235 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001236 int pkgUid = -1;
1237 try {
Jason Monk1c7c3192014-06-26 12:52:18 -04001238 ApplicationInfo appInfo = ActivityThread.getPackageManager()
Jeff Sharkeycd654482016-01-08 17:42:11 -07001239 .getApplicationInfo(packageName,
1240 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1241 UserHandle.getUserId(uid));
Jason Monk1c7c3192014-06-26 12:52:18 -04001242 if (appInfo != null) {
1243 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001244 isPrivileged = (appInfo.privateFlags
1245 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001246 } else {
1247 if ("media".equals(packageName)) {
1248 pkgUid = Process.MEDIA_UID;
1249 isPrivileged = false;
Andy Hunged0ea402015-10-30 14:11:46 -07001250 } else if ("audioserver".equals(packageName)) {
1251 pkgUid = Process.AUDIOSERVER_UID;
1252 isPrivileged = false;
Chien-Yu Chen75cade02016-01-11 10:56:21 -08001253 } else if ("cameraserver".equals(packageName)) {
1254 pkgUid = Process.CAMERASERVER_UID;
1255 isPrivileged = false;
Jason Monk1c7c3192014-06-26 12:52:18 -04001256 }
Dianne Hackborn713df152013-05-17 11:27:57 -07001257 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001258 } catch (RemoteException e) {
1259 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001260 }
1261 if (pkgUid != uid) {
1262 // Oops! The package name is not valid for the uid they are calling
1263 // under. Abort.
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001264 RuntimeException ex = new RuntimeException("here");
1265 ex.fillInStackTrace();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001266 Slog.w(TAG, "Bad call: specified package " + packageName
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001267 + " under uid " + uid + " but it is really " + pkgUid, ex);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001268 return null;
1269 }
1270 } finally {
1271 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001272 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001273 }
Svet Ganov2af57082015-07-30 08:44:20 -07001274 ops = new Ops(packageName, uidState, isPrivileged);
1275 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001276 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08001277 return ops;
1278 }
1279
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001280 private void scheduleWriteLocked() {
1281 if (!mWriteScheduled) {
1282 mWriteScheduled = true;
1283 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
1284 }
1285 }
1286
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001287 private void scheduleFastWriteLocked() {
1288 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001289 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001290 mFastWriteScheduled = true;
1291 mHandler.removeCallbacks(mWriteRunner);
1292 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001293 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001294 }
1295
Dianne Hackborn72e39832013-01-18 18:36:09 -08001296 private Op getOpLocked(int code, int uid, String packageName, boolean edit) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001297 Ops ops = getOpsRawLocked(uid, packageName, edit);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001298 if (ops == null) {
1299 return null;
1300 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001301 return getOpLocked(ops, code, edit);
1302 }
1303
1304 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001305 Op op = ops.get(code);
1306 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001307 if (!edit) {
1308 return null;
1309 }
Svet Ganov2af57082015-07-30 08:44:20 -07001310 op = new Op(ops.uidState.uid, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001311 ops.put(code, op);
1312 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001313 if (edit) {
1314 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001315 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001316 return op;
1317 }
1318
Jason Monk1c7c3192014-06-26 12:52:18 -04001319 private boolean isOpRestricted(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04001320 int userHandle = UserHandle.getUserId(uid);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001321 final int restrictionSetCount = mOpUserRestrictions.size();
Ruben Brunk29931bc2016-03-11 00:24:26 -08001322
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001323 for (int i = 0; i < restrictionSetCount; i++) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08001324 // For each client, check that the given op is not restricted, or that the given
1325 // package is exempt from the restriction.
1326
1327 SparseArray<Pair<boolean[],SparseArray<ArraySet<String>>>> perUserRestrictions =
1328 mOpUserRestrictions.valueAt(i);
1329
1330 Pair<boolean[],SparseArray<ArraySet<String>>> restrictions =
1331 perUserRestrictions.get(userHandle);
1332 if (restrictions == null) {
1333 continue; // No restrictions set by this client
1334 }
1335
1336 boolean[] opRestrictions = restrictions.first;
1337 SparseArray<ArraySet<String>> opExceptions = restrictions.second;
1338
1339 if (opRestrictions == null) {
1340 continue; // No restrictions set by this client
1341 }
1342
1343 if (opRestrictions[code]) {
Ruben Brunk32f0fa42016-03-11 19:07:07 -08001344
1345 if (opExceptions != null) {
1346 ArraySet<String> ex = opExceptions.get(code);
1347 if (ex != null && ex.contains(packageName)) {
1348 continue; // AppOps code is restricted, but this package is exempt
1349 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08001350 }
1351
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001352 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08001353 // If we are the system, bypass user restrictions for certain codes
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001354 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001355 Ops ops = getOpsRawLocked(uid, packageName, true);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001356 if ((ops != null) && ops.isPrivileged) {
1357 return false;
1358 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001359 }
1360 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08001361
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001362 return true;
Jason Monk1c7c3192014-06-26 12:52:18 -04001363 }
Jason Monk62062992014-05-06 09:55:28 -04001364 }
1365 return false;
1366 }
1367
Dianne Hackborn35654b62013-01-14 17:38:02 -08001368 void readState() {
1369 synchronized (mFile) {
1370 synchronized (this) {
1371 FileInputStream stream;
1372 try {
1373 stream = mFile.openRead();
1374 } catch (FileNotFoundException e) {
1375 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
1376 return;
1377 }
1378 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001379 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001380 try {
1381 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001382 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001383 int type;
1384 while ((type = parser.next()) != XmlPullParser.START_TAG
1385 && type != XmlPullParser.END_DOCUMENT) {
1386 ;
1387 }
1388
1389 if (type != XmlPullParser.START_TAG) {
1390 throw new IllegalStateException("no start tag found");
1391 }
1392
1393 int outerDepth = parser.getDepth();
1394 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1395 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1396 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1397 continue;
1398 }
1399
1400 String tagName = parser.getName();
1401 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001402 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07001403 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07001404 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001405 } else {
1406 Slog.w(TAG, "Unknown element under <app-ops>: "
1407 + parser.getName());
1408 XmlUtils.skipCurrentTag(parser);
1409 }
1410 }
1411 success = true;
1412 } catch (IllegalStateException e) {
1413 Slog.w(TAG, "Failed parsing " + e);
1414 } catch (NullPointerException e) {
1415 Slog.w(TAG, "Failed parsing " + e);
1416 } catch (NumberFormatException e) {
1417 Slog.w(TAG, "Failed parsing " + e);
1418 } catch (XmlPullParserException e) {
1419 Slog.w(TAG, "Failed parsing " + e);
1420 } catch (IOException e) {
1421 Slog.w(TAG, "Failed parsing " + e);
1422 } catch (IndexOutOfBoundsException e) {
1423 Slog.w(TAG, "Failed parsing " + e);
1424 } finally {
1425 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07001426 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001427 }
1428 try {
1429 stream.close();
1430 } catch (IOException e) {
1431 }
1432 }
1433 }
1434 }
1435 }
1436
Svet Ganov2af57082015-07-30 08:44:20 -07001437 void readUidOps(XmlPullParser parser) throws NumberFormatException,
1438 XmlPullParserException, IOException {
1439 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
1440 int outerDepth = parser.getDepth();
1441 int type;
1442 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1443 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1444 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1445 continue;
1446 }
1447
1448 String tagName = parser.getName();
1449 if (tagName.equals("op")) {
1450 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
1451 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
1452 UidState uidState = getUidStateLocked(uid, true);
1453 if (uidState.opModes == null) {
1454 uidState.opModes = new SparseIntArray();
1455 }
1456 uidState.opModes.put(code, mode);
1457 } else {
1458 Slog.w(TAG, "Unknown element under <uid-ops>: "
1459 + parser.getName());
1460 XmlUtils.skipCurrentTag(parser);
1461 }
1462 }
1463 }
1464
Dave Burke0997c5bd2013-08-02 20:25:02 +00001465 void readPackage(XmlPullParser parser) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001466 XmlPullParserException, IOException {
1467 String pkgName = parser.getAttributeValue(null, "n");
1468 int outerDepth = parser.getDepth();
1469 int type;
1470 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1471 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1472 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1473 continue;
1474 }
1475
1476 String tagName = parser.getName();
1477 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001478 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001479 } else {
1480 Slog.w(TAG, "Unknown element under <pkg>: "
1481 + parser.getName());
1482 XmlUtils.skipCurrentTag(parser);
1483 }
1484 }
1485 }
1486
Dave Burke0997c5bd2013-08-02 20:25:02 +00001487 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001488 XmlPullParserException, IOException {
1489 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Jason Monk1c7c3192014-06-26 12:52:18 -04001490 String isPrivilegedString = parser.getAttributeValue(null, "p");
1491 boolean isPrivileged = false;
1492 if (isPrivilegedString == null) {
1493 try {
1494 IPackageManager packageManager = ActivityThread.getPackageManager();
1495 if (packageManager != null) {
1496 ApplicationInfo appInfo = ActivityThread.getPackageManager()
1497 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
1498 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001499 isPrivileged = (appInfo.privateFlags
1500 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001501 }
1502 } else {
1503 // Could not load data, don't add to cache so it will be loaded later.
1504 return;
1505 }
1506 } catch (RemoteException e) {
1507 Slog.w(TAG, "Could not contact PackageManager", e);
1508 }
1509 } else {
1510 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
1511 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001512 int outerDepth = parser.getDepth();
1513 int type;
1514 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1515 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1516 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1517 continue;
1518 }
1519
1520 String tagName = parser.getName();
1521 if (tagName.equals("op")) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001522 Op op = new Op(uid, pkgName, Integer.parseInt(parser.getAttributeValue(null, "n")));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001523 String mode = parser.getAttributeValue(null, "m");
1524 if (mode != null) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001525 op.mode = Integer.parseInt(mode);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001526 }
1527 String time = parser.getAttributeValue(null, "t");
1528 if (time != null) {
1529 op.time = Long.parseLong(time);
1530 }
1531 time = parser.getAttributeValue(null, "r");
1532 if (time != null) {
1533 op.rejectTime = Long.parseLong(time);
1534 }
1535 String dur = parser.getAttributeValue(null, "d");
1536 if (dur != null) {
1537 op.duration = Integer.parseInt(dur);
1538 }
Svet Ganov99b60432015-06-27 13:15:22 -07001539 String proxyUid = parser.getAttributeValue(null, "pu");
1540 if (proxyUid != null) {
1541 op.proxyUid = Integer.parseInt(proxyUid);
1542 }
1543 String proxyPackageName = parser.getAttributeValue(null, "pp");
1544 if (proxyPackageName != null) {
1545 op.proxyPackageName = proxyPackageName;
1546 }
Svet Ganov2af57082015-07-30 08:44:20 -07001547
1548 UidState uidState = getUidStateLocked(uid, true);
1549 if (uidState.pkgOps == null) {
1550 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001551 }
Svet Ganov2af57082015-07-30 08:44:20 -07001552
1553 Ops ops = uidState.pkgOps.get(pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001554 if (ops == null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001555 ops = new Ops(pkgName, uidState, isPrivileged);
1556 uidState.pkgOps.put(pkgName, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001557 }
1558 ops.put(op.op, op);
1559 } else {
1560 Slog.w(TAG, "Unknown element under <pkg>: "
1561 + parser.getName());
1562 XmlUtils.skipCurrentTag(parser);
1563 }
1564 }
1565 }
1566
1567 void writeState() {
1568 synchronized (mFile) {
1569 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
1570
1571 FileOutputStream stream;
1572 try {
1573 stream = mFile.startWrite();
1574 } catch (IOException e) {
1575 Slog.w(TAG, "Failed to write state: " + e);
1576 return;
1577 }
1578
1579 try {
1580 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001581 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001582 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001583 out.startTag(null, "app-ops");
Svet Ganov2af57082015-07-30 08:44:20 -07001584
1585 final int uidStateCount = mUidStates.size();
1586 for (int i = 0; i < uidStateCount; i++) {
1587 UidState uidState = mUidStates.valueAt(i);
1588 if (uidState.opModes != null && uidState.opModes.size() > 0) {
1589 out.startTag(null, "uid");
1590 out.attribute(null, "n", Integer.toString(uidState.uid));
1591 SparseIntArray uidOpModes = uidState.opModes;
1592 final int opCount = uidOpModes.size();
1593 for (int j = 0; j < opCount; j++) {
1594 final int op = uidOpModes.keyAt(j);
1595 final int mode = uidOpModes.valueAt(j);
1596 out.startTag(null, "op");
1597 out.attribute(null, "n", Integer.toString(op));
1598 out.attribute(null, "m", Integer.toString(mode));
1599 out.endTag(null, "op");
1600 }
1601 out.endTag(null, "uid");
1602 }
1603 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001604
1605 if (allOps != null) {
1606 String lastPkg = null;
1607 for (int i=0; i<allOps.size(); i++) {
1608 AppOpsManager.PackageOps pkg = allOps.get(i);
1609 if (!pkg.getPackageName().equals(lastPkg)) {
1610 if (lastPkg != null) {
1611 out.endTag(null, "pkg");
1612 }
1613 lastPkg = pkg.getPackageName();
1614 out.startTag(null, "pkg");
1615 out.attribute(null, "n", lastPkg);
1616 }
1617 out.startTag(null, "uid");
1618 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04001619 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001620 Ops ops = getOpsRawLocked(pkg.getUid(), pkg.getPackageName(), false);
Jason Monk1c7c3192014-06-26 12:52:18 -04001621 // Should always be present as the list of PackageOps is generated
1622 // from Ops.
1623 if (ops != null) {
1624 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
1625 } else {
1626 out.attribute(null, "p", Boolean.toString(false));
1627 }
1628 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001629 List<AppOpsManager.OpEntry> ops = pkg.getOps();
1630 for (int j=0; j<ops.size(); j++) {
1631 AppOpsManager.OpEntry op = ops.get(j);
1632 out.startTag(null, "op");
1633 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07001634 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001635 out.attribute(null, "m", Integer.toString(op.getMode()));
1636 }
1637 long time = op.getTime();
1638 if (time != 0) {
1639 out.attribute(null, "t", Long.toString(time));
1640 }
1641 time = op.getRejectTime();
1642 if (time != 0) {
1643 out.attribute(null, "r", Long.toString(time));
1644 }
1645 int dur = op.getDuration();
1646 if (dur != 0) {
1647 out.attribute(null, "d", Integer.toString(dur));
1648 }
Svet Ganov99b60432015-06-27 13:15:22 -07001649 int proxyUid = op.getProxyUid();
1650 if (proxyUid != -1) {
1651 out.attribute(null, "pu", Integer.toString(proxyUid));
1652 }
1653 String proxyPackageName = op.getProxyPackageName();
1654 if (proxyPackageName != null) {
1655 out.attribute(null, "pp", proxyPackageName);
1656 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001657 out.endTag(null, "op");
1658 }
1659 out.endTag(null, "uid");
1660 }
1661 if (lastPkg != null) {
1662 out.endTag(null, "pkg");
1663 }
1664 }
1665
1666 out.endTag(null, "app-ops");
1667 out.endDocument();
1668 mFile.finishWrite(stream);
1669 } catch (IOException e) {
1670 Slog.w(TAG, "Failed to write state, restoring backup.", e);
1671 mFile.failWrite(stream);
1672 }
1673 }
1674 }
1675
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001676 static class Shell extends ShellCommand {
1677 final IAppOpsService mInterface;
1678 final AppOpsService mInternal;
1679
1680 int userId = UserHandle.USER_SYSTEM;
1681 String packageName;
1682 String opStr;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001683 String modeStr;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001684 int op;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001685 int mode;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001686 int packageUid;
1687
1688 Shell(IAppOpsService iface, AppOpsService internal) {
1689 mInterface = iface;
1690 mInternal = internal;
1691 }
1692
1693 @Override
1694 public int onCommand(String cmd) {
1695 return onShellCommand(this, cmd);
1696 }
1697
1698 @Override
1699 public void onHelp() {
1700 PrintWriter pw = getOutPrintWriter();
1701 dumpCommandHelp(pw);
1702 }
1703
1704 private int strOpToOp(String op, PrintWriter err) {
1705 try {
1706 return AppOpsManager.strOpToOp(op);
1707 } catch (IllegalArgumentException e) {
1708 }
1709 try {
1710 return Integer.parseInt(op);
1711 } catch (NumberFormatException e) {
1712 }
1713 try {
1714 return AppOpsManager.strDebugOpToOp(op);
1715 } catch (IllegalArgumentException e) {
1716 err.println("Error: " + e.getMessage());
1717 return -1;
1718 }
1719 }
1720
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001721 int strModeToMode(String modeStr, PrintWriter err) {
1722 switch (modeStr) {
1723 case "allow":
1724 return AppOpsManager.MODE_ALLOWED;
1725 case "deny":
1726 return AppOpsManager.MODE_ERRORED;
1727 case "ignore":
1728 return AppOpsManager.MODE_IGNORED;
1729 case "default":
1730 return AppOpsManager.MODE_DEFAULT;
1731 }
1732 try {
1733 return Integer.parseInt(modeStr);
1734 } catch (NumberFormatException e) {
1735 }
1736 err.println("Error: Mode " + modeStr + " is not valid");
1737 return -1;
1738 }
1739
1740 int parseUserOpMode(int defMode, PrintWriter err) throws RemoteException {
1741 userId = UserHandle.USER_CURRENT;
1742 opStr = null;
1743 modeStr = null;
1744 for (String argument; (argument = getNextArg()) != null;) {
1745 if ("--user".equals(argument)) {
1746 userId = UserHandle.parseUserArg(getNextArgRequired());
1747 } else {
1748 if (opStr == null) {
1749 opStr = argument;
1750 } else if (modeStr == null) {
1751 modeStr = argument;
1752 break;
1753 }
1754 }
1755 }
1756 if (opStr == null) {
1757 err.println("Error: Operation not specified.");
1758 return -1;
1759 }
1760 op = strOpToOp(opStr, err);
1761 if (op < 0) {
1762 return -1;
1763 }
1764 if (modeStr != null) {
1765 if ((mode=strModeToMode(modeStr, err)) < 0) {
1766 return -1;
1767 }
1768 } else {
1769 mode = defMode;
1770 }
1771 return 0;
1772 }
1773
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001774 int parseUserPackageOp(boolean reqOp, PrintWriter err) throws RemoteException {
1775 userId = UserHandle.USER_CURRENT;
1776 packageName = null;
1777 opStr = null;
1778 for (String argument; (argument = getNextArg()) != null;) {
1779 if ("--user".equals(argument)) {
1780 userId = UserHandle.parseUserArg(getNextArgRequired());
1781 } else {
1782 if (packageName == null) {
1783 packageName = argument;
1784 } else if (opStr == null) {
1785 opStr = argument;
1786 break;
1787 }
1788 }
1789 }
1790 if (packageName == null) {
1791 err.println("Error: Package name not specified.");
1792 return -1;
1793 } else if (opStr == null && reqOp) {
1794 err.println("Error: Operation not specified.");
1795 return -1;
1796 }
1797 if (opStr != null) {
1798 op = strOpToOp(opStr, err);
1799 if (op < 0) {
1800 return -1;
1801 }
1802 } else {
1803 op = AppOpsManager.OP_NONE;
1804 }
1805 if (userId == UserHandle.USER_CURRENT) {
1806 userId = ActivityManager.getCurrentUser();
1807 }
1808 if ("root".equals(packageName)) {
1809 packageUid = 0;
1810 } else {
Jeff Sharkeycd654482016-01-08 17:42:11 -07001811 packageUid = AppGlobals.getPackageManager().getPackageUid(packageName,
1812 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001813 }
1814 if (packageUid < 0) {
1815 err.println("Error: No UID for " + packageName + " in user " + userId);
1816 return -1;
1817 }
1818 return 0;
1819 }
1820 }
1821
1822 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
1823 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
1824 (new Shell(this, this)).exec(this, in, out, err, args, resultReceiver);
1825 }
1826
1827 static void dumpCommandHelp(PrintWriter pw) {
1828 pw.println("AppOps service (appops) commands:");
1829 pw.println(" help");
1830 pw.println(" Print this help text.");
1831 pw.println(" set [--user <USER_ID>] <PACKAGE> <OP> <MODE>");
1832 pw.println(" Set the mode for a particular application and operation.");
1833 pw.println(" get [--user <USER_ID>] <PACKAGE> [<OP>]");
1834 pw.println(" Return the mode for a particular application and optional operation.");
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001835 pw.println(" query-op [--user <USER_ID>] <OP> [<MODE>]");
1836 pw.println(" Print all packages that currently have the given op in the given mode.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001837 pw.println(" reset [--user <USER_ID>] [<PACKAGE>]");
1838 pw.println(" Reset the given application or all applications to default modes.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001839 pw.println(" write-settings");
1840 pw.println(" Immediately write pending changes to storage.");
1841 pw.println(" read-settings");
1842 pw.println(" Read the last written settings, replacing current state in RAM.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001843 pw.println(" options:");
1844 pw.println(" <PACKAGE> an Android package name.");
1845 pw.println(" <OP> an AppOps operation.");
1846 pw.println(" <MODE> one of allow, ignore, deny, or default");
1847 pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
1848 pw.println(" specified, the current user is assumed.");
1849 }
1850
1851 static int onShellCommand(Shell shell, String cmd) {
1852 if (cmd == null) {
1853 return shell.handleDefaultCommands(cmd);
1854 }
1855 PrintWriter pw = shell.getOutPrintWriter();
1856 PrintWriter err = shell.getErrPrintWriter();
1857 try {
1858 switch (cmd) {
1859 case "set": {
1860 int res = shell.parseUserPackageOp(true, err);
1861 if (res < 0) {
1862 return res;
1863 }
1864 String modeStr = shell.getNextArg();
1865 if (modeStr == null) {
1866 err.println("Error: Mode not specified.");
1867 return -1;
1868 }
1869
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001870 final int mode = shell.strModeToMode(modeStr, err);
1871 if (mode < 0) {
1872 return -1;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001873 }
1874
1875 shell.mInterface.setMode(shell.op, shell.packageUid, shell.packageName, mode);
1876 return 0;
1877 }
1878 case "get": {
1879 int res = shell.parseUserPackageOp(false, err);
1880 if (res < 0) {
1881 return res;
1882 }
1883
1884 List<AppOpsManager.PackageOps> ops = shell.mInterface.getOpsForPackage(
1885 shell.packageUid, shell.packageName,
1886 shell.op != AppOpsManager.OP_NONE ? new int[] {shell.op} : null);
1887 if (ops == null || ops.size() <= 0) {
1888 pw.println("No operations.");
1889 return 0;
1890 }
1891 final long now = System.currentTimeMillis();
1892 for (int i=0; i<ops.size(); i++) {
1893 List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
1894 for (int j=0; j<entries.size(); j++) {
1895 AppOpsManager.OpEntry ent = entries.get(j);
1896 pw.print(AppOpsManager.opToName(ent.getOp()));
1897 pw.print(": ");
1898 switch (ent.getMode()) {
1899 case AppOpsManager.MODE_ALLOWED:
1900 pw.print("allow");
1901 break;
1902 case AppOpsManager.MODE_IGNORED:
1903 pw.print("ignore");
1904 break;
1905 case AppOpsManager.MODE_ERRORED:
1906 pw.print("deny");
1907 break;
1908 case AppOpsManager.MODE_DEFAULT:
1909 pw.print("default");
1910 break;
1911 default:
1912 pw.print("mode=");
1913 pw.print(ent.getMode());
1914 break;
1915 }
1916 if (ent.getTime() != 0) {
1917 pw.print("; time=");
1918 TimeUtils.formatDuration(now - ent.getTime(), pw);
1919 pw.print(" ago");
1920 }
1921 if (ent.getRejectTime() != 0) {
1922 pw.print("; rejectTime=");
1923 TimeUtils.formatDuration(now - ent.getRejectTime(), pw);
1924 pw.print(" ago");
1925 }
1926 if (ent.getDuration() == -1) {
1927 pw.print(" (running)");
1928 } else if (ent.getDuration() != 0) {
1929 pw.print("; duration=");
1930 TimeUtils.formatDuration(ent.getDuration(), pw);
1931 }
1932 pw.println();
1933 }
1934 }
1935 return 0;
1936 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001937 case "query-op": {
1938 int res = shell.parseUserOpMode(AppOpsManager.MODE_IGNORED, err);
1939 if (res < 0) {
1940 return res;
1941 }
1942 List<AppOpsManager.PackageOps> ops = shell.mInterface.getPackagesForOps(
1943 new int[] {shell.op});
1944 if (ops == null || ops.size() <= 0) {
1945 pw.println("No operations.");
1946 return 0;
1947 }
1948 for (int i=0; i<ops.size(); i++) {
1949 final AppOpsManager.PackageOps pkg = ops.get(i);
1950 boolean hasMatch = false;
1951 final List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
1952 for (int j=0; j<entries.size(); j++) {
1953 AppOpsManager.OpEntry ent = entries.get(j);
1954 if (ent.getOp() == shell.op && ent.getMode() == shell.mode) {
1955 hasMatch = true;
1956 break;
1957 }
1958 }
1959 if (hasMatch) {
1960 pw.println(pkg.getPackageName());
1961 }
1962 }
1963 return 0;
1964 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001965 case "reset": {
1966 String packageName = null;
1967 int userId = UserHandle.USER_CURRENT;
1968 for (String argument; (argument = shell.getNextArg()) != null;) {
1969 if ("--user".equals(argument)) {
1970 String userStr = shell.getNextArgRequired();
1971 userId = UserHandle.parseUserArg(userStr);
1972 } else {
1973 if (packageName == null) {
1974 packageName = argument;
1975 } else {
1976 err.println("Error: Unsupported argument: " + argument);
1977 return -1;
1978 }
1979 }
1980 }
1981
1982 if (userId == UserHandle.USER_CURRENT) {
1983 userId = ActivityManager.getCurrentUser();
1984 }
1985
1986 shell.mInterface.resetAllModes(userId, packageName);
1987 pw.print("Reset all modes for: ");
1988 if (userId == UserHandle.USER_ALL) {
1989 pw.print("all users");
1990 } else {
1991 pw.print("user "); pw.print(userId);
1992 }
1993 pw.print(", ");
1994 if (packageName == null) {
1995 pw.println("all packages");
1996 } else {
1997 pw.print("package "); pw.println(packageName);
1998 }
1999 return 0;
2000 }
2001 case "write-settings": {
2002 shell.mInternal.mContext.enforcePermission(
2003 android.Manifest.permission.UPDATE_APP_OPS_STATS,
2004 Binder.getCallingPid(), Binder.getCallingUid(), null);
2005 long token = Binder.clearCallingIdentity();
2006 try {
2007 synchronized (shell.mInternal) {
2008 shell.mInternal.mHandler.removeCallbacks(shell.mInternal.mWriteRunner);
2009 }
2010 shell.mInternal.writeState();
2011 pw.println("Current settings written.");
2012 } finally {
2013 Binder.restoreCallingIdentity(token);
2014 }
2015 return 0;
2016 }
2017 case "read-settings": {
2018 shell.mInternal.mContext.enforcePermission(
2019 android.Manifest.permission.UPDATE_APP_OPS_STATS,
2020 Binder.getCallingPid(), Binder.getCallingUid(), null);
2021 long token = Binder.clearCallingIdentity();
2022 try {
2023 shell.mInternal.readState();
2024 pw.println("Last settings read.");
2025 } finally {
2026 Binder.restoreCallingIdentity(token);
2027 }
2028 return 0;
2029 }
2030 default:
2031 return shell.handleDefaultCommands(cmd);
2032 }
2033 } catch (RemoteException e) {
2034 pw.println("Remote exception: " + e);
2035 }
2036 return -1;
2037 }
2038
2039 private void dumpHelp(PrintWriter pw) {
2040 pw.println("AppOps service (appops) dump options:");
2041 pw.println(" none");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002042 }
2043
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002044 @Override
2045 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2046 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2047 != PackageManager.PERMISSION_GRANTED) {
2048 pw.println("Permission Denial: can't dump ApOps service from from pid="
2049 + Binder.getCallingPid()
2050 + ", uid=" + Binder.getCallingUid());
2051 return;
2052 }
2053
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002054 if (args != null) {
2055 for (int i=0; i<args.length; i++) {
2056 String arg = args[i];
2057 if ("-h".equals(arg)) {
2058 dumpHelp(pw);
2059 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07002060 } else if ("-a".equals(arg)) {
2061 // dump all data
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002062 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
2063 pw.println("Unknown option: " + arg);
2064 return;
2065 } else {
2066 pw.println("Unknown command: " + arg);
2067 return;
2068 }
2069 }
2070 }
2071
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002072 synchronized (this) {
2073 pw.println("Current AppOps Service state:");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002074 final long now = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002075 boolean needSep = false;
2076 if (mOpModeWatchers.size() > 0) {
2077 needSep = true;
2078 pw.println(" Op mode watchers:");
2079 for (int i=0; i<mOpModeWatchers.size(); i++) {
2080 pw.print(" Op "); pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
2081 pw.println(":");
2082 ArrayList<Callback> callbacks = mOpModeWatchers.valueAt(i);
2083 for (int j=0; j<callbacks.size(); j++) {
2084 pw.print(" #"); pw.print(j); pw.print(": ");
2085 pw.println(callbacks.get(j));
2086 }
2087 }
2088 }
2089 if (mPackageModeWatchers.size() > 0) {
2090 needSep = true;
2091 pw.println(" Package mode watchers:");
2092 for (int i=0; i<mPackageModeWatchers.size(); i++) {
2093 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
2094 pw.println(":");
2095 ArrayList<Callback> callbacks = mPackageModeWatchers.valueAt(i);
2096 for (int j=0; j<callbacks.size(); j++) {
2097 pw.print(" #"); pw.print(j); pw.print(": ");
2098 pw.println(callbacks.get(j));
2099 }
2100 }
2101 }
2102 if (mModeWatchers.size() > 0) {
2103 needSep = true;
2104 pw.println(" All mode watchers:");
2105 for (int i=0; i<mModeWatchers.size(); i++) {
2106 pw.print(" "); pw.print(mModeWatchers.keyAt(i));
2107 pw.print(" -> "); pw.println(mModeWatchers.valueAt(i));
2108 }
2109 }
2110 if (mClients.size() > 0) {
2111 needSep = true;
2112 pw.println(" Clients:");
2113 for (int i=0; i<mClients.size(); i++) {
2114 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
2115 ClientState cs = mClients.valueAt(i);
2116 pw.print(" "); pw.println(cs);
2117 if (cs.mStartedOps != null && cs.mStartedOps.size() > 0) {
2118 pw.println(" Started ops:");
2119 for (int j=0; j<cs.mStartedOps.size(); j++) {
2120 Op op = cs.mStartedOps.get(j);
2121 pw.print(" "); pw.print("uid="); pw.print(op.uid);
2122 pw.print(" pkg="); pw.print(op.packageName);
2123 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
2124 }
2125 }
2126 }
2127 }
John Spurlock1af30c72014-03-10 08:33:35 -04002128 if (mAudioRestrictions.size() > 0) {
2129 boolean printedHeader = false;
2130 for (int o=0; o<mAudioRestrictions.size(); o++) {
2131 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
2132 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
2133 for (int i=0; i<restrictions.size(); i++) {
2134 if (!printedHeader){
2135 pw.println(" Audio Restrictions:");
2136 printedHeader = true;
2137 needSep = true;
2138 }
John Spurlock7b414672014-07-18 13:02:39 -04002139 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04002140 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04002141 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04002142 Restriction r = restrictions.valueAt(i);
2143 pw.print(": mode="); pw.println(r.mode);
2144 if (!r.exceptionPackages.isEmpty()) {
2145 pw.println(" Exceptions:");
2146 for (int j=0; j<r.exceptionPackages.size(); j++) {
2147 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
2148 }
2149 }
2150 }
2151 }
2152 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002153 if (needSep) {
2154 pw.println();
2155 }
Svet Ganov2af57082015-07-30 08:44:20 -07002156 for (int i=0; i<mUidStates.size(); i++) {
2157 UidState uidState = mUidStates.valueAt(i);
2158
2159 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
2160
2161 SparseIntArray opModes = uidState.opModes;
2162 if (opModes != null) {
2163 final int opModeCount = opModes.size();
2164 for (int j = 0; j < opModeCount; j++) {
2165 final int code = opModes.keyAt(j);
2166 final int mode = opModes.valueAt(j);
2167 pw.print(" "); pw.print(AppOpsManager.opToName(code));
2168 pw.print(": mode="); pw.println(mode);
2169 }
2170 }
2171
2172 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
2173 if (pkgOps == null) {
2174 continue;
2175 }
2176
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002177 for (Ops ops : pkgOps.values()) {
2178 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
2179 for (int j=0; j<ops.size(); j++) {
2180 Op op = ops.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002181 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
2182 pw.print(": mode="); pw.print(op.mode);
2183 if (op.time != 0) {
2184 pw.print("; time="); TimeUtils.formatDuration(now-op.time, pw);
2185 pw.print(" ago");
2186 }
2187 if (op.rejectTime != 0) {
2188 pw.print("; rejectTime="); TimeUtils.formatDuration(now-op.rejectTime, pw);
2189 pw.print(" ago");
2190 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002191 if (op.duration == -1) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002192 pw.print(" (running)");
2193 } else if (op.duration != 0) {
2194 pw.print("; duration="); TimeUtils.formatDuration(op.duration, pw);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002195 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002196 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002197 }
2198 }
2199 }
2200 }
2201 }
John Spurlock1af30c72014-03-10 08:33:35 -04002202
2203 private static final class Restriction {
2204 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
2205 int mode;
2206 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
2207 }
Jason Monk62062992014-05-06 09:55:28 -04002208
2209 @Override
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002210 public void setUserRestrictions(Bundle restrictions, IBinder token, int userHandle) {
Jason Monk62062992014-05-06 09:55:28 -04002211 checkSystemUid("setUserRestrictions");
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002212 Preconditions.checkNotNull(restrictions);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002213 Preconditions.checkNotNull(token);
2214 final boolean[] opRestrictions = getOrCreateUserRestrictionsForToken(token, userHandle);
Jason Monk62062992014-05-06 09:55:28 -04002215 for (int i = 0; i < opRestrictions.length; ++i) {
2216 String restriction = AppOpsManager.opToRestriction(i);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002217 final boolean restricted = restriction != null
2218 && restrictions.getBoolean(restriction, false);
2219 setUserRestrictionNoCheck(i, restricted, token, userHandle);
2220 }
2221 }
2222
2223 @Override
Ruben Brunk29931bc2016-03-11 00:24:26 -08002224 public void setUserRestriction(int code, boolean restricted, IBinder token, int userHandle,
2225 String[] exceptionPackages) {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002226 if (Binder.getCallingPid() != Process.myPid()) {
2227 mContext.enforcePermission(Manifest.permission.MANAGE_APP_OPS_RESTRICTIONS,
2228 Binder.getCallingPid(), Binder.getCallingUid(), null);
2229 }
2230 if (userHandle != UserHandle.getCallingUserId()) {
2231 if (mContext.checkCallingOrSelfPermission(Manifest.permission
2232 .INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
2233 && mContext.checkCallingOrSelfPermission(Manifest.permission
2234 .INTERACT_ACROSS_USERS) != PackageManager.PERMISSION_GRANTED) {
2235 throw new SecurityException("Need INTERACT_ACROSS_USERS_FULL or"
2236 + " INTERACT_ACROSS_USERS to interact cross user ");
Jason Monk62062992014-05-06 09:55:28 -04002237 }
2238 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002239 verifyIncomingOp(code);
2240 Preconditions.checkNotNull(token);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002241 setUserRestrictionNoCheck(code, restricted, token, userHandle, exceptionPackages);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002242 }
2243
2244 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
2245 int userHandle) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002246 setUserRestrictionNoCheck(code, restricted, token, userHandle, /*exceptionPackages*/null);
2247 }
2248
2249 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
2250 int userHandle, String[] exceptionPackages) {
2251
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002252 final boolean[] opRestrictions = getOrCreateUserRestrictionsForToken(token, userHandle);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002253
2254 if (restricted) {
2255 final SparseArray<ArraySet<String>> opExceptions =
2256 getUserPackageExemptionsForToken(token, userHandle);
2257
Ruben Brunk29931bc2016-03-11 00:24:26 -08002258 ArraySet<String> exceptions = opExceptions.get(code);
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002259 if (exceptionPackages != null && exceptionPackages.length > 0) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002260 if (exceptions == null) {
2261 exceptions = new ArraySet<>(exceptionPackages.length);
2262 opExceptions.put(code, exceptions);
2263 } else {
2264 exceptions.clear();
2265 }
2266
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002267 for (String p : exceptionPackages) {
2268 exceptions.add(p);
2269 }
2270 } else {
2271 opExceptions.remove(code);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002272 }
2273 }
2274
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002275 if (opRestrictions[code] == restricted) {
2276 return;
2277 }
2278 opRestrictions[code] = restricted;
2279 if (!restricted) {
2280 pruneUserRestrictionsForToken(token, userHandle);
2281 }
2282
2283 final ArrayList<Callback> clonedCallbacks;
2284 synchronized (this) {
2285 ArrayList<Callback> callbacks = mOpModeWatchers.get(code);
2286 if (callbacks == null) {
2287 return;
2288 }
2289 clonedCallbacks = new ArrayList<>(callbacks);
2290 }
2291
2292 // There are components watching for mode changes such as window manager
2293 // and location manager which are in our process. The callbacks in these
2294 // components may require permissions our remote caller does not have.
2295 final long identity = Binder.clearCallingIdentity();
2296 try {
2297 final int callbackCount = clonedCallbacks.size();
2298 for (int i = 0; i < callbackCount; i++) {
2299 Callback callback = clonedCallbacks.get(i);
2300 try {
2301 callback.mCallback.opChanged(code, -1, null);
2302 } catch (RemoteException e) {
2303 Log.w(TAG, "Error dispatching op op change", e);
2304 }
2305 }
2306 } finally {
2307 Binder.restoreCallingIdentity(identity);
2308 }
Jason Monk62062992014-05-06 09:55:28 -04002309 }
2310
2311 @Override
2312 public void removeUser(int userHandle) throws RemoteException {
2313 checkSystemUid("removeUser");
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002314 final int tokenCount = mOpUserRestrictions.size();
2315 for (int i = tokenCount - 1; i >= 0; i--) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002316 SparseArray<Pair<boolean[], SparseArray<ArraySet<String>>>> opRestrictions =
2317 mOpUserRestrictions.valueAt(i);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002318 if (opRestrictions != null) {
2319 opRestrictions.remove(userHandle);
2320 if (opRestrictions.size() <= 0) {
2321 mOpUserRestrictions.removeAt(i);
2322 }
2323 }
2324 }
2325 }
2326
2327
2328 private void pruneUserRestrictionsForToken(IBinder token, int userHandle) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002329 SparseArray<Pair<boolean[], SparseArray<ArraySet<String>>>> perTokenRestrictions =
2330 mOpUserRestrictions.get(token);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002331 if (perTokenRestrictions != null) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002332 final Pair<boolean[], SparseArray<ArraySet<String>>> restrictions =
2333 perTokenRestrictions.get(userHandle);
2334
2335 if (restrictions != null) {
2336 final boolean[] opRestrictions = restrictions.first;
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002337 final SparseArray<ArraySet<String>> opExceptions = restrictions.second;
2338 boolean stillHasRestrictions = false;
Ruben Brunk29931bc2016-03-11 00:24:26 -08002339 if (opRestrictions != null) {
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002340 for (int i = 0; i < opRestrictions.length; i++) {
2341 boolean restriction = opRestrictions[i];
Ruben Brunk29931bc2016-03-11 00:24:26 -08002342 if (restriction) {
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002343 stillHasRestrictions = true;
2344 } else {
2345 opExceptions.remove(i);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002346 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002347 }
2348 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002349
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002350 if (stillHasRestrictions) {
2351 return;
2352 }
2353
Ruben Brunk29931bc2016-03-11 00:24:26 -08002354 // No restrictions set for this client
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002355 perTokenRestrictions.remove(userHandle);
2356 if (perTokenRestrictions.size() <= 0) {
2357 mOpUserRestrictions.remove(token);
2358 }
2359 }
2360 }
2361 }
2362
Ruben Brunk29931bc2016-03-11 00:24:26 -08002363 /**
2364 * Get or create the user restrictions array for a given client if it doesn't already exist.
2365 *
2366 * @param token the binder client creating the restriction.
2367 * @param userHandle the user handle to create a restriction for.
2368 *
2369 * @return the array of restriction states for each AppOps code.
2370 */
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002371 private boolean[] getOrCreateUserRestrictionsForToken(IBinder token, int userHandle) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002372 SparseArray<Pair<boolean[], SparseArray<ArraySet<String>>>> perTokenRestrictions =
2373 mOpUserRestrictions.get(token);
2374
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002375 if (perTokenRestrictions == null) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002376 perTokenRestrictions =
2377 new SparseArray<Pair<boolean[], SparseArray<ArraySet<String>>>>();
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002378 mOpUserRestrictions.put(token, perTokenRestrictions);
2379 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002380
2381 Pair<boolean[], SparseArray<ArraySet<String>>> restrictions =
2382 perTokenRestrictions.get(userHandle);
2383
2384 if (restrictions == null) {
2385 restrictions = new Pair<boolean[], SparseArray<ArraySet<String>>>(
2386 new boolean[AppOpsManager._NUM_OP], new SparseArray<ArraySet<String>>());
2387 perTokenRestrictions.put(userHandle, restrictions);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002388 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002389
2390 return restrictions.first;
2391 }
2392
2393 /**
2394 * Get the per-package exemptions for each AppOps code for a given client and userHandle.
2395 *
2396 * @param token the binder client to get the exemptions for.
2397 * @param userHandle the user handle to get the exemptions for.
2398 *
2399 * @return a mapping from the AppOps code to a set of packages exempt for that code.
2400 */
2401 private SparseArray<ArraySet<String>> getUserPackageExemptionsForToken(IBinder token,
2402 int userHandle) {
2403 SparseArray<Pair<boolean[], SparseArray<ArraySet<String>>>> perTokenRestrictions =
2404 mOpUserRestrictions.get(token);
2405
2406 if (perTokenRestrictions == null) {
2407 return null; // Don't create user restrictions accidentally
2408 }
2409
2410 Pair<boolean[], SparseArray<ArraySet<String>>> restrictions =
2411 perTokenRestrictions.get(userHandle);
2412
2413 if (restrictions == null) {
2414 return null; // Don't create user restrictions accidentally
2415 }
2416
2417 return restrictions.second;
Jason Monk62062992014-05-06 09:55:28 -04002418 }
2419
2420 private void checkSystemUid(String function) {
2421 int uid = Binder.getCallingUid();
2422 if (uid != Process.SYSTEM_UID) {
2423 throw new SecurityException(function + " must by called by the system");
2424 }
2425 }
2426
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002427 private static String resolvePackageName(int uid, String packageName) {
2428 if (uid == 0) {
2429 return "root";
2430 } else if (uid == Process.SHELL_UID) {
2431 return "com.android.shell";
2432 } else if (uid == Process.SYSTEM_UID && packageName == null) {
2433 return "android";
2434 }
2435 return packageName;
2436 }
2437
Svet Ganov2af57082015-07-30 08:44:20 -07002438 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07002439 String[] packageNames = null;
Svet Ganov2af57082015-07-30 08:44:20 -07002440 try {
riddle_hsu40b300f2015-11-23 13:22:03 +08002441 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -07002442 } catch (RemoteException e) {
2443 /* ignore - local call */
2444 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07002445 if (packageNames == null) {
2446 return EmptyArray.STRING;
2447 }
2448 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07002449 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002450}