blob: 57ba1b9ff69b5b273d865c721f41929d64a9e6ad [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);
449 synchronized (this) {
Ian Pedowitz9888e002016-03-22 16:13:48 +0000450 Ops pkgOps = getOpsLocked(uid, packageName, false);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800451 if (pkgOps == null) {
452 return null;
453 }
454 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
455 if (resOps == null) {
456 return null;
457 }
458 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
459 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700460 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800461 res.add(resPackage);
462 return res;
463 }
464 }
465
Dianne Hackborn607b4142013-08-02 18:10:10 -0700466 private void pruneOp(Op op, int uid, String packageName) {
467 if (op.time == 0 && op.rejectTime == 0) {
Ian Pedowitz9888e002016-03-22 16:13:48 +0000468 Ops ops = getOpsLocked(uid, packageName, false);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700469 if (ops != null) {
470 ops.remove(op.op);
471 if (ops.size() <= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -0700472 UidState uidState = ops.uidState;
473 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700474 if (pkgOps != null) {
475 pkgOps.remove(ops.packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700476 if (pkgOps.isEmpty()) {
477 uidState.pkgOps = null;
478 }
479 if (uidState.isDefault()) {
480 mUidStates.remove(uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700481 }
482 }
483 }
484 }
485 }
486 }
487
Dianne Hackborn72e39832013-01-18 18:36:09 -0800488 @Override
Svet Ganov2af57082015-07-30 08:44:20 -0700489 public void setUidMode(int code, int uid, int mode) {
490 if (Binder.getCallingPid() != Process.myPid()) {
491 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
492 Binder.getCallingPid(), Binder.getCallingUid(), null);
493 }
494 verifyIncomingOp(code);
495 code = AppOpsManager.opToSwitch(code);
496
497 synchronized (this) {
498 final int defaultMode = AppOpsManager.opToDefaultMode(code);
499
500 UidState uidState = getUidStateLocked(uid, false);
501 if (uidState == null) {
502 if (mode == defaultMode) {
503 return;
504 }
505 uidState = new UidState(uid);
506 uidState.opModes = new SparseIntArray();
507 uidState.opModes.put(code, mode);
508 mUidStates.put(uid, uidState);
509 scheduleWriteLocked();
510 } else if (uidState.opModes == null) {
511 if (mode != defaultMode) {
512 uidState.opModes = new SparseIntArray();
513 uidState.opModes.put(code, mode);
514 scheduleWriteLocked();
515 }
516 } else {
517 if (uidState.opModes.get(code) == mode) {
518 return;
519 }
520 if (mode == defaultMode) {
521 uidState.opModes.delete(code);
522 if (uidState.opModes.size() <= 0) {
523 uidState.opModes = null;
524 }
525 } else {
526 uidState.opModes.put(code, mode);
527 }
528 scheduleWriteLocked();
529 }
530 }
531
Svetoslav215b44a2015-08-04 19:03:40 -0700532 String[] uidPackageNames = getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -0700533 ArrayMap<Callback, ArraySet<String>> callbackSpecs = null;
534
riddle_hsu40b300f2015-11-23 13:22:03 +0800535 synchronized (this) {
536 ArrayList<Callback> callbacks = mOpModeWatchers.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -0700537 if (callbacks != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700538 final int callbackCount = callbacks.size();
539 for (int i = 0; i < callbackCount; i++) {
540 Callback callback = callbacks.get(i);
riddle_hsu40b300f2015-11-23 13:22:03 +0800541 ArraySet<String> changedPackages = new ArraySet<>();
542 Collections.addAll(changedPackages, uidPackageNames);
543 callbackSpecs = new ArrayMap<>();
544 callbackSpecs.put(callback, changedPackages);
545 }
546 }
547
548 for (String uidPackageName : uidPackageNames) {
549 callbacks = mPackageModeWatchers.get(uidPackageName);
550 if (callbacks != null) {
551 if (callbackSpecs == null) {
552 callbackSpecs = new ArrayMap<>();
Svet Ganov2af57082015-07-30 08:44:20 -0700553 }
riddle_hsu40b300f2015-11-23 13:22:03 +0800554 final int callbackCount = callbacks.size();
555 for (int i = 0; i < callbackCount; i++) {
556 Callback callback = callbacks.get(i);
557 ArraySet<String> changedPackages = callbackSpecs.get(callback);
558 if (changedPackages == null) {
559 changedPackages = new ArraySet<>();
560 callbackSpecs.put(callback, changedPackages);
561 }
562 changedPackages.add(uidPackageName);
563 }
Svet Ganov2af57082015-07-30 08:44:20 -0700564 }
565 }
566 }
567
568 if (callbackSpecs == null) {
569 return;
570 }
571
572 // There are components watching for mode changes such as window manager
573 // and location manager which are in our process. The callbacks in these
574 // components may require permissions our remote caller does not have.
575 final long identity = Binder.clearCallingIdentity();
576 try {
577 for (int i = 0; i < callbackSpecs.size(); i++) {
578 Callback callback = callbackSpecs.keyAt(i);
579 ArraySet<String> reportedPackageNames = callbackSpecs.valueAt(i);
580 try {
581 if (reportedPackageNames == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700582 callback.mCallback.opChanged(code, uid, null);
Svet Ganov2af57082015-07-30 08:44:20 -0700583 } else {
584 final int reportedPackageCount = reportedPackageNames.size();
585 for (int j = 0; j < reportedPackageCount; j++) {
586 String reportedPackageName = reportedPackageNames.valueAt(j);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700587 callback.mCallback.opChanged(code, uid, reportedPackageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700588 }
589 }
590 } catch (RemoteException e) {
591 Log.w(TAG, "Error dispatching op op change", e);
592 }
593 }
594 } finally {
595 Binder.restoreCallingIdentity(identity);
596 }
597 }
598
599 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800600 public void setMode(int code, int uid, String packageName, int mode) {
Dianne Hackbornb64afe12014-07-22 16:29:04 -0700601 if (Binder.getCallingPid() != Process.myPid()) {
602 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
603 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborn133b9df2014-07-01 13:06:10 -0700604 }
Dianne Hackborn961321f2013-02-05 17:22:41 -0800605 verifyIncomingOp(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800606 ArrayList<Callback> repCbs = null;
607 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800608 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700609 UidState uidState = getUidStateLocked(uid, false);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800610 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800611 if (op != null) {
612 if (op.mode != mode) {
613 op.mode = mode;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800614 ArrayList<Callback> cbs = mOpModeWatchers.get(code);
615 if (cbs != null) {
616 if (repCbs == null) {
617 repCbs = new ArrayList<Callback>();
618 }
619 repCbs.addAll(cbs);
620 }
621 cbs = mPackageModeWatchers.get(packageName);
622 if (cbs != null) {
623 if (repCbs == null) {
624 repCbs = new ArrayList<Callback>();
625 }
626 repCbs.addAll(cbs);
627 }
David Braunf5d83192013-09-16 13:43:51 -0700628 if (mode == AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800629 // If going into the default mode, prune this op
630 // if there is nothing else interesting in it.
Dianne Hackborn607b4142013-08-02 18:10:10 -0700631 pruneOp(op, uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800632 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800633 scheduleFastWriteLocked();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800634 }
635 }
636 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800637 if (repCbs != null) {
Svet Ganov38536112015-05-19 12:45:52 -0700638 // There are components watching for mode changes such as window manager
639 // and location manager which are in our process. The callbacks in these
640 // components may require permissions our remote caller does not have.
641 final long identity = Binder.clearCallingIdentity();
642 try {
643 for (int i = 0; i < repCbs.size(); i++) {
644 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700645 repCbs.get(i).mCallback.opChanged(code, uid, packageName);
Svet Ganov38536112015-05-19 12:45:52 -0700646 } catch (RemoteException e) {
647 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800648 }
Svet Ganov38536112015-05-19 12:45:52 -0700649 } finally {
650 Binder.restoreCallingIdentity(identity);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800651 }
652 }
653 }
654
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700655 private static HashMap<Callback, ArrayList<ChangeRec>> addCallbacks(
656 HashMap<Callback, ArrayList<ChangeRec>> callbacks,
657 int op, int uid, String packageName, ArrayList<Callback> cbs) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700658 if (cbs == null) {
659 return callbacks;
660 }
661 if (callbacks == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700662 callbacks = new HashMap<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700663 }
Svet Ganov2af57082015-07-30 08:44:20 -0700664 boolean duplicate = false;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700665 for (int i=0; i<cbs.size(); i++) {
666 Callback cb = cbs.get(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700667 ArrayList<ChangeRec> reports = callbacks.get(cb);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700668 if (reports == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700669 reports = new ArrayList<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700670 callbacks.put(cb, reports);
Svet Ganov2af57082015-07-30 08:44:20 -0700671 } else {
672 final int reportCount = reports.size();
673 for (int j = 0; j < reportCount; j++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700674 ChangeRec report = reports.get(j);
675 if (report.op == op && report.pkg.equals(packageName)) {
Svet Ganov2af57082015-07-30 08:44:20 -0700676 duplicate = true;
677 break;
678 }
679 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700680 }
Svet Ganov2af57082015-07-30 08:44:20 -0700681 if (!duplicate) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700682 reports.add(new ChangeRec(op, uid, packageName));
Svet Ganov2af57082015-07-30 08:44:20 -0700683 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700684 }
685 return callbacks;
686 }
687
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700688 static final class ChangeRec {
689 final int op;
690 final int uid;
691 final String pkg;
692
693 ChangeRec(int _op, int _uid, String _pkg) {
694 op = _op;
695 uid = _uid;
696 pkg = _pkg;
697 }
698 }
699
Dianne Hackborn607b4142013-08-02 18:10:10 -0700700 @Override
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800701 public void resetAllModes(int reqUserId, String reqPackageName) {
702 final int callingPid = Binder.getCallingPid();
703 final int callingUid = Binder.getCallingUid();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700704 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800705 callingPid, callingUid, null);
706 reqUserId = ActivityManager.handleIncomingUser(callingPid, callingUid, reqUserId,
707 true, true, "resetAllModes", null);
Svet Ganov2af57082015-07-30 08:44:20 -0700708
709 int reqUid = -1;
710 if (reqPackageName != null) {
711 try {
712 reqUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -0700713 reqPackageName, PackageManager.MATCH_UNINSTALLED_PACKAGES, reqUserId);
Svet Ganov2af57082015-07-30 08:44:20 -0700714 } catch (RemoteException e) {
715 /* ignore - local call */
716 }
717 }
718
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700719 HashMap<Callback, ArrayList<ChangeRec>> callbacks = null;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700720 synchronized (this) {
721 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700722 for (int i = mUidStates.size() - 1; i >= 0; i--) {
723 UidState uidState = mUidStates.valueAt(i);
724
725 SparseIntArray opModes = uidState.opModes;
726 if (opModes != null && (uidState.uid == reqUid || reqUid == -1)) {
727 final int uidOpCount = opModes.size();
728 for (int j = uidOpCount - 1; j >= 0; j--) {
729 final int code = opModes.keyAt(j);
730 if (AppOpsManager.opAllowsReset(code)) {
731 opModes.removeAt(j);
732 if (opModes.size() <= 0) {
733 uidState.opModes = null;
734 }
735 for (String packageName : getPackagesForUid(uidState.uid)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700736 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700737 mOpModeWatchers.get(code));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700738 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700739 mPackageModeWatchers.get(packageName));
740 }
741 }
742 }
743 }
744
745 if (uidState.pkgOps == null) {
746 continue;
747 }
748
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800749 if (reqUserId != UserHandle.USER_ALL
Svet Ganov2af57082015-07-30 08:44:20 -0700750 && reqUserId != UserHandle.getUserId(uidState.uid)) {
Alexandra Gherghinad6a98972014-08-04 17:05:34 +0100751 // Skip any ops for a different user
752 continue;
753 }
Svet Ganov2af57082015-07-30 08:44:20 -0700754
755 Map<String, Ops> packages = uidState.pkgOps;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700756 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
757 while (it.hasNext()) {
758 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700759 String packageName = ent.getKey();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800760 if (reqPackageName != null && !reqPackageName.equals(packageName)) {
761 // Skip any ops for a different package
762 continue;
763 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700764 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700765 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700766 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -0700767 if (AppOpsManager.opAllowsReset(curOp.op)
768 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -0700769 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700770 changed = true;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700771 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -0700772 mOpModeWatchers.get(curOp.op));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700773 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -0700774 mPackageModeWatchers.get(packageName));
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700775 if (curOp.time == 0 && curOp.rejectTime == 0) {
776 pkgOps.removeAt(j);
777 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700778 }
779 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700780 if (pkgOps.size() == 0) {
781 it.remove();
782 }
783 }
Svet Ganov2af57082015-07-30 08:44:20 -0700784 if (uidState.isDefault()) {
785 mUidStates.remove(uidState.uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700786 }
787 }
Svet Ganov2af57082015-07-30 08:44:20 -0700788
Dianne Hackborn607b4142013-08-02 18:10:10 -0700789 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800790 scheduleFastWriteLocked();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700791 }
792 }
793 if (callbacks != null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700794 for (Map.Entry<Callback, ArrayList<ChangeRec>> ent : callbacks.entrySet()) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700795 Callback cb = ent.getKey();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700796 ArrayList<ChangeRec> reports = ent.getValue();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700797 for (int i=0; i<reports.size(); i++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700798 ChangeRec rep = reports.get(i);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700799 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700800 cb.mCallback.opChanged(rep.op, rep.uid, rep.pkg);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700801 } catch (RemoteException e) {
802 }
803 }
804 }
805 }
806 }
807
Dianne Hackbornc2293022013-02-06 23:14:49 -0800808 @Override
809 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -0800810 if (callback == null) {
811 return;
812 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800813 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700814 op = (op != AppOpsManager.OP_NONE) ? AppOpsManager.opToSwitch(op) : op;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800815 Callback cb = mModeWatchers.get(callback.asBinder());
816 if (cb == null) {
817 cb = new Callback(callback);
818 mModeWatchers.put(callback.asBinder(), cb);
819 }
820 if (op != AppOpsManager.OP_NONE) {
821 ArrayList<Callback> cbs = mOpModeWatchers.get(op);
822 if (cbs == null) {
823 cbs = new ArrayList<Callback>();
824 mOpModeWatchers.put(op, cbs);
825 }
826 cbs.add(cb);
827 }
828 if (packageName != null) {
829 ArrayList<Callback> cbs = mPackageModeWatchers.get(packageName);
830 if (cbs == null) {
831 cbs = new ArrayList<Callback>();
832 mPackageModeWatchers.put(packageName, cbs);
833 }
834 cbs.add(cb);
835 }
836 }
837 }
838
839 @Override
840 public void stopWatchingMode(IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -0800841 if (callback == null) {
842 return;
843 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800844 synchronized (this) {
845 Callback cb = mModeWatchers.remove(callback.asBinder());
846 if (cb != null) {
847 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700848 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800849 ArrayList<Callback> cbs = mOpModeWatchers.valueAt(i);
850 cbs.remove(cb);
851 if (cbs.size() <= 0) {
852 mOpModeWatchers.removeAt(i);
853 }
854 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700855 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
856 ArrayList<Callback> cbs = mPackageModeWatchers.valueAt(i);
857 cbs.remove(cb);
858 if (cbs.size() <= 0) {
859 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800860 }
861 }
862 }
863 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800864 }
865
866 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700867 public IBinder getToken(IBinder clientToken) {
868 synchronized (this) {
869 ClientState cs = mClients.get(clientToken);
870 if (cs == null) {
871 cs = new ClientState(clientToken);
872 mClients.put(clientToken, cs);
873 }
874 return cs;
875 }
876 }
877
878 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800879 public int checkOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800880 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800881 verifyIncomingOp(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800882 synchronized (this) {
Ian Pedowitz9888e002016-03-22 16:13:48 +0000883 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -0400884 return AppOpsManager.MODE_IGNORED;
885 }
Svet Ganov2af57082015-07-30 08:44:20 -0700886 code = AppOpsManager.opToSwitch(code);
887 UidState uidState = getUidStateLocked(uid, false);
888 if (uidState != null && uidState.opModes != null) {
889 final int uidMode = uidState.opModes.get(code);
890 if (uidMode != AppOpsManager.MODE_ALLOWED) {
891 return uidMode;
892 }
893 }
Ian Pedowitz9888e002016-03-22 16:13:48 +0000894 Op op = getOpLocked(code, uid, packageName, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800895 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -0700896 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800897 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800898 return op.mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800899 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800900 }
901
902 @Override
John Spurlock7b414672014-07-18 13:02:39 -0400903 public int checkAudioOperation(int code, int usage, int uid, String packageName) {
Andrei Stingaceanu355b2322016-02-12 16:43:51 +0000904 if (isPackageSuspendedForUser(packageName, uid)) {
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000905 Log.i(TAG, "Audio disabled for suspended package=" + packageName + " for uid=" + uid);
906 return AppOpsManager.MODE_IGNORED;
907 }
908
John Spurlock1af30c72014-03-10 08:33:35 -0400909 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -0400910 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -0400911 if (mode != AppOpsManager.MODE_ALLOWED) {
912 return mode;
913 }
914 }
915 return checkOperation(code, uid, packageName);
916 }
917
Andrei Stingaceanu355b2322016-02-12 16:43:51 +0000918 private boolean isPackageSuspendedForUser(String pkg, int uid) {
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000919 try {
Andrei Stingaceanu355b2322016-02-12 16:43:51 +0000920 return AppGlobals.getPackageManager().isPackageSuspendedForUser(
921 pkg, UserHandle.getUserId(uid));
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000922 } catch (RemoteException re) {
923 throw new SecurityException("Could not talk to package manager service");
924 }
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000925 }
926
John Spurlock7b414672014-07-18 13:02:39 -0400927 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
928 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
929 if (usageRestrictions != null) {
930 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -0400931 if (r != null && !r.exceptionPackages.contains(packageName)) {
932 return r.mode;
933 }
934 }
935 return AppOpsManager.MODE_ALLOWED;
936 }
937
938 @Override
John Spurlock7b414672014-07-18 13:02:39 -0400939 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -0400940 String[] exceptionPackages) {
941 verifyIncomingUid(uid);
942 verifyIncomingOp(code);
943 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -0400944 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
945 if (usageRestrictions == null) {
946 usageRestrictions = new SparseArray<Restriction>();
947 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -0400948 }
John Spurlock7b414672014-07-18 13:02:39 -0400949 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -0400950 if (mode != AppOpsManager.MODE_ALLOWED) {
951 final Restriction r = new Restriction();
952 r.mode = mode;
953 if (exceptionPackages != null) {
954 final int N = exceptionPackages.length;
955 r.exceptionPackages = new ArraySet<String>(N);
956 for (int i = 0; i < N; i++) {
957 final String pkg = exceptionPackages[i];
958 if (pkg != null) {
959 r.exceptionPackages.add(pkg.trim());
960 }
961 }
962 }
John Spurlock7b414672014-07-18 13:02:39 -0400963 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -0400964 }
965 }
966 }
967
968 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700969 public int checkPackage(int uid, String packageName) {
970 synchronized (this) {
Dianne Hackborn0fcef842014-09-12 15:38:33 -0700971 if (getOpsRawLocked(uid, packageName, true) != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700972 return AppOpsManager.MODE_ALLOWED;
973 } else {
974 return AppOpsManager.MODE_ERRORED;
975 }
976 }
977 }
978
979 @Override
Svet Ganov99b60432015-06-27 13:15:22 -0700980 public int noteProxyOperation(int code, String proxyPackageName,
981 int proxiedUid, String proxiedPackageName) {
982 verifyIncomingOp(code);
Ian Pedowitz9888e002016-03-22 16:13:48 +0000983 final int proxyMode = noteOperationUnchecked(code, Binder.getCallingUid(),
984 proxyPackageName, -1, null);
Svet Ganov99b60432015-06-27 13:15:22 -0700985 if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
986 return proxyMode;
987 }
Ian Pedowitz9888e002016-03-22 16:13:48 +0000988 return noteOperationUnchecked(code, proxiedUid, proxiedPackageName,
989 Binder.getCallingUid(), proxyPackageName);
Svet Ganov99b60432015-06-27 13:15:22 -0700990 }
991
992 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800993 public int noteOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800994 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800995 verifyIncomingOp(code);
Ian Pedowitz9888e002016-03-22 16:13:48 +0000996 return noteOperationUnchecked(code, uid, packageName, 0, null);
Svet Ganov99b60432015-06-27 13:15:22 -0700997 }
998
999 private int noteOperationUnchecked(int code, int uid, String packageName,
1000 int proxyUid, String proxyPackageName) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001001 synchronized (this) {
Ian Pedowitz9888e002016-03-22 16:13:48 +00001002 Ops ops = getOpsLocked(uid, packageName, true);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001003 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001004 if (DEBUG) Log.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
1005 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001006 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001007 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001008 Op op = getOpLocked(ops, code, true);
Jason Monk1c7c3192014-06-26 12:52:18 -04001009 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001010 return AppOpsManager.MODE_IGNORED;
1011 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001012 if (op.duration == -1) {
1013 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
1014 + " code " + code + " time=" + op.time + " duration=" + op.duration);
1015 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001016 op.duration = 0;
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001017 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001018 UidState uidState = ops.uidState;
1019 if (uidState.opModes != null) {
1020 final int uidMode = uidState.opModes.get(switchCode);
1021 if (uidMode != AppOpsManager.MODE_ALLOWED) {
1022 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1023 + switchCode + " (" + code + ") uid " + uid + " package "
1024 + packageName);
1025 op.rejectTime = System.currentTimeMillis();
1026 return uidMode;
1027 }
1028 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001029 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
1030 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
1031 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1032 + switchCode + " (" + code + ") uid " + uid + " package " + packageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001033 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001034 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001035 }
1036 if (DEBUG) Log.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
1037 + " package " + packageName);
1038 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001039 op.rejectTime = 0;
Svet Ganov99b60432015-06-27 13:15:22 -07001040 op.proxyUid = proxyUid;
1041 op.proxyPackageName = proxyPackageName;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001042 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001043 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001044 }
1045
1046 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001047 public int startOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001048 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001049 verifyIncomingOp(code);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001050 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001051 synchronized (this) {
Ian Pedowitz9888e002016-03-22 16:13:48 +00001052 Ops ops = getOpsLocked(uid, packageName, true);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001053 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001054 if (DEBUG) Log.d(TAG, "startOperation: no op for code " + code + " uid " + uid
Ian Pedowitz9888e002016-03-22 16:13:48 +00001055 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001056 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001057 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001058 Op op = getOpLocked(ops, code, true);
Ian Pedowitz9888e002016-03-22 16:13:48 +00001059 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001060 return AppOpsManager.MODE_IGNORED;
1061 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001062 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001063 UidState uidState = ops.uidState;
1064 if (uidState.opModes != null) {
1065 final int uidMode = uidState.opModes.get(switchCode);
1066 if (uidMode != AppOpsManager.MODE_ALLOWED) {
1067 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1068 + switchCode + " (" + code + ") uid " + uid + " package "
Ian Pedowitz9888e002016-03-22 16:13:48 +00001069 + packageName);
Svet Ganov2af57082015-07-30 08:44:20 -07001070 op.rejectTime = System.currentTimeMillis();
1071 return uidMode;
1072 }
1073 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001074 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
1075 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
1076 if (DEBUG) Log.d(TAG, "startOperation: reject #" + op.mode + " for code "
Ian Pedowitz9888e002016-03-22 16:13:48 +00001077 + switchCode + " (" + code + ") uid " + uid + " package " + packageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001078 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001079 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001080 }
1081 if (DEBUG) Log.d(TAG, "startOperation: allowing code " + code + " uid " + uid
Ian Pedowitz9888e002016-03-22 16:13:48 +00001082 + " package " + packageName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001083 if (op.nesting == 0) {
1084 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001085 op.rejectTime = 0;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001086 op.duration = -1;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001087 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001088 op.nesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001089 if (client.mStartedOps != null) {
1090 client.mStartedOps.add(op);
1091 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001092 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001093 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001094 }
1095
1096 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001097 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001098 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001099 verifyIncomingOp(code);
Ian Pedowitz9888e002016-03-22 16:13:48 +00001100 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001101 synchronized (this) {
Ian Pedowitz9888e002016-03-22 16:13:48 +00001102 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001103 if (op == null) {
1104 return;
1105 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001106 if (client.mStartedOps != null) {
1107 if (!client.mStartedOps.remove(op)) {
1108 throw new IllegalStateException("Operation not started: uid" + op.uid
1109 + " pkg=" + op.packageName + " op=" + op.op);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001110 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001111 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001112 finishOperationLocked(op);
1113 }
1114 }
1115
Svet Ganovb9d71a62015-04-30 10:38:13 -07001116 @Override
1117 public int permissionToOpCode(String permission) {
1118 return AppOpsManager.permissionToOpCode(permission);
1119 }
1120
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001121 void finishOperationLocked(Op op) {
1122 if (op.nesting <= 1) {
1123 if (op.nesting == 1) {
1124 op.duration = (int)(System.currentTimeMillis() - op.time);
1125 op.time += op.duration;
1126 } else {
1127 Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
1128 + op.packageName + " code " + op.op + " time=" + op.time
1129 + " duration=" + op.duration + " nesting=" + op.nesting);
1130 }
1131 op.nesting = 0;
1132 } else {
1133 op.nesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001134 }
1135 }
1136
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001137 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001138 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001139 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001140 }
1141 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001142 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001143 }
1144 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
1145 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001146 }
1147
Dianne Hackborn961321f2013-02-05 17:22:41 -08001148 private void verifyIncomingOp(int op) {
1149 if (op >= 0 && op < AppOpsManager._NUM_OP) {
1150 return;
1151 }
1152 throw new IllegalArgumentException("Bad operation #" + op);
1153 }
1154
Svet Ganov2af57082015-07-30 08:44:20 -07001155 private UidState getUidStateLocked(int uid, boolean edit) {
1156 UidState uidState = mUidStates.get(uid);
1157 if (uidState == null) {
1158 if (!edit) {
1159 return null;
1160 }
1161 uidState = new UidState(uid);
1162 mUidStates.put(uid, uidState);
1163 }
1164 return uidState;
1165 }
1166
Ian Pedowitz9888e002016-03-22 16:13:48 +00001167 private Ops getOpsLocked(int uid, String packageName, boolean edit) {
1168 if (uid == 0) {
1169 packageName = "root";
1170 } else if (uid == Process.SHELL_UID) {
1171 packageName = "com.android.shell";
1172 }
1173 return getOpsRawLocked(uid, packageName, edit);
1174 }
1175
Dianne Hackborn0fcef842014-09-12 15:38:33 -07001176 private Ops getOpsRawLocked(int uid, String packageName, boolean edit) {
Svet Ganov2af57082015-07-30 08:44:20 -07001177 UidState uidState = getUidStateLocked(uid, edit);
1178 if (uidState == null) {
1179 return null;
1180 }
1181
1182 if (uidState.pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001183 if (!edit) {
1184 return null;
1185 }
Svet Ganov2af57082015-07-30 08:44:20 -07001186 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001187 }
Svet Ganov2af57082015-07-30 08:44:20 -07001188
1189 Ops ops = uidState.pkgOps.get(packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001190 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001191 if (!edit) {
1192 return null;
1193 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001194 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001195 // This is the first time we have seen this package name under this uid,
1196 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -08001197 if (uid != 0) {
1198 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001199 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001200 int pkgUid = -1;
1201 try {
Jason Monk1c7c3192014-06-26 12:52:18 -04001202 ApplicationInfo appInfo = ActivityThread.getPackageManager()
Jeff Sharkeycd654482016-01-08 17:42:11 -07001203 .getApplicationInfo(packageName,
1204 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1205 UserHandle.getUserId(uid));
Jason Monk1c7c3192014-06-26 12:52:18 -04001206 if (appInfo != null) {
1207 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001208 isPrivileged = (appInfo.privateFlags
1209 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001210 } else {
1211 if ("media".equals(packageName)) {
1212 pkgUid = Process.MEDIA_UID;
1213 isPrivileged = false;
Andy Hunged0ea402015-10-30 14:11:46 -07001214 } else if ("audioserver".equals(packageName)) {
1215 pkgUid = Process.AUDIOSERVER_UID;
1216 isPrivileged = false;
Chien-Yu Chen75cade02016-01-11 10:56:21 -08001217 } else if ("cameraserver".equals(packageName)) {
1218 pkgUid = Process.CAMERASERVER_UID;
1219 isPrivileged = false;
Jason Monk1c7c3192014-06-26 12:52:18 -04001220 }
Dianne Hackborn713df152013-05-17 11:27:57 -07001221 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001222 } catch (RemoteException e) {
1223 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001224 }
1225 if (pkgUid != uid) {
1226 // Oops! The package name is not valid for the uid they are calling
1227 // under. Abort.
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001228 RuntimeException ex = new RuntimeException("here");
1229 ex.fillInStackTrace();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001230 Slog.w(TAG, "Bad call: specified package " + packageName
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001231 + " under uid " + uid + " but it is really " + pkgUid, ex);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001232 return null;
1233 }
1234 } finally {
1235 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001236 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001237 }
Svet Ganov2af57082015-07-30 08:44:20 -07001238 ops = new Ops(packageName, uidState, isPrivileged);
1239 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001240 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08001241 return ops;
1242 }
1243
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001244 private void scheduleWriteLocked() {
1245 if (!mWriteScheduled) {
1246 mWriteScheduled = true;
1247 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
1248 }
1249 }
1250
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001251 private void scheduleFastWriteLocked() {
1252 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001253 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001254 mFastWriteScheduled = true;
1255 mHandler.removeCallbacks(mWriteRunner);
1256 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001257 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001258 }
1259
Dianne Hackborn72e39832013-01-18 18:36:09 -08001260 private Op getOpLocked(int code, int uid, String packageName, boolean edit) {
Ian Pedowitz9888e002016-03-22 16:13:48 +00001261 Ops ops = getOpsLocked(uid, packageName, edit);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001262 if (ops == null) {
1263 return null;
1264 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001265 return getOpLocked(ops, code, edit);
1266 }
1267
1268 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001269 Op op = ops.get(code);
1270 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001271 if (!edit) {
1272 return null;
1273 }
Svet Ganov2af57082015-07-30 08:44:20 -07001274 op = new Op(ops.uidState.uid, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001275 ops.put(code, op);
1276 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001277 if (edit) {
1278 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001279 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001280 return op;
1281 }
1282
Jason Monk1c7c3192014-06-26 12:52:18 -04001283 private boolean isOpRestricted(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04001284 int userHandle = UserHandle.getUserId(uid);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001285 final int restrictionSetCount = mOpUserRestrictions.size();
Ruben Brunk29931bc2016-03-11 00:24:26 -08001286
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001287 for (int i = 0; i < restrictionSetCount; i++) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08001288 // For each client, check that the given op is not restricted, or that the given
1289 // package is exempt from the restriction.
1290
1291 SparseArray<Pair<boolean[],SparseArray<ArraySet<String>>>> perUserRestrictions =
1292 mOpUserRestrictions.valueAt(i);
1293
1294 Pair<boolean[],SparseArray<ArraySet<String>>> restrictions =
1295 perUserRestrictions.get(userHandle);
1296 if (restrictions == null) {
1297 continue; // No restrictions set by this client
1298 }
1299
1300 boolean[] opRestrictions = restrictions.first;
1301 SparseArray<ArraySet<String>> opExceptions = restrictions.second;
1302
1303 if (opRestrictions == null) {
1304 continue; // No restrictions set by this client
1305 }
1306
1307 if (opRestrictions[code]) {
Ruben Brunk32f0fa42016-03-11 19:07:07 -08001308
1309 if (opExceptions != null) {
1310 ArraySet<String> ex = opExceptions.get(code);
1311 if (ex != null && ex.contains(packageName)) {
1312 continue; // AppOps code is restricted, but this package is exempt
1313 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08001314 }
1315
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001316 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08001317 // If we are the system, bypass user restrictions for certain codes
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001318 synchronized (this) {
Ian Pedowitz9888e002016-03-22 16:13:48 +00001319 Ops ops = getOpsLocked(uid, packageName, true);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001320 if ((ops != null) && ops.isPrivileged) {
1321 return false;
1322 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001323 }
1324 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08001325
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001326 return true;
Jason Monk1c7c3192014-06-26 12:52:18 -04001327 }
Jason Monk62062992014-05-06 09:55:28 -04001328 }
1329 return false;
1330 }
1331
Dianne Hackborn35654b62013-01-14 17:38:02 -08001332 void readState() {
1333 synchronized (mFile) {
1334 synchronized (this) {
1335 FileInputStream stream;
1336 try {
1337 stream = mFile.openRead();
1338 } catch (FileNotFoundException e) {
1339 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
1340 return;
1341 }
1342 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001343 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001344 try {
1345 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001346 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001347 int type;
1348 while ((type = parser.next()) != XmlPullParser.START_TAG
1349 && type != XmlPullParser.END_DOCUMENT) {
1350 ;
1351 }
1352
1353 if (type != XmlPullParser.START_TAG) {
1354 throw new IllegalStateException("no start tag found");
1355 }
1356
1357 int outerDepth = parser.getDepth();
1358 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1359 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1360 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1361 continue;
1362 }
1363
1364 String tagName = parser.getName();
1365 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001366 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07001367 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07001368 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001369 } else {
1370 Slog.w(TAG, "Unknown element under <app-ops>: "
1371 + parser.getName());
1372 XmlUtils.skipCurrentTag(parser);
1373 }
1374 }
1375 success = true;
1376 } catch (IllegalStateException e) {
1377 Slog.w(TAG, "Failed parsing " + e);
1378 } catch (NullPointerException e) {
1379 Slog.w(TAG, "Failed parsing " + e);
1380 } catch (NumberFormatException e) {
1381 Slog.w(TAG, "Failed parsing " + e);
1382 } catch (XmlPullParserException e) {
1383 Slog.w(TAG, "Failed parsing " + e);
1384 } catch (IOException e) {
1385 Slog.w(TAG, "Failed parsing " + e);
1386 } catch (IndexOutOfBoundsException e) {
1387 Slog.w(TAG, "Failed parsing " + e);
1388 } finally {
1389 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07001390 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001391 }
1392 try {
1393 stream.close();
1394 } catch (IOException e) {
1395 }
1396 }
1397 }
1398 }
1399 }
1400
Svet Ganov2af57082015-07-30 08:44:20 -07001401 void readUidOps(XmlPullParser parser) throws NumberFormatException,
1402 XmlPullParserException, IOException {
1403 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
1404 int outerDepth = parser.getDepth();
1405 int type;
1406 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1407 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1408 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1409 continue;
1410 }
1411
1412 String tagName = parser.getName();
1413 if (tagName.equals("op")) {
1414 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
1415 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
1416 UidState uidState = getUidStateLocked(uid, true);
1417 if (uidState.opModes == null) {
1418 uidState.opModes = new SparseIntArray();
1419 }
1420 uidState.opModes.put(code, mode);
1421 } else {
1422 Slog.w(TAG, "Unknown element under <uid-ops>: "
1423 + parser.getName());
1424 XmlUtils.skipCurrentTag(parser);
1425 }
1426 }
1427 }
1428
Dave Burke0997c5bd2013-08-02 20:25:02 +00001429 void readPackage(XmlPullParser parser) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001430 XmlPullParserException, IOException {
1431 String pkgName = parser.getAttributeValue(null, "n");
1432 int outerDepth = parser.getDepth();
1433 int type;
1434 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1435 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1436 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1437 continue;
1438 }
1439
1440 String tagName = parser.getName();
1441 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001442 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001443 } else {
1444 Slog.w(TAG, "Unknown element under <pkg>: "
1445 + parser.getName());
1446 XmlUtils.skipCurrentTag(parser);
1447 }
1448 }
1449 }
1450
Dave Burke0997c5bd2013-08-02 20:25:02 +00001451 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001452 XmlPullParserException, IOException {
1453 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Jason Monk1c7c3192014-06-26 12:52:18 -04001454 String isPrivilegedString = parser.getAttributeValue(null, "p");
1455 boolean isPrivileged = false;
1456 if (isPrivilegedString == null) {
1457 try {
1458 IPackageManager packageManager = ActivityThread.getPackageManager();
1459 if (packageManager != null) {
1460 ApplicationInfo appInfo = ActivityThread.getPackageManager()
1461 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
1462 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001463 isPrivileged = (appInfo.privateFlags
1464 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001465 }
1466 } else {
1467 // Could not load data, don't add to cache so it will be loaded later.
1468 return;
1469 }
1470 } catch (RemoteException e) {
1471 Slog.w(TAG, "Could not contact PackageManager", e);
1472 }
1473 } else {
1474 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
1475 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001476 int outerDepth = parser.getDepth();
1477 int type;
1478 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1479 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1480 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1481 continue;
1482 }
1483
1484 String tagName = parser.getName();
1485 if (tagName.equals("op")) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001486 Op op = new Op(uid, pkgName, Integer.parseInt(parser.getAttributeValue(null, "n")));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001487 String mode = parser.getAttributeValue(null, "m");
1488 if (mode != null) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001489 op.mode = Integer.parseInt(mode);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001490 }
1491 String time = parser.getAttributeValue(null, "t");
1492 if (time != null) {
1493 op.time = Long.parseLong(time);
1494 }
1495 time = parser.getAttributeValue(null, "r");
1496 if (time != null) {
1497 op.rejectTime = Long.parseLong(time);
1498 }
1499 String dur = parser.getAttributeValue(null, "d");
1500 if (dur != null) {
1501 op.duration = Integer.parseInt(dur);
1502 }
Svet Ganov99b60432015-06-27 13:15:22 -07001503 String proxyUid = parser.getAttributeValue(null, "pu");
1504 if (proxyUid != null) {
1505 op.proxyUid = Integer.parseInt(proxyUid);
1506 }
1507 String proxyPackageName = parser.getAttributeValue(null, "pp");
1508 if (proxyPackageName != null) {
1509 op.proxyPackageName = proxyPackageName;
1510 }
Svet Ganov2af57082015-07-30 08:44:20 -07001511
1512 UidState uidState = getUidStateLocked(uid, true);
1513 if (uidState.pkgOps == null) {
1514 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001515 }
Svet Ganov2af57082015-07-30 08:44:20 -07001516
1517 Ops ops = uidState.pkgOps.get(pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001518 if (ops == null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001519 ops = new Ops(pkgName, uidState, isPrivileged);
1520 uidState.pkgOps.put(pkgName, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001521 }
1522 ops.put(op.op, op);
1523 } else {
1524 Slog.w(TAG, "Unknown element under <pkg>: "
1525 + parser.getName());
1526 XmlUtils.skipCurrentTag(parser);
1527 }
1528 }
1529 }
1530
1531 void writeState() {
1532 synchronized (mFile) {
1533 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
1534
1535 FileOutputStream stream;
1536 try {
1537 stream = mFile.startWrite();
1538 } catch (IOException e) {
1539 Slog.w(TAG, "Failed to write state: " + e);
1540 return;
1541 }
1542
1543 try {
1544 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001545 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001546 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001547 out.startTag(null, "app-ops");
Svet Ganov2af57082015-07-30 08:44:20 -07001548
1549 final int uidStateCount = mUidStates.size();
1550 for (int i = 0; i < uidStateCount; i++) {
1551 UidState uidState = mUidStates.valueAt(i);
1552 if (uidState.opModes != null && uidState.opModes.size() > 0) {
1553 out.startTag(null, "uid");
1554 out.attribute(null, "n", Integer.toString(uidState.uid));
1555 SparseIntArray uidOpModes = uidState.opModes;
1556 final int opCount = uidOpModes.size();
1557 for (int j = 0; j < opCount; j++) {
1558 final int op = uidOpModes.keyAt(j);
1559 final int mode = uidOpModes.valueAt(j);
1560 out.startTag(null, "op");
1561 out.attribute(null, "n", Integer.toString(op));
1562 out.attribute(null, "m", Integer.toString(mode));
1563 out.endTag(null, "op");
1564 }
1565 out.endTag(null, "uid");
1566 }
1567 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001568
1569 if (allOps != null) {
1570 String lastPkg = null;
1571 for (int i=0; i<allOps.size(); i++) {
1572 AppOpsManager.PackageOps pkg = allOps.get(i);
1573 if (!pkg.getPackageName().equals(lastPkg)) {
1574 if (lastPkg != null) {
1575 out.endTag(null, "pkg");
1576 }
1577 lastPkg = pkg.getPackageName();
1578 out.startTag(null, "pkg");
1579 out.attribute(null, "n", lastPkg);
1580 }
1581 out.startTag(null, "uid");
1582 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04001583 synchronized (this) {
Ian Pedowitz9888e002016-03-22 16:13:48 +00001584 Ops ops = getOpsLocked(pkg.getUid(), pkg.getPackageName(), false);
Jason Monk1c7c3192014-06-26 12:52:18 -04001585 // Should always be present as the list of PackageOps is generated
1586 // from Ops.
1587 if (ops != null) {
1588 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
1589 } else {
1590 out.attribute(null, "p", Boolean.toString(false));
1591 }
1592 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001593 List<AppOpsManager.OpEntry> ops = pkg.getOps();
1594 for (int j=0; j<ops.size(); j++) {
1595 AppOpsManager.OpEntry op = ops.get(j);
1596 out.startTag(null, "op");
1597 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07001598 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001599 out.attribute(null, "m", Integer.toString(op.getMode()));
1600 }
1601 long time = op.getTime();
1602 if (time != 0) {
1603 out.attribute(null, "t", Long.toString(time));
1604 }
1605 time = op.getRejectTime();
1606 if (time != 0) {
1607 out.attribute(null, "r", Long.toString(time));
1608 }
1609 int dur = op.getDuration();
1610 if (dur != 0) {
1611 out.attribute(null, "d", Integer.toString(dur));
1612 }
Svet Ganov99b60432015-06-27 13:15:22 -07001613 int proxyUid = op.getProxyUid();
1614 if (proxyUid != -1) {
1615 out.attribute(null, "pu", Integer.toString(proxyUid));
1616 }
1617 String proxyPackageName = op.getProxyPackageName();
1618 if (proxyPackageName != null) {
1619 out.attribute(null, "pp", proxyPackageName);
1620 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001621 out.endTag(null, "op");
1622 }
1623 out.endTag(null, "uid");
1624 }
1625 if (lastPkg != null) {
1626 out.endTag(null, "pkg");
1627 }
1628 }
1629
1630 out.endTag(null, "app-ops");
1631 out.endDocument();
1632 mFile.finishWrite(stream);
1633 } catch (IOException e) {
1634 Slog.w(TAG, "Failed to write state, restoring backup.", e);
1635 mFile.failWrite(stream);
1636 }
1637 }
1638 }
1639
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001640 static class Shell extends ShellCommand {
1641 final IAppOpsService mInterface;
1642 final AppOpsService mInternal;
1643
1644 int userId = UserHandle.USER_SYSTEM;
1645 String packageName;
1646 String opStr;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001647 String modeStr;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001648 int op;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001649 int mode;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001650 int packageUid;
1651
1652 Shell(IAppOpsService iface, AppOpsService internal) {
1653 mInterface = iface;
1654 mInternal = internal;
1655 }
1656
1657 @Override
1658 public int onCommand(String cmd) {
1659 return onShellCommand(this, cmd);
1660 }
1661
1662 @Override
1663 public void onHelp() {
1664 PrintWriter pw = getOutPrintWriter();
1665 dumpCommandHelp(pw);
1666 }
1667
1668 private int strOpToOp(String op, PrintWriter err) {
1669 try {
1670 return AppOpsManager.strOpToOp(op);
1671 } catch (IllegalArgumentException e) {
1672 }
1673 try {
1674 return Integer.parseInt(op);
1675 } catch (NumberFormatException e) {
1676 }
1677 try {
1678 return AppOpsManager.strDebugOpToOp(op);
1679 } catch (IllegalArgumentException e) {
1680 err.println("Error: " + e.getMessage());
1681 return -1;
1682 }
1683 }
1684
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001685 int strModeToMode(String modeStr, PrintWriter err) {
1686 switch (modeStr) {
1687 case "allow":
1688 return AppOpsManager.MODE_ALLOWED;
1689 case "deny":
1690 return AppOpsManager.MODE_ERRORED;
1691 case "ignore":
1692 return AppOpsManager.MODE_IGNORED;
1693 case "default":
1694 return AppOpsManager.MODE_DEFAULT;
1695 }
1696 try {
1697 return Integer.parseInt(modeStr);
1698 } catch (NumberFormatException e) {
1699 }
1700 err.println("Error: Mode " + modeStr + " is not valid");
1701 return -1;
1702 }
1703
1704 int parseUserOpMode(int defMode, PrintWriter err) throws RemoteException {
1705 userId = UserHandle.USER_CURRENT;
1706 opStr = null;
1707 modeStr = null;
1708 for (String argument; (argument = getNextArg()) != null;) {
1709 if ("--user".equals(argument)) {
1710 userId = UserHandle.parseUserArg(getNextArgRequired());
1711 } else {
1712 if (opStr == null) {
1713 opStr = argument;
1714 } else if (modeStr == null) {
1715 modeStr = argument;
1716 break;
1717 }
1718 }
1719 }
1720 if (opStr == null) {
1721 err.println("Error: Operation not specified.");
1722 return -1;
1723 }
1724 op = strOpToOp(opStr, err);
1725 if (op < 0) {
1726 return -1;
1727 }
1728 if (modeStr != null) {
1729 if ((mode=strModeToMode(modeStr, err)) < 0) {
1730 return -1;
1731 }
1732 } else {
1733 mode = defMode;
1734 }
1735 return 0;
1736 }
1737
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001738 int parseUserPackageOp(boolean reqOp, PrintWriter err) throws RemoteException {
1739 userId = UserHandle.USER_CURRENT;
1740 packageName = null;
1741 opStr = null;
1742 for (String argument; (argument = getNextArg()) != null;) {
1743 if ("--user".equals(argument)) {
1744 userId = UserHandle.parseUserArg(getNextArgRequired());
1745 } else {
1746 if (packageName == null) {
1747 packageName = argument;
1748 } else if (opStr == null) {
1749 opStr = argument;
1750 break;
1751 }
1752 }
1753 }
1754 if (packageName == null) {
1755 err.println("Error: Package name not specified.");
1756 return -1;
1757 } else if (opStr == null && reqOp) {
1758 err.println("Error: Operation not specified.");
1759 return -1;
1760 }
1761 if (opStr != null) {
1762 op = strOpToOp(opStr, err);
1763 if (op < 0) {
1764 return -1;
1765 }
1766 } else {
1767 op = AppOpsManager.OP_NONE;
1768 }
1769 if (userId == UserHandle.USER_CURRENT) {
1770 userId = ActivityManager.getCurrentUser();
1771 }
1772 if ("root".equals(packageName)) {
1773 packageUid = 0;
1774 } else {
Jeff Sharkeycd654482016-01-08 17:42:11 -07001775 packageUid = AppGlobals.getPackageManager().getPackageUid(packageName,
1776 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001777 }
1778 if (packageUid < 0) {
1779 err.println("Error: No UID for " + packageName + " in user " + userId);
1780 return -1;
1781 }
1782 return 0;
1783 }
1784 }
1785
1786 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
1787 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
1788 (new Shell(this, this)).exec(this, in, out, err, args, resultReceiver);
1789 }
1790
1791 static void dumpCommandHelp(PrintWriter pw) {
1792 pw.println("AppOps service (appops) commands:");
1793 pw.println(" help");
1794 pw.println(" Print this help text.");
1795 pw.println(" set [--user <USER_ID>] <PACKAGE> <OP> <MODE>");
1796 pw.println(" Set the mode for a particular application and operation.");
1797 pw.println(" get [--user <USER_ID>] <PACKAGE> [<OP>]");
1798 pw.println(" Return the mode for a particular application and optional operation.");
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001799 pw.println(" query-op [--user <USER_ID>] <OP> [<MODE>]");
1800 pw.println(" Print all packages that currently have the given op in the given mode.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001801 pw.println(" reset [--user <USER_ID>] [<PACKAGE>]");
1802 pw.println(" Reset the given application or all applications to default modes.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001803 pw.println(" write-settings");
1804 pw.println(" Immediately write pending changes to storage.");
1805 pw.println(" read-settings");
1806 pw.println(" Read the last written settings, replacing current state in RAM.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001807 pw.println(" options:");
1808 pw.println(" <PACKAGE> an Android package name.");
1809 pw.println(" <OP> an AppOps operation.");
1810 pw.println(" <MODE> one of allow, ignore, deny, or default");
1811 pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
1812 pw.println(" specified, the current user is assumed.");
1813 }
1814
1815 static int onShellCommand(Shell shell, String cmd) {
1816 if (cmd == null) {
1817 return shell.handleDefaultCommands(cmd);
1818 }
1819 PrintWriter pw = shell.getOutPrintWriter();
1820 PrintWriter err = shell.getErrPrintWriter();
1821 try {
1822 switch (cmd) {
1823 case "set": {
1824 int res = shell.parseUserPackageOp(true, err);
1825 if (res < 0) {
1826 return res;
1827 }
1828 String modeStr = shell.getNextArg();
1829 if (modeStr == null) {
1830 err.println("Error: Mode not specified.");
1831 return -1;
1832 }
1833
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001834 final int mode = shell.strModeToMode(modeStr, err);
1835 if (mode < 0) {
1836 return -1;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001837 }
1838
1839 shell.mInterface.setMode(shell.op, shell.packageUid, shell.packageName, mode);
1840 return 0;
1841 }
1842 case "get": {
1843 int res = shell.parseUserPackageOp(false, err);
1844 if (res < 0) {
1845 return res;
1846 }
1847
1848 List<AppOpsManager.PackageOps> ops = shell.mInterface.getOpsForPackage(
1849 shell.packageUid, shell.packageName,
1850 shell.op != AppOpsManager.OP_NONE ? new int[] {shell.op} : null);
1851 if (ops == null || ops.size() <= 0) {
1852 pw.println("No operations.");
1853 return 0;
1854 }
1855 final long now = System.currentTimeMillis();
1856 for (int i=0; i<ops.size(); i++) {
1857 List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
1858 for (int j=0; j<entries.size(); j++) {
1859 AppOpsManager.OpEntry ent = entries.get(j);
1860 pw.print(AppOpsManager.opToName(ent.getOp()));
1861 pw.print(": ");
1862 switch (ent.getMode()) {
1863 case AppOpsManager.MODE_ALLOWED:
1864 pw.print("allow");
1865 break;
1866 case AppOpsManager.MODE_IGNORED:
1867 pw.print("ignore");
1868 break;
1869 case AppOpsManager.MODE_ERRORED:
1870 pw.print("deny");
1871 break;
1872 case AppOpsManager.MODE_DEFAULT:
1873 pw.print("default");
1874 break;
1875 default:
1876 pw.print("mode=");
1877 pw.print(ent.getMode());
1878 break;
1879 }
1880 if (ent.getTime() != 0) {
1881 pw.print("; time=");
1882 TimeUtils.formatDuration(now - ent.getTime(), pw);
1883 pw.print(" ago");
1884 }
1885 if (ent.getRejectTime() != 0) {
1886 pw.print("; rejectTime=");
1887 TimeUtils.formatDuration(now - ent.getRejectTime(), pw);
1888 pw.print(" ago");
1889 }
1890 if (ent.getDuration() == -1) {
1891 pw.print(" (running)");
1892 } else if (ent.getDuration() != 0) {
1893 pw.print("; duration=");
1894 TimeUtils.formatDuration(ent.getDuration(), pw);
1895 }
1896 pw.println();
1897 }
1898 }
1899 return 0;
1900 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001901 case "query-op": {
1902 int res = shell.parseUserOpMode(AppOpsManager.MODE_IGNORED, err);
1903 if (res < 0) {
1904 return res;
1905 }
1906 List<AppOpsManager.PackageOps> ops = shell.mInterface.getPackagesForOps(
1907 new int[] {shell.op});
1908 if (ops == null || ops.size() <= 0) {
1909 pw.println("No operations.");
1910 return 0;
1911 }
1912 for (int i=0; i<ops.size(); i++) {
1913 final AppOpsManager.PackageOps pkg = ops.get(i);
1914 boolean hasMatch = false;
1915 final List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
1916 for (int j=0; j<entries.size(); j++) {
1917 AppOpsManager.OpEntry ent = entries.get(j);
1918 if (ent.getOp() == shell.op && ent.getMode() == shell.mode) {
1919 hasMatch = true;
1920 break;
1921 }
1922 }
1923 if (hasMatch) {
1924 pw.println(pkg.getPackageName());
1925 }
1926 }
1927 return 0;
1928 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001929 case "reset": {
1930 String packageName = null;
1931 int userId = UserHandle.USER_CURRENT;
1932 for (String argument; (argument = shell.getNextArg()) != null;) {
1933 if ("--user".equals(argument)) {
1934 String userStr = shell.getNextArgRequired();
1935 userId = UserHandle.parseUserArg(userStr);
1936 } else {
1937 if (packageName == null) {
1938 packageName = argument;
1939 } else {
1940 err.println("Error: Unsupported argument: " + argument);
1941 return -1;
1942 }
1943 }
1944 }
1945
1946 if (userId == UserHandle.USER_CURRENT) {
1947 userId = ActivityManager.getCurrentUser();
1948 }
1949
1950 shell.mInterface.resetAllModes(userId, packageName);
1951 pw.print("Reset all modes for: ");
1952 if (userId == UserHandle.USER_ALL) {
1953 pw.print("all users");
1954 } else {
1955 pw.print("user "); pw.print(userId);
1956 }
1957 pw.print(", ");
1958 if (packageName == null) {
1959 pw.println("all packages");
1960 } else {
1961 pw.print("package "); pw.println(packageName);
1962 }
1963 return 0;
1964 }
1965 case "write-settings": {
1966 shell.mInternal.mContext.enforcePermission(
1967 android.Manifest.permission.UPDATE_APP_OPS_STATS,
1968 Binder.getCallingPid(), Binder.getCallingUid(), null);
1969 long token = Binder.clearCallingIdentity();
1970 try {
1971 synchronized (shell.mInternal) {
1972 shell.mInternal.mHandler.removeCallbacks(shell.mInternal.mWriteRunner);
1973 }
1974 shell.mInternal.writeState();
1975 pw.println("Current settings written.");
1976 } finally {
1977 Binder.restoreCallingIdentity(token);
1978 }
1979 return 0;
1980 }
1981 case "read-settings": {
1982 shell.mInternal.mContext.enforcePermission(
1983 android.Manifest.permission.UPDATE_APP_OPS_STATS,
1984 Binder.getCallingPid(), Binder.getCallingUid(), null);
1985 long token = Binder.clearCallingIdentity();
1986 try {
1987 shell.mInternal.readState();
1988 pw.println("Last settings read.");
1989 } finally {
1990 Binder.restoreCallingIdentity(token);
1991 }
1992 return 0;
1993 }
1994 default:
1995 return shell.handleDefaultCommands(cmd);
1996 }
1997 } catch (RemoteException e) {
1998 pw.println("Remote exception: " + e);
1999 }
2000 return -1;
2001 }
2002
2003 private void dumpHelp(PrintWriter pw) {
2004 pw.println("AppOps service (appops) dump options:");
2005 pw.println(" none");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002006 }
2007
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002008 @Override
2009 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2010 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2011 != PackageManager.PERMISSION_GRANTED) {
2012 pw.println("Permission Denial: can't dump ApOps service from from pid="
2013 + Binder.getCallingPid()
2014 + ", uid=" + Binder.getCallingUid());
2015 return;
2016 }
2017
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002018 if (args != null) {
2019 for (int i=0; i<args.length; i++) {
2020 String arg = args[i];
2021 if ("-h".equals(arg)) {
2022 dumpHelp(pw);
2023 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07002024 } else if ("-a".equals(arg)) {
2025 // dump all data
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002026 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
2027 pw.println("Unknown option: " + arg);
2028 return;
2029 } else {
2030 pw.println("Unknown command: " + arg);
2031 return;
2032 }
2033 }
2034 }
2035
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002036 synchronized (this) {
2037 pw.println("Current AppOps Service state:");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002038 final long now = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002039 boolean needSep = false;
2040 if (mOpModeWatchers.size() > 0) {
2041 needSep = true;
2042 pw.println(" Op mode watchers:");
2043 for (int i=0; i<mOpModeWatchers.size(); i++) {
2044 pw.print(" Op "); pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
2045 pw.println(":");
2046 ArrayList<Callback> callbacks = mOpModeWatchers.valueAt(i);
2047 for (int j=0; j<callbacks.size(); j++) {
2048 pw.print(" #"); pw.print(j); pw.print(": ");
2049 pw.println(callbacks.get(j));
2050 }
2051 }
2052 }
2053 if (mPackageModeWatchers.size() > 0) {
2054 needSep = true;
2055 pw.println(" Package mode watchers:");
2056 for (int i=0; i<mPackageModeWatchers.size(); i++) {
2057 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
2058 pw.println(":");
2059 ArrayList<Callback> callbacks = mPackageModeWatchers.valueAt(i);
2060 for (int j=0; j<callbacks.size(); j++) {
2061 pw.print(" #"); pw.print(j); pw.print(": ");
2062 pw.println(callbacks.get(j));
2063 }
2064 }
2065 }
2066 if (mModeWatchers.size() > 0) {
2067 needSep = true;
2068 pw.println(" All mode watchers:");
2069 for (int i=0; i<mModeWatchers.size(); i++) {
2070 pw.print(" "); pw.print(mModeWatchers.keyAt(i));
2071 pw.print(" -> "); pw.println(mModeWatchers.valueAt(i));
2072 }
2073 }
2074 if (mClients.size() > 0) {
2075 needSep = true;
2076 pw.println(" Clients:");
2077 for (int i=0; i<mClients.size(); i++) {
2078 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
2079 ClientState cs = mClients.valueAt(i);
2080 pw.print(" "); pw.println(cs);
2081 if (cs.mStartedOps != null && cs.mStartedOps.size() > 0) {
2082 pw.println(" Started ops:");
2083 for (int j=0; j<cs.mStartedOps.size(); j++) {
2084 Op op = cs.mStartedOps.get(j);
2085 pw.print(" "); pw.print("uid="); pw.print(op.uid);
2086 pw.print(" pkg="); pw.print(op.packageName);
2087 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
2088 }
2089 }
2090 }
2091 }
John Spurlock1af30c72014-03-10 08:33:35 -04002092 if (mAudioRestrictions.size() > 0) {
2093 boolean printedHeader = false;
2094 for (int o=0; o<mAudioRestrictions.size(); o++) {
2095 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
2096 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
2097 for (int i=0; i<restrictions.size(); i++) {
2098 if (!printedHeader){
2099 pw.println(" Audio Restrictions:");
2100 printedHeader = true;
2101 needSep = true;
2102 }
John Spurlock7b414672014-07-18 13:02:39 -04002103 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04002104 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04002105 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04002106 Restriction r = restrictions.valueAt(i);
2107 pw.print(": mode="); pw.println(r.mode);
2108 if (!r.exceptionPackages.isEmpty()) {
2109 pw.println(" Exceptions:");
2110 for (int j=0; j<r.exceptionPackages.size(); j++) {
2111 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
2112 }
2113 }
2114 }
2115 }
2116 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002117 if (needSep) {
2118 pw.println();
2119 }
Svet Ganov2af57082015-07-30 08:44:20 -07002120 for (int i=0; i<mUidStates.size(); i++) {
2121 UidState uidState = mUidStates.valueAt(i);
2122
2123 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
2124
2125 SparseIntArray opModes = uidState.opModes;
2126 if (opModes != null) {
2127 final int opModeCount = opModes.size();
2128 for (int j = 0; j < opModeCount; j++) {
2129 final int code = opModes.keyAt(j);
2130 final int mode = opModes.valueAt(j);
2131 pw.print(" "); pw.print(AppOpsManager.opToName(code));
2132 pw.print(": mode="); pw.println(mode);
2133 }
2134 }
2135
2136 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
2137 if (pkgOps == null) {
2138 continue;
2139 }
2140
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002141 for (Ops ops : pkgOps.values()) {
2142 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
2143 for (int j=0; j<ops.size(); j++) {
2144 Op op = ops.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002145 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
2146 pw.print(": mode="); pw.print(op.mode);
2147 if (op.time != 0) {
2148 pw.print("; time="); TimeUtils.formatDuration(now-op.time, pw);
2149 pw.print(" ago");
2150 }
2151 if (op.rejectTime != 0) {
2152 pw.print("; rejectTime="); TimeUtils.formatDuration(now-op.rejectTime, pw);
2153 pw.print(" ago");
2154 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002155 if (op.duration == -1) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002156 pw.print(" (running)");
2157 } else if (op.duration != 0) {
2158 pw.print("; duration="); TimeUtils.formatDuration(op.duration, pw);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002159 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002160 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002161 }
2162 }
2163 }
2164 }
2165 }
John Spurlock1af30c72014-03-10 08:33:35 -04002166
2167 private static final class Restriction {
2168 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
2169 int mode;
2170 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
2171 }
Jason Monk62062992014-05-06 09:55:28 -04002172
2173 @Override
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002174 public void setUserRestrictions(Bundle restrictions, IBinder token, int userHandle) {
Jason Monk62062992014-05-06 09:55:28 -04002175 checkSystemUid("setUserRestrictions");
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002176 Preconditions.checkNotNull(token);
2177 final boolean[] opRestrictions = getOrCreateUserRestrictionsForToken(token, userHandle);
Jason Monk62062992014-05-06 09:55:28 -04002178 for (int i = 0; i < opRestrictions.length; ++i) {
2179 String restriction = AppOpsManager.opToRestriction(i);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002180 final boolean restricted = restriction != null
2181 && restrictions.getBoolean(restriction, false);
2182 setUserRestrictionNoCheck(i, restricted, token, userHandle);
2183 }
2184 }
2185
2186 @Override
Ruben Brunk29931bc2016-03-11 00:24:26 -08002187 public void setUserRestriction(int code, boolean restricted, IBinder token, int userHandle,
2188 String[] exceptionPackages) {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002189 if (Binder.getCallingPid() != Process.myPid()) {
2190 mContext.enforcePermission(Manifest.permission.MANAGE_APP_OPS_RESTRICTIONS,
2191 Binder.getCallingPid(), Binder.getCallingUid(), null);
2192 }
2193 if (userHandle != UserHandle.getCallingUserId()) {
2194 if (mContext.checkCallingOrSelfPermission(Manifest.permission
2195 .INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
2196 && mContext.checkCallingOrSelfPermission(Manifest.permission
2197 .INTERACT_ACROSS_USERS) != PackageManager.PERMISSION_GRANTED) {
2198 throw new SecurityException("Need INTERACT_ACROSS_USERS_FULL or"
2199 + " INTERACT_ACROSS_USERS to interact cross user ");
Jason Monk62062992014-05-06 09:55:28 -04002200 }
2201 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002202 verifyIncomingOp(code);
2203 Preconditions.checkNotNull(token);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002204 setUserRestrictionNoCheck(code, restricted, token, userHandle, exceptionPackages);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002205 }
2206
2207 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
2208 int userHandle) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002209 setUserRestrictionNoCheck(code, restricted, token, userHandle, /*exceptionPackages*/null);
2210 }
2211
2212 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
2213 int userHandle, String[] exceptionPackages) {
2214
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002215 final boolean[] opRestrictions = getOrCreateUserRestrictionsForToken(token, userHandle);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002216
2217 if (restricted) {
2218 final SparseArray<ArraySet<String>> opExceptions =
2219 getUserPackageExemptionsForToken(token, userHandle);
2220
Ruben Brunk29931bc2016-03-11 00:24:26 -08002221 ArraySet<String> exceptions = opExceptions.get(code);
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002222 if (exceptionPackages != null && exceptionPackages.length > 0) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002223 if (exceptions == null) {
2224 exceptions = new ArraySet<>(exceptionPackages.length);
2225 opExceptions.put(code, exceptions);
2226 } else {
2227 exceptions.clear();
2228 }
2229
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002230 for (String p : exceptionPackages) {
2231 exceptions.add(p);
2232 }
2233 } else {
2234 opExceptions.remove(code);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002235 }
2236 }
2237
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002238 if (opRestrictions[code] == restricted) {
2239 return;
2240 }
2241 opRestrictions[code] = restricted;
2242 if (!restricted) {
2243 pruneUserRestrictionsForToken(token, userHandle);
2244 }
2245
2246 final ArrayList<Callback> clonedCallbacks;
2247 synchronized (this) {
2248 ArrayList<Callback> callbacks = mOpModeWatchers.get(code);
2249 if (callbacks == null) {
2250 return;
2251 }
2252 clonedCallbacks = new ArrayList<>(callbacks);
2253 }
2254
2255 // There are components watching for mode changes such as window manager
2256 // and location manager which are in our process. The callbacks in these
2257 // components may require permissions our remote caller does not have.
2258 final long identity = Binder.clearCallingIdentity();
2259 try {
2260 final int callbackCount = clonedCallbacks.size();
2261 for (int i = 0; i < callbackCount; i++) {
2262 Callback callback = clonedCallbacks.get(i);
2263 try {
2264 callback.mCallback.opChanged(code, -1, null);
2265 } catch (RemoteException e) {
2266 Log.w(TAG, "Error dispatching op op change", e);
2267 }
2268 }
2269 } finally {
2270 Binder.restoreCallingIdentity(identity);
2271 }
Jason Monk62062992014-05-06 09:55:28 -04002272 }
2273
2274 @Override
2275 public void removeUser(int userHandle) throws RemoteException {
2276 checkSystemUid("removeUser");
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002277 final int tokenCount = mOpUserRestrictions.size();
2278 for (int i = tokenCount - 1; i >= 0; i--) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002279 SparseArray<Pair<boolean[], SparseArray<ArraySet<String>>>> opRestrictions =
2280 mOpUserRestrictions.valueAt(i);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002281 if (opRestrictions != null) {
2282 opRestrictions.remove(userHandle);
2283 if (opRestrictions.size() <= 0) {
2284 mOpUserRestrictions.removeAt(i);
2285 }
2286 }
2287 }
2288 }
2289
2290
2291 private void pruneUserRestrictionsForToken(IBinder token, int userHandle) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002292 SparseArray<Pair<boolean[], SparseArray<ArraySet<String>>>> perTokenRestrictions =
2293 mOpUserRestrictions.get(token);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002294 if (perTokenRestrictions != null) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002295 final Pair<boolean[], SparseArray<ArraySet<String>>> restrictions =
2296 perTokenRestrictions.get(userHandle);
2297
2298 if (restrictions != null) {
2299 final boolean[] opRestrictions = restrictions.first;
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002300 final SparseArray<ArraySet<String>> opExceptions = restrictions.second;
2301 boolean stillHasRestrictions = false;
Ruben Brunk29931bc2016-03-11 00:24:26 -08002302 if (opRestrictions != null) {
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002303 for (int i = 0; i < opRestrictions.length; i++) {
2304 boolean restriction = opRestrictions[i];
Ruben Brunk29931bc2016-03-11 00:24:26 -08002305 if (restriction) {
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002306 stillHasRestrictions = true;
2307 } else {
2308 opExceptions.remove(i);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002309 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002310 }
2311 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002312
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002313 if (stillHasRestrictions) {
2314 return;
2315 }
2316
Ruben Brunk29931bc2016-03-11 00:24:26 -08002317 // No restrictions set for this client
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002318 perTokenRestrictions.remove(userHandle);
2319 if (perTokenRestrictions.size() <= 0) {
2320 mOpUserRestrictions.remove(token);
2321 }
2322 }
2323 }
2324 }
2325
Ruben Brunk29931bc2016-03-11 00:24:26 -08002326 /**
2327 * Get or create the user restrictions array for a given client if it doesn't already exist.
2328 *
2329 * @param token the binder client creating the restriction.
2330 * @param userHandle the user handle to create a restriction for.
2331 *
2332 * @return the array of restriction states for each AppOps code.
2333 */
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002334 private boolean[] getOrCreateUserRestrictionsForToken(IBinder token, int userHandle) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002335 SparseArray<Pair<boolean[], SparseArray<ArraySet<String>>>> perTokenRestrictions =
2336 mOpUserRestrictions.get(token);
2337
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002338 if (perTokenRestrictions == null) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002339 perTokenRestrictions =
2340 new SparseArray<Pair<boolean[], SparseArray<ArraySet<String>>>>();
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002341 mOpUserRestrictions.put(token, perTokenRestrictions);
2342 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002343
2344 Pair<boolean[], SparseArray<ArraySet<String>>> restrictions =
2345 perTokenRestrictions.get(userHandle);
2346
2347 if (restrictions == null) {
2348 restrictions = new Pair<boolean[], SparseArray<ArraySet<String>>>(
2349 new boolean[AppOpsManager._NUM_OP], new SparseArray<ArraySet<String>>());
2350 perTokenRestrictions.put(userHandle, restrictions);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002351 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002352
2353 return restrictions.first;
2354 }
2355
2356 /**
2357 * Get the per-package exemptions for each AppOps code for a given client and userHandle.
2358 *
2359 * @param token the binder client to get the exemptions for.
2360 * @param userHandle the user handle to get the exemptions for.
2361 *
2362 * @return a mapping from the AppOps code to a set of packages exempt for that code.
2363 */
2364 private SparseArray<ArraySet<String>> getUserPackageExemptionsForToken(IBinder token,
2365 int userHandle) {
2366 SparseArray<Pair<boolean[], SparseArray<ArraySet<String>>>> perTokenRestrictions =
2367 mOpUserRestrictions.get(token);
2368
2369 if (perTokenRestrictions == null) {
2370 return null; // Don't create user restrictions accidentally
2371 }
2372
2373 Pair<boolean[], SparseArray<ArraySet<String>>> restrictions =
2374 perTokenRestrictions.get(userHandle);
2375
2376 if (restrictions == null) {
2377 return null; // Don't create user restrictions accidentally
2378 }
2379
2380 return restrictions.second;
Jason Monk62062992014-05-06 09:55:28 -04002381 }
2382
2383 private void checkSystemUid(String function) {
2384 int uid = Binder.getCallingUid();
2385 if (uid != Process.SYSTEM_UID) {
2386 throw new SecurityException(function + " must by called by the system");
2387 }
2388 }
2389
Svet Ganov2af57082015-07-30 08:44:20 -07002390 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07002391 String[] packageNames = null;
Svet Ganov2af57082015-07-30 08:44:20 -07002392 try {
riddle_hsu40b300f2015-11-23 13:22:03 +08002393 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -07002394 } catch (RemoteException e) {
2395 /* ignore - local call */
2396 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07002397 if (packageNames == null) {
2398 return EmptyArray.STRING;
2399 }
2400 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07002401 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002402}