blob: fd57af6b02f0a90d0b20301f56be9d3a791cef97 [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 Stingaceanuefc4a342016-03-22 14:43:01 +0000904 boolean suspended;
905 try {
906 suspended = isPackageSuspendedForUser(packageName, uid);
907 } catch (IllegalArgumentException ex) {
908 // Package not found.
909 suspended = false;
910 }
911
912 if (suspended) {
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000913 Log.i(TAG, "Audio disabled for suspended package=" + packageName + " for uid=" + uid);
914 return AppOpsManager.MODE_IGNORED;
915 }
916
John Spurlock1af30c72014-03-10 08:33:35 -0400917 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -0400918 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -0400919 if (mode != AppOpsManager.MODE_ALLOWED) {
920 return mode;
921 }
922 }
923 return checkOperation(code, uid, packageName);
924 }
925
Andrei Stingaceanu355b2322016-02-12 16:43:51 +0000926 private boolean isPackageSuspendedForUser(String pkg, int uid) {
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000927 try {
Andrei Stingaceanu355b2322016-02-12 16:43:51 +0000928 return AppGlobals.getPackageManager().isPackageSuspendedForUser(
929 pkg, UserHandle.getUserId(uid));
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000930 } catch (RemoteException re) {
931 throw new SecurityException("Could not talk to package manager service");
932 }
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000933 }
934
John Spurlock7b414672014-07-18 13:02:39 -0400935 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
936 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
937 if (usageRestrictions != null) {
938 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -0400939 if (r != null && !r.exceptionPackages.contains(packageName)) {
940 return r.mode;
941 }
942 }
943 return AppOpsManager.MODE_ALLOWED;
944 }
945
946 @Override
John Spurlock7b414672014-07-18 13:02:39 -0400947 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -0400948 String[] exceptionPackages) {
949 verifyIncomingUid(uid);
950 verifyIncomingOp(code);
951 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -0400952 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
953 if (usageRestrictions == null) {
954 usageRestrictions = new SparseArray<Restriction>();
955 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -0400956 }
John Spurlock7b414672014-07-18 13:02:39 -0400957 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -0400958 if (mode != AppOpsManager.MODE_ALLOWED) {
959 final Restriction r = new Restriction();
960 r.mode = mode;
961 if (exceptionPackages != null) {
962 final int N = exceptionPackages.length;
963 r.exceptionPackages = new ArraySet<String>(N);
964 for (int i = 0; i < N; i++) {
965 final String pkg = exceptionPackages[i];
966 if (pkg != null) {
967 r.exceptionPackages.add(pkg.trim());
968 }
969 }
970 }
John Spurlock7b414672014-07-18 13:02:39 -0400971 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -0400972 }
973 }
974 }
975
976 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700977 public int checkPackage(int uid, String packageName) {
978 synchronized (this) {
Dianne Hackborn0fcef842014-09-12 15:38:33 -0700979 if (getOpsRawLocked(uid, packageName, true) != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700980 return AppOpsManager.MODE_ALLOWED;
981 } else {
982 return AppOpsManager.MODE_ERRORED;
983 }
984 }
985 }
986
987 @Override
Svet Ganov99b60432015-06-27 13:15:22 -0700988 public int noteProxyOperation(int code, String proxyPackageName,
989 int proxiedUid, String proxiedPackageName) {
990 verifyIncomingOp(code);
Ian Pedowitz9888e002016-03-22 16:13:48 +0000991 final int proxyMode = noteOperationUnchecked(code, Binder.getCallingUid(),
992 proxyPackageName, -1, null);
Svet Ganov99b60432015-06-27 13:15:22 -0700993 if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
994 return proxyMode;
995 }
Ian Pedowitz9888e002016-03-22 16:13:48 +0000996 return noteOperationUnchecked(code, proxiedUid, proxiedPackageName,
997 Binder.getCallingUid(), proxyPackageName);
Svet Ganov99b60432015-06-27 13:15:22 -0700998 }
999
1000 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001001 public int noteOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001002 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001003 verifyIncomingOp(code);
Ian Pedowitz9888e002016-03-22 16:13:48 +00001004 return noteOperationUnchecked(code, uid, packageName, 0, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001005 }
1006
1007 private int noteOperationUnchecked(int code, int uid, String packageName,
1008 int proxyUid, String proxyPackageName) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001009 synchronized (this) {
Ian Pedowitz9888e002016-03-22 16:13:48 +00001010 Ops ops = getOpsLocked(uid, packageName, true);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001011 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001012 if (DEBUG) Log.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
1013 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001014 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001015 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001016 Op op = getOpLocked(ops, code, true);
Jason Monk1c7c3192014-06-26 12:52:18 -04001017 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001018 return AppOpsManager.MODE_IGNORED;
1019 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001020 if (op.duration == -1) {
1021 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
1022 + " code " + code + " time=" + op.time + " duration=" + op.duration);
1023 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001024 op.duration = 0;
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001025 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001026 UidState uidState = ops.uidState;
1027 if (uidState.opModes != null) {
1028 final int uidMode = uidState.opModes.get(switchCode);
1029 if (uidMode != AppOpsManager.MODE_ALLOWED) {
1030 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1031 + switchCode + " (" + code + ") uid " + uid + " package "
1032 + packageName);
1033 op.rejectTime = System.currentTimeMillis();
1034 return uidMode;
1035 }
1036 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001037 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
1038 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
1039 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1040 + switchCode + " (" + code + ") uid " + uid + " package " + packageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001041 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001042 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001043 }
1044 if (DEBUG) Log.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
1045 + " package " + packageName);
1046 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001047 op.rejectTime = 0;
Svet Ganov99b60432015-06-27 13:15:22 -07001048 op.proxyUid = proxyUid;
1049 op.proxyPackageName = proxyPackageName;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001050 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001051 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001052 }
1053
1054 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001055 public int startOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001056 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001057 verifyIncomingOp(code);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001058 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001059 synchronized (this) {
Ian Pedowitz9888e002016-03-22 16:13:48 +00001060 Ops ops = getOpsLocked(uid, packageName, true);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001061 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001062 if (DEBUG) Log.d(TAG, "startOperation: no op for code " + code + " uid " + uid
Ian Pedowitz9888e002016-03-22 16:13:48 +00001063 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001064 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001065 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001066 Op op = getOpLocked(ops, code, true);
Ian Pedowitz9888e002016-03-22 16:13:48 +00001067 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001068 return AppOpsManager.MODE_IGNORED;
1069 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001070 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001071 UidState uidState = ops.uidState;
1072 if (uidState.opModes != null) {
1073 final int uidMode = uidState.opModes.get(switchCode);
1074 if (uidMode != AppOpsManager.MODE_ALLOWED) {
1075 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1076 + switchCode + " (" + code + ") uid " + uid + " package "
Ian Pedowitz9888e002016-03-22 16:13:48 +00001077 + packageName);
Svet Ganov2af57082015-07-30 08:44:20 -07001078 op.rejectTime = System.currentTimeMillis();
1079 return uidMode;
1080 }
1081 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001082 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
1083 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
1084 if (DEBUG) Log.d(TAG, "startOperation: reject #" + op.mode + " for code "
Ian Pedowitz9888e002016-03-22 16:13:48 +00001085 + switchCode + " (" + code + ") uid " + uid + " package " + packageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001086 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001087 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001088 }
1089 if (DEBUG) Log.d(TAG, "startOperation: allowing code " + code + " uid " + uid
Ian Pedowitz9888e002016-03-22 16:13:48 +00001090 + " package " + packageName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001091 if (op.nesting == 0) {
1092 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001093 op.rejectTime = 0;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001094 op.duration = -1;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001095 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001096 op.nesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001097 if (client.mStartedOps != null) {
1098 client.mStartedOps.add(op);
1099 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001100 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001101 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001102 }
1103
1104 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001105 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001106 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001107 verifyIncomingOp(code);
Ian Pedowitz9888e002016-03-22 16:13:48 +00001108 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001109 synchronized (this) {
Ian Pedowitz9888e002016-03-22 16:13:48 +00001110 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001111 if (op == null) {
1112 return;
1113 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001114 if (client.mStartedOps != null) {
1115 if (!client.mStartedOps.remove(op)) {
1116 throw new IllegalStateException("Operation not started: uid" + op.uid
1117 + " pkg=" + op.packageName + " op=" + op.op);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001118 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001119 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001120 finishOperationLocked(op);
1121 }
1122 }
1123
Svet Ganovb9d71a62015-04-30 10:38:13 -07001124 @Override
1125 public int permissionToOpCode(String permission) {
1126 return AppOpsManager.permissionToOpCode(permission);
1127 }
1128
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001129 void finishOperationLocked(Op op) {
1130 if (op.nesting <= 1) {
1131 if (op.nesting == 1) {
1132 op.duration = (int)(System.currentTimeMillis() - op.time);
1133 op.time += op.duration;
1134 } else {
1135 Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
1136 + op.packageName + " code " + op.op + " time=" + op.time
1137 + " duration=" + op.duration + " nesting=" + op.nesting);
1138 }
1139 op.nesting = 0;
1140 } else {
1141 op.nesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001142 }
1143 }
1144
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001145 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001146 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001147 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001148 }
1149 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001150 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001151 }
1152 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
1153 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001154 }
1155
Dianne Hackborn961321f2013-02-05 17:22:41 -08001156 private void verifyIncomingOp(int op) {
1157 if (op >= 0 && op < AppOpsManager._NUM_OP) {
1158 return;
1159 }
1160 throw new IllegalArgumentException("Bad operation #" + op);
1161 }
1162
Svet Ganov2af57082015-07-30 08:44:20 -07001163 private UidState getUidStateLocked(int uid, boolean edit) {
1164 UidState uidState = mUidStates.get(uid);
1165 if (uidState == null) {
1166 if (!edit) {
1167 return null;
1168 }
1169 uidState = new UidState(uid);
1170 mUidStates.put(uid, uidState);
1171 }
1172 return uidState;
1173 }
1174
Ian Pedowitz9888e002016-03-22 16:13:48 +00001175 private Ops getOpsLocked(int uid, String packageName, boolean edit) {
1176 if (uid == 0) {
1177 packageName = "root";
1178 } else if (uid == Process.SHELL_UID) {
1179 packageName = "com.android.shell";
1180 }
1181 return getOpsRawLocked(uid, packageName, edit);
1182 }
1183
Dianne Hackborn0fcef842014-09-12 15:38:33 -07001184 private Ops getOpsRawLocked(int uid, String packageName, boolean edit) {
Svet Ganov2af57082015-07-30 08:44:20 -07001185 UidState uidState = getUidStateLocked(uid, edit);
1186 if (uidState == null) {
1187 return null;
1188 }
1189
1190 if (uidState.pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001191 if (!edit) {
1192 return null;
1193 }
Svet Ganov2af57082015-07-30 08:44:20 -07001194 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001195 }
Svet Ganov2af57082015-07-30 08:44:20 -07001196
1197 Ops ops = uidState.pkgOps.get(packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001198 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001199 if (!edit) {
1200 return null;
1201 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001202 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001203 // This is the first time we have seen this package name under this uid,
1204 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -08001205 if (uid != 0) {
1206 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001207 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001208 int pkgUid = -1;
1209 try {
Jason Monk1c7c3192014-06-26 12:52:18 -04001210 ApplicationInfo appInfo = ActivityThread.getPackageManager()
Jeff Sharkeycd654482016-01-08 17:42:11 -07001211 .getApplicationInfo(packageName,
1212 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1213 UserHandle.getUserId(uid));
Jason Monk1c7c3192014-06-26 12:52:18 -04001214 if (appInfo != null) {
1215 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001216 isPrivileged = (appInfo.privateFlags
1217 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001218 } else {
1219 if ("media".equals(packageName)) {
1220 pkgUid = Process.MEDIA_UID;
1221 isPrivileged = false;
Andy Hunged0ea402015-10-30 14:11:46 -07001222 } else if ("audioserver".equals(packageName)) {
1223 pkgUid = Process.AUDIOSERVER_UID;
1224 isPrivileged = false;
Chien-Yu Chen75cade02016-01-11 10:56:21 -08001225 } else if ("cameraserver".equals(packageName)) {
1226 pkgUid = Process.CAMERASERVER_UID;
1227 isPrivileged = false;
Jason Monk1c7c3192014-06-26 12:52:18 -04001228 }
Dianne Hackborn713df152013-05-17 11:27:57 -07001229 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001230 } catch (RemoteException e) {
1231 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001232 }
1233 if (pkgUid != uid) {
1234 // Oops! The package name is not valid for the uid they are calling
1235 // under. Abort.
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001236 RuntimeException ex = new RuntimeException("here");
1237 ex.fillInStackTrace();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001238 Slog.w(TAG, "Bad call: specified package " + packageName
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001239 + " under uid " + uid + " but it is really " + pkgUid, ex);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001240 return null;
1241 }
1242 } finally {
1243 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001244 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001245 }
Svet Ganov2af57082015-07-30 08:44:20 -07001246 ops = new Ops(packageName, uidState, isPrivileged);
1247 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001248 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08001249 return ops;
1250 }
1251
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001252 private void scheduleWriteLocked() {
1253 if (!mWriteScheduled) {
1254 mWriteScheduled = true;
1255 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
1256 }
1257 }
1258
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001259 private void scheduleFastWriteLocked() {
1260 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001261 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001262 mFastWriteScheduled = true;
1263 mHandler.removeCallbacks(mWriteRunner);
1264 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001265 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001266 }
1267
Dianne Hackborn72e39832013-01-18 18:36:09 -08001268 private Op getOpLocked(int code, int uid, String packageName, boolean edit) {
Ian Pedowitz9888e002016-03-22 16:13:48 +00001269 Ops ops = getOpsLocked(uid, packageName, edit);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001270 if (ops == null) {
1271 return null;
1272 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001273 return getOpLocked(ops, code, edit);
1274 }
1275
1276 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001277 Op op = ops.get(code);
1278 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001279 if (!edit) {
1280 return null;
1281 }
Svet Ganov2af57082015-07-30 08:44:20 -07001282 op = new Op(ops.uidState.uid, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001283 ops.put(code, op);
1284 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001285 if (edit) {
1286 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001287 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001288 return op;
1289 }
1290
Jason Monk1c7c3192014-06-26 12:52:18 -04001291 private boolean isOpRestricted(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04001292 int userHandle = UserHandle.getUserId(uid);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001293 final int restrictionSetCount = mOpUserRestrictions.size();
Ruben Brunk29931bc2016-03-11 00:24:26 -08001294
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001295 for (int i = 0; i < restrictionSetCount; i++) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08001296 // For each client, check that the given op is not restricted, or that the given
1297 // package is exempt from the restriction.
1298
1299 SparseArray<Pair<boolean[],SparseArray<ArraySet<String>>>> perUserRestrictions =
1300 mOpUserRestrictions.valueAt(i);
1301
1302 Pair<boolean[],SparseArray<ArraySet<String>>> restrictions =
1303 perUserRestrictions.get(userHandle);
1304 if (restrictions == null) {
1305 continue; // No restrictions set by this client
1306 }
1307
1308 boolean[] opRestrictions = restrictions.first;
1309 SparseArray<ArraySet<String>> opExceptions = restrictions.second;
1310
1311 if (opRestrictions == null) {
1312 continue; // No restrictions set by this client
1313 }
1314
1315 if (opRestrictions[code]) {
Ruben Brunk32f0fa42016-03-11 19:07:07 -08001316
1317 if (opExceptions != null) {
1318 ArraySet<String> ex = opExceptions.get(code);
1319 if (ex != null && ex.contains(packageName)) {
1320 continue; // AppOps code is restricted, but this package is exempt
1321 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08001322 }
1323
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001324 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08001325 // If we are the system, bypass user restrictions for certain codes
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001326 synchronized (this) {
Ian Pedowitz9888e002016-03-22 16:13:48 +00001327 Ops ops = getOpsLocked(uid, packageName, true);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001328 if ((ops != null) && ops.isPrivileged) {
1329 return false;
1330 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001331 }
1332 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08001333
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001334 return true;
Jason Monk1c7c3192014-06-26 12:52:18 -04001335 }
Jason Monk62062992014-05-06 09:55:28 -04001336 }
1337 return false;
1338 }
1339
Dianne Hackborn35654b62013-01-14 17:38:02 -08001340 void readState() {
1341 synchronized (mFile) {
1342 synchronized (this) {
1343 FileInputStream stream;
1344 try {
1345 stream = mFile.openRead();
1346 } catch (FileNotFoundException e) {
1347 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
1348 return;
1349 }
1350 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001351 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001352 try {
1353 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001354 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001355 int type;
1356 while ((type = parser.next()) != XmlPullParser.START_TAG
1357 && type != XmlPullParser.END_DOCUMENT) {
1358 ;
1359 }
1360
1361 if (type != XmlPullParser.START_TAG) {
1362 throw new IllegalStateException("no start tag found");
1363 }
1364
1365 int outerDepth = parser.getDepth();
1366 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1367 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1368 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1369 continue;
1370 }
1371
1372 String tagName = parser.getName();
1373 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001374 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07001375 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07001376 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001377 } else {
1378 Slog.w(TAG, "Unknown element under <app-ops>: "
1379 + parser.getName());
1380 XmlUtils.skipCurrentTag(parser);
1381 }
1382 }
1383 success = true;
1384 } catch (IllegalStateException e) {
1385 Slog.w(TAG, "Failed parsing " + e);
1386 } catch (NullPointerException e) {
1387 Slog.w(TAG, "Failed parsing " + e);
1388 } catch (NumberFormatException e) {
1389 Slog.w(TAG, "Failed parsing " + e);
1390 } catch (XmlPullParserException e) {
1391 Slog.w(TAG, "Failed parsing " + e);
1392 } catch (IOException e) {
1393 Slog.w(TAG, "Failed parsing " + e);
1394 } catch (IndexOutOfBoundsException e) {
1395 Slog.w(TAG, "Failed parsing " + e);
1396 } finally {
1397 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07001398 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001399 }
1400 try {
1401 stream.close();
1402 } catch (IOException e) {
1403 }
1404 }
1405 }
1406 }
1407 }
1408
Svet Ganov2af57082015-07-30 08:44:20 -07001409 void readUidOps(XmlPullParser parser) throws NumberFormatException,
1410 XmlPullParserException, IOException {
1411 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
1412 int outerDepth = parser.getDepth();
1413 int type;
1414 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1415 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1416 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1417 continue;
1418 }
1419
1420 String tagName = parser.getName();
1421 if (tagName.equals("op")) {
1422 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
1423 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
1424 UidState uidState = getUidStateLocked(uid, true);
1425 if (uidState.opModes == null) {
1426 uidState.opModes = new SparseIntArray();
1427 }
1428 uidState.opModes.put(code, mode);
1429 } else {
1430 Slog.w(TAG, "Unknown element under <uid-ops>: "
1431 + parser.getName());
1432 XmlUtils.skipCurrentTag(parser);
1433 }
1434 }
1435 }
1436
Dave Burke0997c5bd2013-08-02 20:25:02 +00001437 void readPackage(XmlPullParser parser) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001438 XmlPullParserException, IOException {
1439 String pkgName = parser.getAttributeValue(null, "n");
1440 int outerDepth = parser.getDepth();
1441 int type;
1442 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1443 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1444 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1445 continue;
1446 }
1447
1448 String tagName = parser.getName();
1449 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001450 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001451 } else {
1452 Slog.w(TAG, "Unknown element under <pkg>: "
1453 + parser.getName());
1454 XmlUtils.skipCurrentTag(parser);
1455 }
1456 }
1457 }
1458
Dave Burke0997c5bd2013-08-02 20:25:02 +00001459 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001460 XmlPullParserException, IOException {
1461 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Jason Monk1c7c3192014-06-26 12:52:18 -04001462 String isPrivilegedString = parser.getAttributeValue(null, "p");
1463 boolean isPrivileged = false;
1464 if (isPrivilegedString == null) {
1465 try {
1466 IPackageManager packageManager = ActivityThread.getPackageManager();
1467 if (packageManager != null) {
1468 ApplicationInfo appInfo = ActivityThread.getPackageManager()
1469 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
1470 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001471 isPrivileged = (appInfo.privateFlags
1472 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001473 }
1474 } else {
1475 // Could not load data, don't add to cache so it will be loaded later.
1476 return;
1477 }
1478 } catch (RemoteException e) {
1479 Slog.w(TAG, "Could not contact PackageManager", e);
1480 }
1481 } else {
1482 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
1483 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001484 int outerDepth = parser.getDepth();
1485 int type;
1486 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1487 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1488 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1489 continue;
1490 }
1491
1492 String tagName = parser.getName();
1493 if (tagName.equals("op")) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001494 Op op = new Op(uid, pkgName, Integer.parseInt(parser.getAttributeValue(null, "n")));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001495 String mode = parser.getAttributeValue(null, "m");
1496 if (mode != null) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001497 op.mode = Integer.parseInt(mode);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001498 }
1499 String time = parser.getAttributeValue(null, "t");
1500 if (time != null) {
1501 op.time = Long.parseLong(time);
1502 }
1503 time = parser.getAttributeValue(null, "r");
1504 if (time != null) {
1505 op.rejectTime = Long.parseLong(time);
1506 }
1507 String dur = parser.getAttributeValue(null, "d");
1508 if (dur != null) {
1509 op.duration = Integer.parseInt(dur);
1510 }
Svet Ganov99b60432015-06-27 13:15:22 -07001511 String proxyUid = parser.getAttributeValue(null, "pu");
1512 if (proxyUid != null) {
1513 op.proxyUid = Integer.parseInt(proxyUid);
1514 }
1515 String proxyPackageName = parser.getAttributeValue(null, "pp");
1516 if (proxyPackageName != null) {
1517 op.proxyPackageName = proxyPackageName;
1518 }
Svet Ganov2af57082015-07-30 08:44:20 -07001519
1520 UidState uidState = getUidStateLocked(uid, true);
1521 if (uidState.pkgOps == null) {
1522 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001523 }
Svet Ganov2af57082015-07-30 08:44:20 -07001524
1525 Ops ops = uidState.pkgOps.get(pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001526 if (ops == null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001527 ops = new Ops(pkgName, uidState, isPrivileged);
1528 uidState.pkgOps.put(pkgName, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001529 }
1530 ops.put(op.op, op);
1531 } else {
1532 Slog.w(TAG, "Unknown element under <pkg>: "
1533 + parser.getName());
1534 XmlUtils.skipCurrentTag(parser);
1535 }
1536 }
1537 }
1538
1539 void writeState() {
1540 synchronized (mFile) {
1541 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
1542
1543 FileOutputStream stream;
1544 try {
1545 stream = mFile.startWrite();
1546 } catch (IOException e) {
1547 Slog.w(TAG, "Failed to write state: " + e);
1548 return;
1549 }
1550
1551 try {
1552 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001553 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001554 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001555 out.startTag(null, "app-ops");
Svet Ganov2af57082015-07-30 08:44:20 -07001556
1557 final int uidStateCount = mUidStates.size();
1558 for (int i = 0; i < uidStateCount; i++) {
1559 UidState uidState = mUidStates.valueAt(i);
1560 if (uidState.opModes != null && uidState.opModes.size() > 0) {
1561 out.startTag(null, "uid");
1562 out.attribute(null, "n", Integer.toString(uidState.uid));
1563 SparseIntArray uidOpModes = uidState.opModes;
1564 final int opCount = uidOpModes.size();
1565 for (int j = 0; j < opCount; j++) {
1566 final int op = uidOpModes.keyAt(j);
1567 final int mode = uidOpModes.valueAt(j);
1568 out.startTag(null, "op");
1569 out.attribute(null, "n", Integer.toString(op));
1570 out.attribute(null, "m", Integer.toString(mode));
1571 out.endTag(null, "op");
1572 }
1573 out.endTag(null, "uid");
1574 }
1575 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001576
1577 if (allOps != null) {
1578 String lastPkg = null;
1579 for (int i=0; i<allOps.size(); i++) {
1580 AppOpsManager.PackageOps pkg = allOps.get(i);
1581 if (!pkg.getPackageName().equals(lastPkg)) {
1582 if (lastPkg != null) {
1583 out.endTag(null, "pkg");
1584 }
1585 lastPkg = pkg.getPackageName();
1586 out.startTag(null, "pkg");
1587 out.attribute(null, "n", lastPkg);
1588 }
1589 out.startTag(null, "uid");
1590 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04001591 synchronized (this) {
Ian Pedowitz9888e002016-03-22 16:13:48 +00001592 Ops ops = getOpsLocked(pkg.getUid(), pkg.getPackageName(), false);
Jason Monk1c7c3192014-06-26 12:52:18 -04001593 // Should always be present as the list of PackageOps is generated
1594 // from Ops.
1595 if (ops != null) {
1596 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
1597 } else {
1598 out.attribute(null, "p", Boolean.toString(false));
1599 }
1600 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001601 List<AppOpsManager.OpEntry> ops = pkg.getOps();
1602 for (int j=0; j<ops.size(); j++) {
1603 AppOpsManager.OpEntry op = ops.get(j);
1604 out.startTag(null, "op");
1605 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07001606 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001607 out.attribute(null, "m", Integer.toString(op.getMode()));
1608 }
1609 long time = op.getTime();
1610 if (time != 0) {
1611 out.attribute(null, "t", Long.toString(time));
1612 }
1613 time = op.getRejectTime();
1614 if (time != 0) {
1615 out.attribute(null, "r", Long.toString(time));
1616 }
1617 int dur = op.getDuration();
1618 if (dur != 0) {
1619 out.attribute(null, "d", Integer.toString(dur));
1620 }
Svet Ganov99b60432015-06-27 13:15:22 -07001621 int proxyUid = op.getProxyUid();
1622 if (proxyUid != -1) {
1623 out.attribute(null, "pu", Integer.toString(proxyUid));
1624 }
1625 String proxyPackageName = op.getProxyPackageName();
1626 if (proxyPackageName != null) {
1627 out.attribute(null, "pp", proxyPackageName);
1628 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001629 out.endTag(null, "op");
1630 }
1631 out.endTag(null, "uid");
1632 }
1633 if (lastPkg != null) {
1634 out.endTag(null, "pkg");
1635 }
1636 }
1637
1638 out.endTag(null, "app-ops");
1639 out.endDocument();
1640 mFile.finishWrite(stream);
1641 } catch (IOException e) {
1642 Slog.w(TAG, "Failed to write state, restoring backup.", e);
1643 mFile.failWrite(stream);
1644 }
1645 }
1646 }
1647
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001648 static class Shell extends ShellCommand {
1649 final IAppOpsService mInterface;
1650 final AppOpsService mInternal;
1651
1652 int userId = UserHandle.USER_SYSTEM;
1653 String packageName;
1654 String opStr;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001655 String modeStr;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001656 int op;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001657 int mode;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001658 int packageUid;
1659
1660 Shell(IAppOpsService iface, AppOpsService internal) {
1661 mInterface = iface;
1662 mInternal = internal;
1663 }
1664
1665 @Override
1666 public int onCommand(String cmd) {
1667 return onShellCommand(this, cmd);
1668 }
1669
1670 @Override
1671 public void onHelp() {
1672 PrintWriter pw = getOutPrintWriter();
1673 dumpCommandHelp(pw);
1674 }
1675
1676 private int strOpToOp(String op, PrintWriter err) {
1677 try {
1678 return AppOpsManager.strOpToOp(op);
1679 } catch (IllegalArgumentException e) {
1680 }
1681 try {
1682 return Integer.parseInt(op);
1683 } catch (NumberFormatException e) {
1684 }
1685 try {
1686 return AppOpsManager.strDebugOpToOp(op);
1687 } catch (IllegalArgumentException e) {
1688 err.println("Error: " + e.getMessage());
1689 return -1;
1690 }
1691 }
1692
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001693 int strModeToMode(String modeStr, PrintWriter err) {
1694 switch (modeStr) {
1695 case "allow":
1696 return AppOpsManager.MODE_ALLOWED;
1697 case "deny":
1698 return AppOpsManager.MODE_ERRORED;
1699 case "ignore":
1700 return AppOpsManager.MODE_IGNORED;
1701 case "default":
1702 return AppOpsManager.MODE_DEFAULT;
1703 }
1704 try {
1705 return Integer.parseInt(modeStr);
1706 } catch (NumberFormatException e) {
1707 }
1708 err.println("Error: Mode " + modeStr + " is not valid");
1709 return -1;
1710 }
1711
1712 int parseUserOpMode(int defMode, PrintWriter err) throws RemoteException {
1713 userId = UserHandle.USER_CURRENT;
1714 opStr = null;
1715 modeStr = null;
1716 for (String argument; (argument = getNextArg()) != null;) {
1717 if ("--user".equals(argument)) {
1718 userId = UserHandle.parseUserArg(getNextArgRequired());
1719 } else {
1720 if (opStr == null) {
1721 opStr = argument;
1722 } else if (modeStr == null) {
1723 modeStr = argument;
1724 break;
1725 }
1726 }
1727 }
1728 if (opStr == null) {
1729 err.println("Error: Operation not specified.");
1730 return -1;
1731 }
1732 op = strOpToOp(opStr, err);
1733 if (op < 0) {
1734 return -1;
1735 }
1736 if (modeStr != null) {
1737 if ((mode=strModeToMode(modeStr, err)) < 0) {
1738 return -1;
1739 }
1740 } else {
1741 mode = defMode;
1742 }
1743 return 0;
1744 }
1745
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001746 int parseUserPackageOp(boolean reqOp, PrintWriter err) throws RemoteException {
1747 userId = UserHandle.USER_CURRENT;
1748 packageName = null;
1749 opStr = null;
1750 for (String argument; (argument = getNextArg()) != null;) {
1751 if ("--user".equals(argument)) {
1752 userId = UserHandle.parseUserArg(getNextArgRequired());
1753 } else {
1754 if (packageName == null) {
1755 packageName = argument;
1756 } else if (opStr == null) {
1757 opStr = argument;
1758 break;
1759 }
1760 }
1761 }
1762 if (packageName == null) {
1763 err.println("Error: Package name not specified.");
1764 return -1;
1765 } else if (opStr == null && reqOp) {
1766 err.println("Error: Operation not specified.");
1767 return -1;
1768 }
1769 if (opStr != null) {
1770 op = strOpToOp(opStr, err);
1771 if (op < 0) {
1772 return -1;
1773 }
1774 } else {
1775 op = AppOpsManager.OP_NONE;
1776 }
1777 if (userId == UserHandle.USER_CURRENT) {
1778 userId = ActivityManager.getCurrentUser();
1779 }
1780 if ("root".equals(packageName)) {
1781 packageUid = 0;
1782 } else {
Jeff Sharkeycd654482016-01-08 17:42:11 -07001783 packageUid = AppGlobals.getPackageManager().getPackageUid(packageName,
1784 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001785 }
1786 if (packageUid < 0) {
1787 err.println("Error: No UID for " + packageName + " in user " + userId);
1788 return -1;
1789 }
1790 return 0;
1791 }
1792 }
1793
1794 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
1795 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
1796 (new Shell(this, this)).exec(this, in, out, err, args, resultReceiver);
1797 }
1798
1799 static void dumpCommandHelp(PrintWriter pw) {
1800 pw.println("AppOps service (appops) commands:");
1801 pw.println(" help");
1802 pw.println(" Print this help text.");
1803 pw.println(" set [--user <USER_ID>] <PACKAGE> <OP> <MODE>");
1804 pw.println(" Set the mode for a particular application and operation.");
1805 pw.println(" get [--user <USER_ID>] <PACKAGE> [<OP>]");
1806 pw.println(" Return the mode for a particular application and optional operation.");
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001807 pw.println(" query-op [--user <USER_ID>] <OP> [<MODE>]");
1808 pw.println(" Print all packages that currently have the given op in the given mode.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001809 pw.println(" reset [--user <USER_ID>] [<PACKAGE>]");
1810 pw.println(" Reset the given application or all applications to default modes.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001811 pw.println(" write-settings");
1812 pw.println(" Immediately write pending changes to storage.");
1813 pw.println(" read-settings");
1814 pw.println(" Read the last written settings, replacing current state in RAM.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001815 pw.println(" options:");
1816 pw.println(" <PACKAGE> an Android package name.");
1817 pw.println(" <OP> an AppOps operation.");
1818 pw.println(" <MODE> one of allow, ignore, deny, or default");
1819 pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
1820 pw.println(" specified, the current user is assumed.");
1821 }
1822
1823 static int onShellCommand(Shell shell, String cmd) {
1824 if (cmd == null) {
1825 return shell.handleDefaultCommands(cmd);
1826 }
1827 PrintWriter pw = shell.getOutPrintWriter();
1828 PrintWriter err = shell.getErrPrintWriter();
1829 try {
1830 switch (cmd) {
1831 case "set": {
1832 int res = shell.parseUserPackageOp(true, err);
1833 if (res < 0) {
1834 return res;
1835 }
1836 String modeStr = shell.getNextArg();
1837 if (modeStr == null) {
1838 err.println("Error: Mode not specified.");
1839 return -1;
1840 }
1841
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001842 final int mode = shell.strModeToMode(modeStr, err);
1843 if (mode < 0) {
1844 return -1;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001845 }
1846
1847 shell.mInterface.setMode(shell.op, shell.packageUid, shell.packageName, mode);
1848 return 0;
1849 }
1850 case "get": {
1851 int res = shell.parseUserPackageOp(false, err);
1852 if (res < 0) {
1853 return res;
1854 }
1855
1856 List<AppOpsManager.PackageOps> ops = shell.mInterface.getOpsForPackage(
1857 shell.packageUid, shell.packageName,
1858 shell.op != AppOpsManager.OP_NONE ? new int[] {shell.op} : null);
1859 if (ops == null || ops.size() <= 0) {
1860 pw.println("No operations.");
1861 return 0;
1862 }
1863 final long now = System.currentTimeMillis();
1864 for (int i=0; i<ops.size(); i++) {
1865 List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
1866 for (int j=0; j<entries.size(); j++) {
1867 AppOpsManager.OpEntry ent = entries.get(j);
1868 pw.print(AppOpsManager.opToName(ent.getOp()));
1869 pw.print(": ");
1870 switch (ent.getMode()) {
1871 case AppOpsManager.MODE_ALLOWED:
1872 pw.print("allow");
1873 break;
1874 case AppOpsManager.MODE_IGNORED:
1875 pw.print("ignore");
1876 break;
1877 case AppOpsManager.MODE_ERRORED:
1878 pw.print("deny");
1879 break;
1880 case AppOpsManager.MODE_DEFAULT:
1881 pw.print("default");
1882 break;
1883 default:
1884 pw.print("mode=");
1885 pw.print(ent.getMode());
1886 break;
1887 }
1888 if (ent.getTime() != 0) {
1889 pw.print("; time=");
1890 TimeUtils.formatDuration(now - ent.getTime(), pw);
1891 pw.print(" ago");
1892 }
1893 if (ent.getRejectTime() != 0) {
1894 pw.print("; rejectTime=");
1895 TimeUtils.formatDuration(now - ent.getRejectTime(), pw);
1896 pw.print(" ago");
1897 }
1898 if (ent.getDuration() == -1) {
1899 pw.print(" (running)");
1900 } else if (ent.getDuration() != 0) {
1901 pw.print("; duration=");
1902 TimeUtils.formatDuration(ent.getDuration(), pw);
1903 }
1904 pw.println();
1905 }
1906 }
1907 return 0;
1908 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001909 case "query-op": {
1910 int res = shell.parseUserOpMode(AppOpsManager.MODE_IGNORED, err);
1911 if (res < 0) {
1912 return res;
1913 }
1914 List<AppOpsManager.PackageOps> ops = shell.mInterface.getPackagesForOps(
1915 new int[] {shell.op});
1916 if (ops == null || ops.size() <= 0) {
1917 pw.println("No operations.");
1918 return 0;
1919 }
1920 for (int i=0; i<ops.size(); i++) {
1921 final AppOpsManager.PackageOps pkg = ops.get(i);
1922 boolean hasMatch = false;
1923 final List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
1924 for (int j=0; j<entries.size(); j++) {
1925 AppOpsManager.OpEntry ent = entries.get(j);
1926 if (ent.getOp() == shell.op && ent.getMode() == shell.mode) {
1927 hasMatch = true;
1928 break;
1929 }
1930 }
1931 if (hasMatch) {
1932 pw.println(pkg.getPackageName());
1933 }
1934 }
1935 return 0;
1936 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001937 case "reset": {
1938 String packageName = null;
1939 int userId = UserHandle.USER_CURRENT;
1940 for (String argument; (argument = shell.getNextArg()) != null;) {
1941 if ("--user".equals(argument)) {
1942 String userStr = shell.getNextArgRequired();
1943 userId = UserHandle.parseUserArg(userStr);
1944 } else {
1945 if (packageName == null) {
1946 packageName = argument;
1947 } else {
1948 err.println("Error: Unsupported argument: " + argument);
1949 return -1;
1950 }
1951 }
1952 }
1953
1954 if (userId == UserHandle.USER_CURRENT) {
1955 userId = ActivityManager.getCurrentUser();
1956 }
1957
1958 shell.mInterface.resetAllModes(userId, packageName);
1959 pw.print("Reset all modes for: ");
1960 if (userId == UserHandle.USER_ALL) {
1961 pw.print("all users");
1962 } else {
1963 pw.print("user "); pw.print(userId);
1964 }
1965 pw.print(", ");
1966 if (packageName == null) {
1967 pw.println("all packages");
1968 } else {
1969 pw.print("package "); pw.println(packageName);
1970 }
1971 return 0;
1972 }
1973 case "write-settings": {
1974 shell.mInternal.mContext.enforcePermission(
1975 android.Manifest.permission.UPDATE_APP_OPS_STATS,
1976 Binder.getCallingPid(), Binder.getCallingUid(), null);
1977 long token = Binder.clearCallingIdentity();
1978 try {
1979 synchronized (shell.mInternal) {
1980 shell.mInternal.mHandler.removeCallbacks(shell.mInternal.mWriteRunner);
1981 }
1982 shell.mInternal.writeState();
1983 pw.println("Current settings written.");
1984 } finally {
1985 Binder.restoreCallingIdentity(token);
1986 }
1987 return 0;
1988 }
1989 case "read-settings": {
1990 shell.mInternal.mContext.enforcePermission(
1991 android.Manifest.permission.UPDATE_APP_OPS_STATS,
1992 Binder.getCallingPid(), Binder.getCallingUid(), null);
1993 long token = Binder.clearCallingIdentity();
1994 try {
1995 shell.mInternal.readState();
1996 pw.println("Last settings read.");
1997 } finally {
1998 Binder.restoreCallingIdentity(token);
1999 }
2000 return 0;
2001 }
2002 default:
2003 return shell.handleDefaultCommands(cmd);
2004 }
2005 } catch (RemoteException e) {
2006 pw.println("Remote exception: " + e);
2007 }
2008 return -1;
2009 }
2010
2011 private void dumpHelp(PrintWriter pw) {
2012 pw.println("AppOps service (appops) dump options:");
2013 pw.println(" none");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002014 }
2015
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002016 @Override
2017 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2018 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2019 != PackageManager.PERMISSION_GRANTED) {
2020 pw.println("Permission Denial: can't dump ApOps service from from pid="
2021 + Binder.getCallingPid()
2022 + ", uid=" + Binder.getCallingUid());
2023 return;
2024 }
2025
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002026 if (args != null) {
2027 for (int i=0; i<args.length; i++) {
2028 String arg = args[i];
2029 if ("-h".equals(arg)) {
2030 dumpHelp(pw);
2031 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07002032 } else if ("-a".equals(arg)) {
2033 // dump all data
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002034 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
2035 pw.println("Unknown option: " + arg);
2036 return;
2037 } else {
2038 pw.println("Unknown command: " + arg);
2039 return;
2040 }
2041 }
2042 }
2043
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002044 synchronized (this) {
2045 pw.println("Current AppOps Service state:");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002046 final long now = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002047 boolean needSep = false;
2048 if (mOpModeWatchers.size() > 0) {
2049 needSep = true;
2050 pw.println(" Op mode watchers:");
2051 for (int i=0; i<mOpModeWatchers.size(); i++) {
2052 pw.print(" Op "); pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
2053 pw.println(":");
2054 ArrayList<Callback> callbacks = mOpModeWatchers.valueAt(i);
2055 for (int j=0; j<callbacks.size(); j++) {
2056 pw.print(" #"); pw.print(j); pw.print(": ");
2057 pw.println(callbacks.get(j));
2058 }
2059 }
2060 }
2061 if (mPackageModeWatchers.size() > 0) {
2062 needSep = true;
2063 pw.println(" Package mode watchers:");
2064 for (int i=0; i<mPackageModeWatchers.size(); i++) {
2065 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
2066 pw.println(":");
2067 ArrayList<Callback> callbacks = mPackageModeWatchers.valueAt(i);
2068 for (int j=0; j<callbacks.size(); j++) {
2069 pw.print(" #"); pw.print(j); pw.print(": ");
2070 pw.println(callbacks.get(j));
2071 }
2072 }
2073 }
2074 if (mModeWatchers.size() > 0) {
2075 needSep = true;
2076 pw.println(" All mode watchers:");
2077 for (int i=0; i<mModeWatchers.size(); i++) {
2078 pw.print(" "); pw.print(mModeWatchers.keyAt(i));
2079 pw.print(" -> "); pw.println(mModeWatchers.valueAt(i));
2080 }
2081 }
2082 if (mClients.size() > 0) {
2083 needSep = true;
2084 pw.println(" Clients:");
2085 for (int i=0; i<mClients.size(); i++) {
2086 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
2087 ClientState cs = mClients.valueAt(i);
2088 pw.print(" "); pw.println(cs);
2089 if (cs.mStartedOps != null && cs.mStartedOps.size() > 0) {
2090 pw.println(" Started ops:");
2091 for (int j=0; j<cs.mStartedOps.size(); j++) {
2092 Op op = cs.mStartedOps.get(j);
2093 pw.print(" "); pw.print("uid="); pw.print(op.uid);
2094 pw.print(" pkg="); pw.print(op.packageName);
2095 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
2096 }
2097 }
2098 }
2099 }
John Spurlock1af30c72014-03-10 08:33:35 -04002100 if (mAudioRestrictions.size() > 0) {
2101 boolean printedHeader = false;
2102 for (int o=0; o<mAudioRestrictions.size(); o++) {
2103 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
2104 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
2105 for (int i=0; i<restrictions.size(); i++) {
2106 if (!printedHeader){
2107 pw.println(" Audio Restrictions:");
2108 printedHeader = true;
2109 needSep = true;
2110 }
John Spurlock7b414672014-07-18 13:02:39 -04002111 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04002112 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04002113 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04002114 Restriction r = restrictions.valueAt(i);
2115 pw.print(": mode="); pw.println(r.mode);
2116 if (!r.exceptionPackages.isEmpty()) {
2117 pw.println(" Exceptions:");
2118 for (int j=0; j<r.exceptionPackages.size(); j++) {
2119 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
2120 }
2121 }
2122 }
2123 }
2124 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002125 if (needSep) {
2126 pw.println();
2127 }
Svet Ganov2af57082015-07-30 08:44:20 -07002128 for (int i=0; i<mUidStates.size(); i++) {
2129 UidState uidState = mUidStates.valueAt(i);
2130
2131 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
2132
2133 SparseIntArray opModes = uidState.opModes;
2134 if (opModes != null) {
2135 final int opModeCount = opModes.size();
2136 for (int j = 0; j < opModeCount; j++) {
2137 final int code = opModes.keyAt(j);
2138 final int mode = opModes.valueAt(j);
2139 pw.print(" "); pw.print(AppOpsManager.opToName(code));
2140 pw.print(": mode="); pw.println(mode);
2141 }
2142 }
2143
2144 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
2145 if (pkgOps == null) {
2146 continue;
2147 }
2148
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002149 for (Ops ops : pkgOps.values()) {
2150 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
2151 for (int j=0; j<ops.size(); j++) {
2152 Op op = ops.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002153 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
2154 pw.print(": mode="); pw.print(op.mode);
2155 if (op.time != 0) {
2156 pw.print("; time="); TimeUtils.formatDuration(now-op.time, pw);
2157 pw.print(" ago");
2158 }
2159 if (op.rejectTime != 0) {
2160 pw.print("; rejectTime="); TimeUtils.formatDuration(now-op.rejectTime, pw);
2161 pw.print(" ago");
2162 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002163 if (op.duration == -1) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002164 pw.print(" (running)");
2165 } else if (op.duration != 0) {
2166 pw.print("; duration="); TimeUtils.formatDuration(op.duration, pw);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002167 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002168 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002169 }
2170 }
2171 }
2172 }
2173 }
John Spurlock1af30c72014-03-10 08:33:35 -04002174
2175 private static final class Restriction {
2176 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
2177 int mode;
2178 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
2179 }
Jason Monk62062992014-05-06 09:55:28 -04002180
2181 @Override
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002182 public void setUserRestrictions(Bundle restrictions, IBinder token, int userHandle) {
Jason Monk62062992014-05-06 09:55:28 -04002183 checkSystemUid("setUserRestrictions");
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002184 Preconditions.checkNotNull(token);
2185 final boolean[] opRestrictions = getOrCreateUserRestrictionsForToken(token, userHandle);
Jason Monk62062992014-05-06 09:55:28 -04002186 for (int i = 0; i < opRestrictions.length; ++i) {
2187 String restriction = AppOpsManager.opToRestriction(i);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002188 final boolean restricted = restriction != null
2189 && restrictions.getBoolean(restriction, false);
2190 setUserRestrictionNoCheck(i, restricted, token, userHandle);
2191 }
2192 }
2193
2194 @Override
Ruben Brunk29931bc2016-03-11 00:24:26 -08002195 public void setUserRestriction(int code, boolean restricted, IBinder token, int userHandle,
2196 String[] exceptionPackages) {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002197 if (Binder.getCallingPid() != Process.myPid()) {
2198 mContext.enforcePermission(Manifest.permission.MANAGE_APP_OPS_RESTRICTIONS,
2199 Binder.getCallingPid(), Binder.getCallingUid(), null);
2200 }
2201 if (userHandle != UserHandle.getCallingUserId()) {
2202 if (mContext.checkCallingOrSelfPermission(Manifest.permission
2203 .INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
2204 && mContext.checkCallingOrSelfPermission(Manifest.permission
2205 .INTERACT_ACROSS_USERS) != PackageManager.PERMISSION_GRANTED) {
2206 throw new SecurityException("Need INTERACT_ACROSS_USERS_FULL or"
2207 + " INTERACT_ACROSS_USERS to interact cross user ");
Jason Monk62062992014-05-06 09:55:28 -04002208 }
2209 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002210 verifyIncomingOp(code);
2211 Preconditions.checkNotNull(token);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002212 setUserRestrictionNoCheck(code, restricted, token, userHandle, exceptionPackages);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002213 }
2214
2215 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
2216 int userHandle) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002217 setUserRestrictionNoCheck(code, restricted, token, userHandle, /*exceptionPackages*/null);
2218 }
2219
2220 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
2221 int userHandle, String[] exceptionPackages) {
2222
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002223 final boolean[] opRestrictions = getOrCreateUserRestrictionsForToken(token, userHandle);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002224
2225 if (restricted) {
2226 final SparseArray<ArraySet<String>> opExceptions =
2227 getUserPackageExemptionsForToken(token, userHandle);
2228
Ruben Brunk29931bc2016-03-11 00:24:26 -08002229 ArraySet<String> exceptions = opExceptions.get(code);
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002230 if (exceptionPackages != null && exceptionPackages.length > 0) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002231 if (exceptions == null) {
2232 exceptions = new ArraySet<>(exceptionPackages.length);
2233 opExceptions.put(code, exceptions);
2234 } else {
2235 exceptions.clear();
2236 }
2237
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002238 for (String p : exceptionPackages) {
2239 exceptions.add(p);
2240 }
2241 } else {
2242 opExceptions.remove(code);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002243 }
2244 }
2245
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002246 if (opRestrictions[code] == restricted) {
2247 return;
2248 }
2249 opRestrictions[code] = restricted;
2250 if (!restricted) {
2251 pruneUserRestrictionsForToken(token, userHandle);
2252 }
2253
2254 final ArrayList<Callback> clonedCallbacks;
2255 synchronized (this) {
2256 ArrayList<Callback> callbacks = mOpModeWatchers.get(code);
2257 if (callbacks == null) {
2258 return;
2259 }
2260 clonedCallbacks = new ArrayList<>(callbacks);
2261 }
2262
2263 // There are components watching for mode changes such as window manager
2264 // and location manager which are in our process. The callbacks in these
2265 // components may require permissions our remote caller does not have.
2266 final long identity = Binder.clearCallingIdentity();
2267 try {
2268 final int callbackCount = clonedCallbacks.size();
2269 for (int i = 0; i < callbackCount; i++) {
2270 Callback callback = clonedCallbacks.get(i);
2271 try {
2272 callback.mCallback.opChanged(code, -1, null);
2273 } catch (RemoteException e) {
2274 Log.w(TAG, "Error dispatching op op change", e);
2275 }
2276 }
2277 } finally {
2278 Binder.restoreCallingIdentity(identity);
2279 }
Jason Monk62062992014-05-06 09:55:28 -04002280 }
2281
2282 @Override
2283 public void removeUser(int userHandle) throws RemoteException {
2284 checkSystemUid("removeUser");
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002285 final int tokenCount = mOpUserRestrictions.size();
2286 for (int i = tokenCount - 1; i >= 0; i--) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002287 SparseArray<Pair<boolean[], SparseArray<ArraySet<String>>>> opRestrictions =
2288 mOpUserRestrictions.valueAt(i);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002289 if (opRestrictions != null) {
2290 opRestrictions.remove(userHandle);
2291 if (opRestrictions.size() <= 0) {
2292 mOpUserRestrictions.removeAt(i);
2293 }
2294 }
2295 }
2296 }
2297
2298
2299 private void pruneUserRestrictionsForToken(IBinder token, int userHandle) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002300 SparseArray<Pair<boolean[], SparseArray<ArraySet<String>>>> perTokenRestrictions =
2301 mOpUserRestrictions.get(token);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002302 if (perTokenRestrictions != null) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002303 final Pair<boolean[], SparseArray<ArraySet<String>>> restrictions =
2304 perTokenRestrictions.get(userHandle);
2305
2306 if (restrictions != null) {
2307 final boolean[] opRestrictions = restrictions.first;
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002308 final SparseArray<ArraySet<String>> opExceptions = restrictions.second;
2309 boolean stillHasRestrictions = false;
Ruben Brunk29931bc2016-03-11 00:24:26 -08002310 if (opRestrictions != null) {
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002311 for (int i = 0; i < opRestrictions.length; i++) {
2312 boolean restriction = opRestrictions[i];
Ruben Brunk29931bc2016-03-11 00:24:26 -08002313 if (restriction) {
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002314 stillHasRestrictions = true;
2315 } else {
2316 opExceptions.remove(i);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002317 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002318 }
2319 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002320
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002321 if (stillHasRestrictions) {
2322 return;
2323 }
2324
Ruben Brunk29931bc2016-03-11 00:24:26 -08002325 // No restrictions set for this client
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002326 perTokenRestrictions.remove(userHandle);
2327 if (perTokenRestrictions.size() <= 0) {
2328 mOpUserRestrictions.remove(token);
2329 }
2330 }
2331 }
2332 }
2333
Ruben Brunk29931bc2016-03-11 00:24:26 -08002334 /**
2335 * Get or create the user restrictions array for a given client if it doesn't already exist.
2336 *
2337 * @param token the binder client creating the restriction.
2338 * @param userHandle the user handle to create a restriction for.
2339 *
2340 * @return the array of restriction states for each AppOps code.
2341 */
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002342 private boolean[] getOrCreateUserRestrictionsForToken(IBinder token, int userHandle) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002343 SparseArray<Pair<boolean[], SparseArray<ArraySet<String>>>> perTokenRestrictions =
2344 mOpUserRestrictions.get(token);
2345
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002346 if (perTokenRestrictions == null) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002347 perTokenRestrictions =
2348 new SparseArray<Pair<boolean[], SparseArray<ArraySet<String>>>>();
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002349 mOpUserRestrictions.put(token, perTokenRestrictions);
2350 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002351
2352 Pair<boolean[], SparseArray<ArraySet<String>>> restrictions =
2353 perTokenRestrictions.get(userHandle);
2354
2355 if (restrictions == null) {
2356 restrictions = new Pair<boolean[], SparseArray<ArraySet<String>>>(
2357 new boolean[AppOpsManager._NUM_OP], new SparseArray<ArraySet<String>>());
2358 perTokenRestrictions.put(userHandle, restrictions);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002359 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002360
2361 return restrictions.first;
2362 }
2363
2364 /**
2365 * Get the per-package exemptions for each AppOps code for a given client and userHandle.
2366 *
2367 * @param token the binder client to get the exemptions for.
2368 * @param userHandle the user handle to get the exemptions for.
2369 *
2370 * @return a mapping from the AppOps code to a set of packages exempt for that code.
2371 */
2372 private SparseArray<ArraySet<String>> getUserPackageExemptionsForToken(IBinder token,
2373 int userHandle) {
2374 SparseArray<Pair<boolean[], SparseArray<ArraySet<String>>>> perTokenRestrictions =
2375 mOpUserRestrictions.get(token);
2376
2377 if (perTokenRestrictions == null) {
2378 return null; // Don't create user restrictions accidentally
2379 }
2380
2381 Pair<boolean[], SparseArray<ArraySet<String>>> restrictions =
2382 perTokenRestrictions.get(userHandle);
2383
2384 if (restrictions == null) {
2385 return null; // Don't create user restrictions accidentally
2386 }
2387
2388 return restrictions.second;
Jason Monk62062992014-05-06 09:55:28 -04002389 }
2390
2391 private void checkSystemUid(String function) {
2392 int uid = Binder.getCallingUid();
2393 if (uid != Process.SYSTEM_UID) {
2394 throw new SecurityException(function + " must by called by the system");
2395 }
2396 }
2397
Svet Ganov2af57082015-07-30 08:44:20 -07002398 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07002399 String[] packageNames = null;
Svet Ganov2af57082015-07-30 08:44:20 -07002400 try {
riddle_hsu40b300f2015-11-23 13:22:03 +08002401 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -07002402 } catch (RemoteException e) {
2403 /* ignore - local call */
2404 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07002405 if (packageNames == null) {
2406 return EmptyArray.STRING;
2407 }
2408 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07002409 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002410}