blob: 32f2d593f670b699a8e5ec469755d308eeb6497d [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;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080060import android.util.Slog;
61import android.util.SparseArray;
Svet Ganov2af57082015-07-30 08:44:20 -070062import android.util.SparseIntArray;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080063import android.util.TimeUtils;
Dianne Hackborn35654b62013-01-14 17:38:02 -080064import android.util.Xml;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080065
66import com.android.internal.app.IAppOpsService;
Dianne Hackbornc2293022013-02-06 23:14:49 -080067import com.android.internal.app.IAppOpsCallback;
Svet Ganov6ee871e2015-07-10 14:29:33 -070068import com.android.internal.os.Zygote;
Svet Ganov2af57082015-07-30 08:44:20 -070069import com.android.internal.util.ArrayUtils;
Dianne Hackborn35654b62013-01-14 17:38:02 -080070import com.android.internal.util.FastXmlSerializer;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080071import com.android.internal.util.Preconditions;
Dianne Hackborn35654b62013-01-14 17:38:02 -080072import com.android.internal.util.XmlUtils;
73
Svet Ganov2af57082015-07-30 08:44:20 -070074import libcore.util.EmptyArray;
Dianne Hackborn35654b62013-01-14 17:38:02 -080075import org.xmlpull.v1.XmlPullParser;
76import org.xmlpull.v1.XmlPullParserException;
77import org.xmlpull.v1.XmlSerializer;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080078
79public class AppOpsService extends IAppOpsService.Stub {
80 static final String TAG = "AppOps";
Dianne Hackborn35654b62013-01-14 17:38:02 -080081 static final boolean DEBUG = false;
82
83 // Write at most every 30 minutes.
84 static final long WRITE_DELAY = DEBUG ? 1000 : 30*60*1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080085
86 Context mContext;
87 final AtomicFile mFile;
Dianne Hackborn35654b62013-01-14 17:38:02 -080088 final Handler mHandler;
89
90 boolean mWriteScheduled;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -080091 boolean mFastWriteScheduled;
Dianne Hackborn35654b62013-01-14 17:38:02 -080092 final Runnable mWriteRunner = new Runnable() {
93 public void run() {
94 synchronized (AppOpsService.this) {
95 mWriteScheduled = false;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -080096 mFastWriteScheduled = false;
Dianne Hackborn35654b62013-01-14 17:38:02 -080097 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
98 @Override protected Void doInBackground(Void... params) {
99 writeState();
100 return null;
101 }
102 };
103 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
104 }
105 }
106 };
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800107
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800108 private final SparseArray<UidState> mUidStates = new SparseArray<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800109
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800110 /** These are app op restrictions imposed per user from various parties */
111 private final ArrayMap<IBinder, SparseArray<boolean[]>> mOpUserRestrictions = new ArrayMap<>();
Jason Monk62062992014-05-06 09:55:28 -0400112
Svet Ganov2af57082015-07-30 08:44:20 -0700113 private static final class UidState {
114 public final int uid;
115 public ArrayMap<String, Ops> pkgOps;
116 public SparseIntArray opModes;
117
118 public UidState(int uid) {
119 this.uid = uid;
120 }
121
122 public void clear() {
123 pkgOps = null;
124 opModes = null;
125 }
126
127 public boolean isDefault() {
128 return (pkgOps == null || pkgOps.isEmpty())
129 && (opModes == null || opModes.size() <= 0);
130 }
131 }
132
Dianne Hackbornc2293022013-02-06 23:14:49 -0800133 public final static class Ops extends SparseArray<Op> {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800134 public final String packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700135 public final UidState uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400136 public final boolean isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800137
Svet Ganov2af57082015-07-30 08:44:20 -0700138 public Ops(String _packageName, UidState _uidState, boolean _isPrivileged) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800139 packageName = _packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700140 uidState = _uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400141 isPrivileged = _isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800142 }
143 }
144
Dianne Hackbornc2293022013-02-06 23:14:49 -0800145 public final static class Op {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700146 public final int uid;
147 public final String packageName;
Svet Ganov99b60432015-06-27 13:15:22 -0700148 public int proxyUid = -1;
149 public String proxyPackageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800150 public final int op;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800151 public int mode;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800152 public int duration;
153 public long time;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800154 public long rejectTime;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800155 public int nesting;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800156
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700157 public Op(int _uid, String _packageName, int _op) {
158 uid = _uid;
159 packageName = _packageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800160 op = _op;
David Braunf5d83192013-09-16 13:43:51 -0700161 mode = AppOpsManager.opToDefaultMode(op);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800162 }
163 }
164
Dianne Hackbornc2293022013-02-06 23:14:49 -0800165 final SparseArray<ArrayList<Callback>> mOpModeWatchers
166 = new SparseArray<ArrayList<Callback>>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700167 final ArrayMap<String, ArrayList<Callback>> mPackageModeWatchers
168 = new ArrayMap<String, ArrayList<Callback>>();
169 final ArrayMap<IBinder, Callback> mModeWatchers
170 = new ArrayMap<IBinder, Callback>();
John Spurlock1af30c72014-03-10 08:33:35 -0400171 final SparseArray<SparseArray<Restriction>> mAudioRestrictions
172 = new SparseArray<SparseArray<Restriction>>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800173
174 public final class Callback implements DeathRecipient {
175 final IAppOpsCallback mCallback;
176
177 public Callback(IAppOpsCallback callback) {
178 mCallback = callback;
179 try {
180 mCallback.asBinder().linkToDeath(this, 0);
181 } catch (RemoteException e) {
182 }
183 }
184
185 public void unlinkToDeath() {
186 mCallback.asBinder().unlinkToDeath(this, 0);
187 }
188
189 @Override
190 public void binderDied() {
191 stopWatchingMode(mCallback);
192 }
193 }
194
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700195 final ArrayMap<IBinder, ClientState> mClients = new ArrayMap<IBinder, ClientState>();
196
197 public final class ClientState extends Binder implements DeathRecipient {
198 final IBinder mAppToken;
199 final int mPid;
200 final ArrayList<Op> mStartedOps;
201
202 public ClientState(IBinder appToken) {
203 mAppToken = appToken;
204 mPid = Binder.getCallingPid();
205 if (appToken instanceof Binder) {
206 // For local clients, there is no reason to track them.
207 mStartedOps = null;
208 } else {
209 mStartedOps = new ArrayList<Op>();
210 try {
211 mAppToken.linkToDeath(this, 0);
212 } catch (RemoteException e) {
213 }
214 }
215 }
216
217 @Override
218 public String toString() {
219 return "ClientState{" +
220 "mAppToken=" + mAppToken +
221 ", " + (mStartedOps != null ? ("pid=" + mPid) : "local") +
222 '}';
223 }
224
225 @Override
226 public void binderDied() {
227 synchronized (AppOpsService.this) {
228 for (int i=mStartedOps.size()-1; i>=0; i--) {
229 finishOperationLocked(mStartedOps.get(i));
230 }
231 mClients.remove(mAppToken);
232 }
233 }
234 }
235
Jeff Brown6f357d32014-01-15 20:40:55 -0800236 public AppOpsService(File storagePath, Handler handler) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800237 mFile = new AtomicFile(storagePath);
Jeff Brown6f357d32014-01-15 20:40:55 -0800238 mHandler = handler;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800239 readState();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800240 }
David Braunf5d83192013-09-16 13:43:51 -0700241
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800242 public void publish(Context context) {
243 mContext = context;
244 ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
245 }
246
Dianne Hackborn514074f2013-02-11 10:52:46 -0800247 public void systemReady() {
248 synchronized (this) {
249 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700250 for (int i = mUidStates.size() - 1; i >= 0; i--) {
251 UidState uidState = mUidStates.valueAt(i);
252
253 String[] packageNames = getPackagesForUid(uidState.uid);
254 if (ArrayUtils.isEmpty(packageNames)) {
255 uidState.clear();
256 mUidStates.removeAt(i);
257 changed = true;
258 continue;
259 }
260
261 ArrayMap<String, Ops> pkgs = uidState.pkgOps;
262 if (pkgs == null) {
263 continue;
264 }
265
Dianne Hackborn514074f2013-02-11 10:52:46 -0800266 Iterator<Ops> it = pkgs.values().iterator();
267 while (it.hasNext()) {
268 Ops ops = it.next();
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700269 int curUid = -1;
Dianne Hackborn514074f2013-02-11 10:52:46 -0800270 try {
Jeff Sharkeycd654482016-01-08 17:42:11 -0700271 curUid = AppGlobals.getPackageManager().getPackageUid(ops.packageName,
272 PackageManager.MATCH_UNINSTALLED_PACKAGES,
Svet Ganov2af57082015-07-30 08:44:20 -0700273 UserHandle.getUserId(ops.uidState.uid));
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700274 } catch (RemoteException ignored) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800275 }
Svet Ganov2af57082015-07-30 08:44:20 -0700276 if (curUid != ops.uidState.uid) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800277 Slog.i(TAG, "Pruning old package " + ops.packageName
Svet Ganov2af57082015-07-30 08:44:20 -0700278 + "/" + ops.uidState + ": new uid=" + curUid);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800279 it.remove();
280 changed = true;
281 }
282 }
Svet Ganov2af57082015-07-30 08:44:20 -0700283
284 if (uidState.isDefault()) {
285 mUidStates.removeAt(i);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800286 }
287 }
288 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800289 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800290 }
291 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700292
293 MountServiceInternal mountServiceInternal = LocalServices.getService(
294 MountServiceInternal.class);
295 mountServiceInternal.addExternalStoragePolicy(
296 new MountServiceInternal.ExternalStorageMountPolicy() {
297 @Override
298 public int getMountMode(int uid, String packageName) {
299 if (Process.isIsolated(uid)) {
300 return Zygote.MOUNT_EXTERNAL_NONE;
301 }
302 if (noteOperation(AppOpsManager.OP_READ_EXTERNAL_STORAGE, uid,
303 packageName) != AppOpsManager.MODE_ALLOWED) {
304 return Zygote.MOUNT_EXTERNAL_NONE;
305 }
306 if (noteOperation(AppOpsManager.OP_WRITE_EXTERNAL_STORAGE, uid,
307 packageName) != AppOpsManager.MODE_ALLOWED) {
308 return Zygote.MOUNT_EXTERNAL_READ;
309 }
310 return Zygote.MOUNT_EXTERNAL_WRITE;
311 }
312
313 @Override
314 public boolean hasExternalStorage(int uid, String packageName) {
315 final int mountMode = getMountMode(uid, packageName);
316 return mountMode == Zygote.MOUNT_EXTERNAL_READ
317 || mountMode == Zygote.MOUNT_EXTERNAL_WRITE;
318 }
319 });
Dianne Hackborn514074f2013-02-11 10:52:46 -0800320 }
321
322 public void packageRemoved(int uid, String packageName) {
323 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700324 UidState uidState = mUidStates.get(uid);
325 if (uidState == null) {
326 return;
327 }
328
329 boolean changed = false;
330
331 // Remove any package state if such.
332 if (uidState.pkgOps != null && uidState.pkgOps.remove(packageName) != null) {
333 changed = true;
334 }
335
336 // If we just nuked the last package state check if the UID is valid.
337 if (changed && uidState.pkgOps.isEmpty()
338 && getPackagesForUid(uid).length <= 0) {
339 mUidStates.remove(uid);
340 }
341
342 if (changed) {
343 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800344 }
345 }
346 }
347
348 public void uidRemoved(int uid) {
349 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700350 if (mUidStates.indexOfKey(uid) >= 0) {
351 mUidStates.remove(uid);
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800352 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800353 }
354 }
355 }
356
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800357 public void shutdown() {
358 Slog.w(TAG, "Writing app ops before shutdown...");
Dianne Hackborn35654b62013-01-14 17:38:02 -0800359 boolean doWrite = false;
360 synchronized (this) {
361 if (mWriteScheduled) {
362 mWriteScheduled = false;
363 doWrite = true;
364 }
365 }
366 if (doWrite) {
367 writeState();
368 }
369 }
370
Dianne Hackborn72e39832013-01-18 18:36:09 -0800371 private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
372 ArrayList<AppOpsManager.OpEntry> resOps = null;
373 if (ops == null) {
374 resOps = new ArrayList<AppOpsManager.OpEntry>();
375 for (int j=0; j<pkgOps.size(); j++) {
376 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800377 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Svet Ganov99b60432015-06-27 13:15:22 -0700378 curOp.rejectTime, curOp.duration, curOp.proxyUid,
379 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800380 }
381 } else {
382 for (int j=0; j<ops.length; j++) {
383 Op curOp = pkgOps.get(ops[j]);
384 if (curOp != null) {
385 if (resOps == null) {
386 resOps = new ArrayList<AppOpsManager.OpEntry>();
387 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800388 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Svet Ganov99b60432015-06-27 13:15:22 -0700389 curOp.rejectTime, curOp.duration, curOp.proxyUid,
390 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800391 }
392 }
393 }
394 return resOps;
395 }
396
Dianne Hackborn35654b62013-01-14 17:38:02 -0800397 @Override
398 public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
399 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
400 Binder.getCallingPid(), Binder.getCallingUid(), null);
401 ArrayList<AppOpsManager.PackageOps> res = null;
402 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700403 final int uidStateCount = mUidStates.size();
404 for (int i = 0; i < uidStateCount; i++) {
405 UidState uidState = mUidStates.valueAt(i);
406 if (uidState.pkgOps == null || uidState.pkgOps.isEmpty()) {
407 continue;
408 }
409 ArrayMap<String, Ops> packages = uidState.pkgOps;
410 final int packageCount = packages.size();
411 for (int j = 0; j < packageCount; j++) {
412 Ops pkgOps = packages.valueAt(j);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800413 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800414 if (resOps != null) {
415 if (res == null) {
416 res = new ArrayList<AppOpsManager.PackageOps>();
417 }
418 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700419 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800420 res.add(resPackage);
421 }
422 }
423 }
424 }
425 return res;
426 }
427
428 @Override
Dianne Hackborn72e39832013-01-18 18:36:09 -0800429 public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
430 int[] ops) {
431 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
432 Binder.getCallingPid(), Binder.getCallingUid(), null);
433 synchronized (this) {
434 Ops pkgOps = getOpsLocked(uid, packageName, false);
435 if (pkgOps == null) {
436 return null;
437 }
438 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
439 if (resOps == null) {
440 return null;
441 }
442 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
443 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700444 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800445 res.add(resPackage);
446 return res;
447 }
448 }
449
Dianne Hackborn607b4142013-08-02 18:10:10 -0700450 private void pruneOp(Op op, int uid, String packageName) {
451 if (op.time == 0 && op.rejectTime == 0) {
452 Ops ops = getOpsLocked(uid, packageName, false);
453 if (ops != null) {
454 ops.remove(op.op);
455 if (ops.size() <= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -0700456 UidState uidState = ops.uidState;
457 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700458 if (pkgOps != null) {
459 pkgOps.remove(ops.packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700460 if (pkgOps.isEmpty()) {
461 uidState.pkgOps = null;
462 }
463 if (uidState.isDefault()) {
464 mUidStates.remove(uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700465 }
466 }
467 }
468 }
469 }
470 }
471
Dianne Hackborn72e39832013-01-18 18:36:09 -0800472 @Override
Svet Ganov2af57082015-07-30 08:44:20 -0700473 public void setUidMode(int code, int uid, int mode) {
474 if (Binder.getCallingPid() != Process.myPid()) {
475 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
476 Binder.getCallingPid(), Binder.getCallingUid(), null);
477 }
478 verifyIncomingOp(code);
479 code = AppOpsManager.opToSwitch(code);
480
481 synchronized (this) {
482 final int defaultMode = AppOpsManager.opToDefaultMode(code);
483
484 UidState uidState = getUidStateLocked(uid, false);
485 if (uidState == null) {
486 if (mode == defaultMode) {
487 return;
488 }
489 uidState = new UidState(uid);
490 uidState.opModes = new SparseIntArray();
491 uidState.opModes.put(code, mode);
492 mUidStates.put(uid, uidState);
493 scheduleWriteLocked();
494 } else if (uidState.opModes == null) {
495 if (mode != defaultMode) {
496 uidState.opModes = new SparseIntArray();
497 uidState.opModes.put(code, mode);
498 scheduleWriteLocked();
499 }
500 } else {
501 if (uidState.opModes.get(code) == mode) {
502 return;
503 }
504 if (mode == defaultMode) {
505 uidState.opModes.delete(code);
506 if (uidState.opModes.size() <= 0) {
507 uidState.opModes = null;
508 }
509 } else {
510 uidState.opModes.put(code, mode);
511 }
512 scheduleWriteLocked();
513 }
514 }
515
Svetoslav215b44a2015-08-04 19:03:40 -0700516 String[] uidPackageNames = getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -0700517 ArrayMap<Callback, ArraySet<String>> callbackSpecs = null;
518
riddle_hsu40b300f2015-11-23 13:22:03 +0800519 synchronized (this) {
520 ArrayList<Callback> callbacks = mOpModeWatchers.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -0700521 if (callbacks != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700522 final int callbackCount = callbacks.size();
523 for (int i = 0; i < callbackCount; i++) {
524 Callback callback = callbacks.get(i);
riddle_hsu40b300f2015-11-23 13:22:03 +0800525 ArraySet<String> changedPackages = new ArraySet<>();
526 Collections.addAll(changedPackages, uidPackageNames);
527 callbackSpecs = new ArrayMap<>();
528 callbackSpecs.put(callback, changedPackages);
529 }
530 }
531
532 for (String uidPackageName : uidPackageNames) {
533 callbacks = mPackageModeWatchers.get(uidPackageName);
534 if (callbacks != null) {
535 if (callbackSpecs == null) {
536 callbackSpecs = new ArrayMap<>();
Svet Ganov2af57082015-07-30 08:44:20 -0700537 }
riddle_hsu40b300f2015-11-23 13:22:03 +0800538 final int callbackCount = callbacks.size();
539 for (int i = 0; i < callbackCount; i++) {
540 Callback callback = callbacks.get(i);
541 ArraySet<String> changedPackages = callbackSpecs.get(callback);
542 if (changedPackages == null) {
543 changedPackages = new ArraySet<>();
544 callbackSpecs.put(callback, changedPackages);
545 }
546 changedPackages.add(uidPackageName);
547 }
Svet Ganov2af57082015-07-30 08:44:20 -0700548 }
549 }
550 }
551
552 if (callbackSpecs == null) {
553 return;
554 }
555
556 // There are components watching for mode changes such as window manager
557 // and location manager which are in our process. The callbacks in these
558 // components may require permissions our remote caller does not have.
559 final long identity = Binder.clearCallingIdentity();
560 try {
561 for (int i = 0; i < callbackSpecs.size(); i++) {
562 Callback callback = callbackSpecs.keyAt(i);
563 ArraySet<String> reportedPackageNames = callbackSpecs.valueAt(i);
564 try {
565 if (reportedPackageNames == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700566 callback.mCallback.opChanged(code, uid, null);
Svet Ganov2af57082015-07-30 08:44:20 -0700567 } else {
568 final int reportedPackageCount = reportedPackageNames.size();
569 for (int j = 0; j < reportedPackageCount; j++) {
570 String reportedPackageName = reportedPackageNames.valueAt(j);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700571 callback.mCallback.opChanged(code, uid, reportedPackageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700572 }
573 }
574 } catch (RemoteException e) {
575 Log.w(TAG, "Error dispatching op op change", e);
576 }
577 }
578 } finally {
579 Binder.restoreCallingIdentity(identity);
580 }
581 }
582
583 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800584 public void setMode(int code, int uid, String packageName, int mode) {
Dianne Hackbornb64afe12014-07-22 16:29:04 -0700585 if (Binder.getCallingPid() != Process.myPid()) {
586 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
587 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborn133b9df2014-07-01 13:06:10 -0700588 }
Dianne Hackborn961321f2013-02-05 17:22:41 -0800589 verifyIncomingOp(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800590 ArrayList<Callback> repCbs = null;
591 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800592 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700593 UidState uidState = getUidStateLocked(uid, false);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800594 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800595 if (op != null) {
596 if (op.mode != mode) {
597 op.mode = mode;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800598 ArrayList<Callback> cbs = mOpModeWatchers.get(code);
599 if (cbs != null) {
600 if (repCbs == null) {
601 repCbs = new ArrayList<Callback>();
602 }
603 repCbs.addAll(cbs);
604 }
605 cbs = mPackageModeWatchers.get(packageName);
606 if (cbs != null) {
607 if (repCbs == null) {
608 repCbs = new ArrayList<Callback>();
609 }
610 repCbs.addAll(cbs);
611 }
David Braunf5d83192013-09-16 13:43:51 -0700612 if (mode == AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800613 // If going into the default mode, prune this op
614 // if there is nothing else interesting in it.
Dianne Hackborn607b4142013-08-02 18:10:10 -0700615 pruneOp(op, uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800616 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800617 scheduleFastWriteLocked();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800618 }
619 }
620 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800621 if (repCbs != null) {
Svet Ganov38536112015-05-19 12:45:52 -0700622 // There are components watching for mode changes such as window manager
623 // and location manager which are in our process. The callbacks in these
624 // components may require permissions our remote caller does not have.
625 final long identity = Binder.clearCallingIdentity();
626 try {
627 for (int i = 0; i < repCbs.size(); i++) {
628 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700629 repCbs.get(i).mCallback.opChanged(code, uid, packageName);
Svet Ganov38536112015-05-19 12:45:52 -0700630 } catch (RemoteException e) {
631 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800632 }
Svet Ganov38536112015-05-19 12:45:52 -0700633 } finally {
634 Binder.restoreCallingIdentity(identity);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800635 }
636 }
637 }
638
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700639 private static HashMap<Callback, ArrayList<ChangeRec>> addCallbacks(
640 HashMap<Callback, ArrayList<ChangeRec>> callbacks,
641 int op, int uid, String packageName, ArrayList<Callback> cbs) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700642 if (cbs == null) {
643 return callbacks;
644 }
645 if (callbacks == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700646 callbacks = new HashMap<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700647 }
Svet Ganov2af57082015-07-30 08:44:20 -0700648 boolean duplicate = false;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700649 for (int i=0; i<cbs.size(); i++) {
650 Callback cb = cbs.get(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700651 ArrayList<ChangeRec> reports = callbacks.get(cb);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700652 if (reports == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700653 reports = new ArrayList<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700654 callbacks.put(cb, reports);
Svet Ganov2af57082015-07-30 08:44:20 -0700655 } else {
656 final int reportCount = reports.size();
657 for (int j = 0; j < reportCount; j++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700658 ChangeRec report = reports.get(j);
659 if (report.op == op && report.pkg.equals(packageName)) {
Svet Ganov2af57082015-07-30 08:44:20 -0700660 duplicate = true;
661 break;
662 }
663 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700664 }
Svet Ganov2af57082015-07-30 08:44:20 -0700665 if (!duplicate) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700666 reports.add(new ChangeRec(op, uid, packageName));
Svet Ganov2af57082015-07-30 08:44:20 -0700667 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700668 }
669 return callbacks;
670 }
671
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700672 static final class ChangeRec {
673 final int op;
674 final int uid;
675 final String pkg;
676
677 ChangeRec(int _op, int _uid, String _pkg) {
678 op = _op;
679 uid = _uid;
680 pkg = _pkg;
681 }
682 }
683
Dianne Hackborn607b4142013-08-02 18:10:10 -0700684 @Override
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800685 public void resetAllModes(int reqUserId, String reqPackageName) {
686 final int callingPid = Binder.getCallingPid();
687 final int callingUid = Binder.getCallingUid();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700688 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800689 callingPid, callingUid, null);
690 reqUserId = ActivityManager.handleIncomingUser(callingPid, callingUid, reqUserId,
691 true, true, "resetAllModes", null);
Svet Ganov2af57082015-07-30 08:44:20 -0700692
693 int reqUid = -1;
694 if (reqPackageName != null) {
695 try {
696 reqUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -0700697 reqPackageName, PackageManager.MATCH_UNINSTALLED_PACKAGES, reqUserId);
Svet Ganov2af57082015-07-30 08:44:20 -0700698 } catch (RemoteException e) {
699 /* ignore - local call */
700 }
701 }
702
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700703 HashMap<Callback, ArrayList<ChangeRec>> callbacks = null;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700704 synchronized (this) {
705 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700706 for (int i = mUidStates.size() - 1; i >= 0; i--) {
707 UidState uidState = mUidStates.valueAt(i);
708
709 SparseIntArray opModes = uidState.opModes;
710 if (opModes != null && (uidState.uid == reqUid || reqUid == -1)) {
711 final int uidOpCount = opModes.size();
712 for (int j = uidOpCount - 1; j >= 0; j--) {
713 final int code = opModes.keyAt(j);
714 if (AppOpsManager.opAllowsReset(code)) {
715 opModes.removeAt(j);
716 if (opModes.size() <= 0) {
717 uidState.opModes = null;
718 }
719 for (String packageName : getPackagesForUid(uidState.uid)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700720 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700721 mOpModeWatchers.get(code));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700722 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700723 mPackageModeWatchers.get(packageName));
724 }
725 }
726 }
727 }
728
729 if (uidState.pkgOps == null) {
730 continue;
731 }
732
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800733 if (reqUserId != UserHandle.USER_ALL
Svet Ganov2af57082015-07-30 08:44:20 -0700734 && reqUserId != UserHandle.getUserId(uidState.uid)) {
Alexandra Gherghinad6a98972014-08-04 17:05:34 +0100735 // Skip any ops for a different user
736 continue;
737 }
Svet Ganov2af57082015-07-30 08:44:20 -0700738
739 Map<String, Ops> packages = uidState.pkgOps;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700740 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
741 while (it.hasNext()) {
742 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700743 String packageName = ent.getKey();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800744 if (reqPackageName != null && !reqPackageName.equals(packageName)) {
745 // Skip any ops for a different package
746 continue;
747 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700748 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700749 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700750 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -0700751 if (AppOpsManager.opAllowsReset(curOp.op)
752 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -0700753 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700754 changed = true;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700755 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -0700756 mOpModeWatchers.get(curOp.op));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700757 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -0700758 mPackageModeWatchers.get(packageName));
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700759 if (curOp.time == 0 && curOp.rejectTime == 0) {
760 pkgOps.removeAt(j);
761 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700762 }
763 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700764 if (pkgOps.size() == 0) {
765 it.remove();
766 }
767 }
Svet Ganov2af57082015-07-30 08:44:20 -0700768 if (uidState.isDefault()) {
769 mUidStates.remove(uidState.uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700770 }
771 }
Svet Ganov2af57082015-07-30 08:44:20 -0700772
Dianne Hackborn607b4142013-08-02 18:10:10 -0700773 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800774 scheduleFastWriteLocked();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700775 }
776 }
777 if (callbacks != null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700778 for (Map.Entry<Callback, ArrayList<ChangeRec>> ent : callbacks.entrySet()) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700779 Callback cb = ent.getKey();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700780 ArrayList<ChangeRec> reports = ent.getValue();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700781 for (int i=0; i<reports.size(); i++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700782 ChangeRec rep = reports.get(i);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700783 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700784 cb.mCallback.opChanged(rep.op, rep.uid, rep.pkg);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700785 } catch (RemoteException e) {
786 }
787 }
788 }
789 }
790 }
791
Dianne Hackbornc2293022013-02-06 23:14:49 -0800792 @Override
793 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -0800794 if (callback == null) {
795 return;
796 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800797 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700798 op = (op != AppOpsManager.OP_NONE) ? AppOpsManager.opToSwitch(op) : op;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800799 Callback cb = mModeWatchers.get(callback.asBinder());
800 if (cb == null) {
801 cb = new Callback(callback);
802 mModeWatchers.put(callback.asBinder(), cb);
803 }
804 if (op != AppOpsManager.OP_NONE) {
805 ArrayList<Callback> cbs = mOpModeWatchers.get(op);
806 if (cbs == null) {
807 cbs = new ArrayList<Callback>();
808 mOpModeWatchers.put(op, cbs);
809 }
810 cbs.add(cb);
811 }
812 if (packageName != null) {
813 ArrayList<Callback> cbs = mPackageModeWatchers.get(packageName);
814 if (cbs == null) {
815 cbs = new ArrayList<Callback>();
816 mPackageModeWatchers.put(packageName, cbs);
817 }
818 cbs.add(cb);
819 }
820 }
821 }
822
823 @Override
824 public void stopWatchingMode(IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -0800825 if (callback == null) {
826 return;
827 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800828 synchronized (this) {
829 Callback cb = mModeWatchers.remove(callback.asBinder());
830 if (cb != null) {
831 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700832 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800833 ArrayList<Callback> cbs = mOpModeWatchers.valueAt(i);
834 cbs.remove(cb);
835 if (cbs.size() <= 0) {
836 mOpModeWatchers.removeAt(i);
837 }
838 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700839 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
840 ArrayList<Callback> cbs = mPackageModeWatchers.valueAt(i);
841 cbs.remove(cb);
842 if (cbs.size() <= 0) {
843 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800844 }
845 }
846 }
847 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800848 }
849
850 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700851 public IBinder getToken(IBinder clientToken) {
852 synchronized (this) {
853 ClientState cs = mClients.get(clientToken);
854 if (cs == null) {
855 cs = new ClientState(clientToken);
856 mClients.put(clientToken, cs);
857 }
858 return cs;
859 }
860 }
861
862 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800863 public int checkOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800864 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800865 verifyIncomingOp(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800866 synchronized (this) {
Jason Monk1c7c3192014-06-26 12:52:18 -0400867 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -0400868 return AppOpsManager.MODE_IGNORED;
869 }
Svet Ganov2af57082015-07-30 08:44:20 -0700870 code = AppOpsManager.opToSwitch(code);
871 UidState uidState = getUidStateLocked(uid, false);
872 if (uidState != null && uidState.opModes != null) {
873 final int uidMode = uidState.opModes.get(code);
874 if (uidMode != AppOpsManager.MODE_ALLOWED) {
875 return uidMode;
876 }
877 }
878 Op op = getOpLocked(code, uid, packageName, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800879 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -0700880 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800881 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800882 return op.mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800883 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800884 }
885
886 @Override
John Spurlock7b414672014-07-18 13:02:39 -0400887 public int checkAudioOperation(int code, int usage, int uid, String packageName) {
Andrei Stingaceanu355b2322016-02-12 16:43:51 +0000888 if (isPackageSuspendedForUser(packageName, uid)) {
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000889 Log.i(TAG, "Audio disabled for suspended package=" + packageName + " for uid=" + uid);
890 return AppOpsManager.MODE_IGNORED;
891 }
892
John Spurlock1af30c72014-03-10 08:33:35 -0400893 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -0400894 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -0400895 if (mode != AppOpsManager.MODE_ALLOWED) {
896 return mode;
897 }
898 }
899 return checkOperation(code, uid, packageName);
900 }
901
Andrei Stingaceanu355b2322016-02-12 16:43:51 +0000902 private boolean isPackageSuspendedForUser(String pkg, int uid) {
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000903 try {
Andrei Stingaceanu355b2322016-02-12 16:43:51 +0000904 return AppGlobals.getPackageManager().isPackageSuspendedForUser(
905 pkg, UserHandle.getUserId(uid));
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000906 } catch (RemoteException re) {
907 throw new SecurityException("Could not talk to package manager service");
908 }
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000909 }
910
John Spurlock7b414672014-07-18 13:02:39 -0400911 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
912 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
913 if (usageRestrictions != null) {
914 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -0400915 if (r != null && !r.exceptionPackages.contains(packageName)) {
916 return r.mode;
917 }
918 }
919 return AppOpsManager.MODE_ALLOWED;
920 }
921
922 @Override
John Spurlock7b414672014-07-18 13:02:39 -0400923 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -0400924 String[] exceptionPackages) {
925 verifyIncomingUid(uid);
926 verifyIncomingOp(code);
927 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -0400928 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
929 if (usageRestrictions == null) {
930 usageRestrictions = new SparseArray<Restriction>();
931 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -0400932 }
John Spurlock7b414672014-07-18 13:02:39 -0400933 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -0400934 if (mode != AppOpsManager.MODE_ALLOWED) {
935 final Restriction r = new Restriction();
936 r.mode = mode;
937 if (exceptionPackages != null) {
938 final int N = exceptionPackages.length;
939 r.exceptionPackages = new ArraySet<String>(N);
940 for (int i = 0; i < N; i++) {
941 final String pkg = exceptionPackages[i];
942 if (pkg != null) {
943 r.exceptionPackages.add(pkg.trim());
944 }
945 }
946 }
John Spurlock7b414672014-07-18 13:02:39 -0400947 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -0400948 }
949 }
950 }
951
952 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700953 public int checkPackage(int uid, String packageName) {
954 synchronized (this) {
Dianne Hackborn0fcef842014-09-12 15:38:33 -0700955 if (getOpsRawLocked(uid, packageName, true) != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700956 return AppOpsManager.MODE_ALLOWED;
957 } else {
958 return AppOpsManager.MODE_ERRORED;
959 }
960 }
961 }
962
963 @Override
Svet Ganov99b60432015-06-27 13:15:22 -0700964 public int noteProxyOperation(int code, String proxyPackageName,
965 int proxiedUid, String proxiedPackageName) {
966 verifyIncomingOp(code);
967 final int proxyMode = noteOperationUnchecked(code, Binder.getCallingUid(),
968 proxyPackageName, -1, null);
969 if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
970 return proxyMode;
971 }
972 return noteOperationUnchecked(code, proxiedUid, proxiedPackageName,
973 Binder.getCallingUid(), proxyPackageName);
Svet Ganov99b60432015-06-27 13:15:22 -0700974 }
975
976 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800977 public int noteOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800978 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800979 verifyIncomingOp(code);
Svet Ganov99b60432015-06-27 13:15:22 -0700980 return noteOperationUnchecked(code, uid, packageName, 0, null);
981 }
982
983 private int noteOperationUnchecked(int code, int uid, String packageName,
984 int proxyUid, String proxyPackageName) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800985 synchronized (this) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800986 Ops ops = getOpsLocked(uid, packageName, true);
987 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800988 if (DEBUG) Log.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
989 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700990 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800991 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800992 Op op = getOpLocked(ops, code, true);
Jason Monk1c7c3192014-06-26 12:52:18 -0400993 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -0400994 return AppOpsManager.MODE_IGNORED;
995 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800996 if (op.duration == -1) {
997 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
998 + " code " + code + " time=" + op.time + " duration=" + op.duration);
999 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001000 op.duration = 0;
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001001 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001002 UidState uidState = ops.uidState;
1003 if (uidState.opModes != null) {
1004 final int uidMode = uidState.opModes.get(switchCode);
1005 if (uidMode != AppOpsManager.MODE_ALLOWED) {
1006 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1007 + switchCode + " (" + code + ") uid " + uid + " package "
1008 + packageName);
1009 op.rejectTime = System.currentTimeMillis();
1010 return uidMode;
1011 }
1012 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001013 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
1014 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
1015 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1016 + switchCode + " (" + code + ") uid " + uid + " package " + packageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001017 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001018 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001019 }
1020 if (DEBUG) Log.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
1021 + " package " + packageName);
1022 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001023 op.rejectTime = 0;
Svet Ganov99b60432015-06-27 13:15:22 -07001024 op.proxyUid = proxyUid;
1025 op.proxyPackageName = proxyPackageName;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001026 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001027 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001028 }
1029
1030 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001031 public int startOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001032 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001033 verifyIncomingOp(code);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001034 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001035 synchronized (this) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001036 Ops ops = getOpsLocked(uid, packageName, true);
1037 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001038 if (DEBUG) Log.d(TAG, "startOperation: no op for code " + code + " uid " + uid
1039 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001040 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001041 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001042 Op op = getOpLocked(ops, code, true);
Jason Monk1c7c3192014-06-26 12:52:18 -04001043 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001044 return AppOpsManager.MODE_IGNORED;
1045 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001046 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001047 UidState uidState = ops.uidState;
1048 if (uidState.opModes != null) {
1049 final int uidMode = uidState.opModes.get(switchCode);
1050 if (uidMode != AppOpsManager.MODE_ALLOWED) {
1051 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1052 + switchCode + " (" + code + ") uid " + uid + " package "
1053 + packageName);
1054 op.rejectTime = System.currentTimeMillis();
1055 return uidMode;
1056 }
1057 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001058 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
1059 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
1060 if (DEBUG) Log.d(TAG, "startOperation: reject #" + op.mode + " for code "
1061 + switchCode + " (" + code + ") uid " + uid + " package " + packageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001062 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001063 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001064 }
1065 if (DEBUG) Log.d(TAG, "startOperation: allowing code " + code + " uid " + uid
1066 + " package " + packageName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001067 if (op.nesting == 0) {
1068 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001069 op.rejectTime = 0;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001070 op.duration = -1;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001071 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001072 op.nesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001073 if (client.mStartedOps != null) {
1074 client.mStartedOps.add(op);
1075 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001076 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001077 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001078 }
1079
1080 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001081 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001082 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001083 verifyIncomingOp(code);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001084 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001085 synchronized (this) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001086 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001087 if (op == null) {
1088 return;
1089 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001090 if (client.mStartedOps != null) {
1091 if (!client.mStartedOps.remove(op)) {
1092 throw new IllegalStateException("Operation not started: uid" + op.uid
1093 + " pkg=" + op.packageName + " op=" + op.op);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001094 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001095 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001096 finishOperationLocked(op);
1097 }
1098 }
1099
Svet Ganovb9d71a62015-04-30 10:38:13 -07001100 @Override
1101 public int permissionToOpCode(String permission) {
1102 return AppOpsManager.permissionToOpCode(permission);
1103 }
1104
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001105 void finishOperationLocked(Op op) {
1106 if (op.nesting <= 1) {
1107 if (op.nesting == 1) {
1108 op.duration = (int)(System.currentTimeMillis() - op.time);
1109 op.time += op.duration;
1110 } else {
1111 Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
1112 + op.packageName + " code " + op.op + " time=" + op.time
1113 + " duration=" + op.duration + " nesting=" + op.nesting);
1114 }
1115 op.nesting = 0;
1116 } else {
1117 op.nesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001118 }
1119 }
1120
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001121 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001122 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001123 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001124 }
1125 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001126 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001127 }
1128 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
1129 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001130 }
1131
Dianne Hackborn961321f2013-02-05 17:22:41 -08001132 private void verifyIncomingOp(int op) {
1133 if (op >= 0 && op < AppOpsManager._NUM_OP) {
1134 return;
1135 }
1136 throw new IllegalArgumentException("Bad operation #" + op);
1137 }
1138
Svet Ganov2af57082015-07-30 08:44:20 -07001139 private UidState getUidStateLocked(int uid, boolean edit) {
1140 UidState uidState = mUidStates.get(uid);
1141 if (uidState == null) {
1142 if (!edit) {
1143 return null;
1144 }
1145 uidState = new UidState(uid);
1146 mUidStates.put(uid, uidState);
1147 }
1148 return uidState;
1149 }
1150
Dianne Hackborn72e39832013-01-18 18:36:09 -08001151 private Ops getOpsLocked(int uid, String packageName, boolean edit) {
Dianne Hackborn0fcef842014-09-12 15:38:33 -07001152 if (uid == 0) {
1153 packageName = "root";
1154 } else if (uid == Process.SHELL_UID) {
1155 packageName = "com.android.shell";
1156 }
1157 return getOpsRawLocked(uid, packageName, edit);
1158 }
1159
1160 private Ops getOpsRawLocked(int uid, String packageName, boolean edit) {
Svet Ganov2af57082015-07-30 08:44:20 -07001161 UidState uidState = getUidStateLocked(uid, edit);
1162 if (uidState == null) {
1163 return null;
1164 }
1165
1166 if (uidState.pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001167 if (!edit) {
1168 return null;
1169 }
Svet Ganov2af57082015-07-30 08:44:20 -07001170 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001171 }
Svet Ganov2af57082015-07-30 08:44:20 -07001172
1173 Ops ops = uidState.pkgOps.get(packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001174 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001175 if (!edit) {
1176 return null;
1177 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001178 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001179 // This is the first time we have seen this package name under this uid,
1180 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -08001181 if (uid != 0) {
1182 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001183 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001184 int pkgUid = -1;
1185 try {
Jason Monk1c7c3192014-06-26 12:52:18 -04001186 ApplicationInfo appInfo = ActivityThread.getPackageManager()
Jeff Sharkeycd654482016-01-08 17:42:11 -07001187 .getApplicationInfo(packageName,
1188 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1189 UserHandle.getUserId(uid));
Jason Monk1c7c3192014-06-26 12:52:18 -04001190 if (appInfo != null) {
1191 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001192 isPrivileged = (appInfo.privateFlags
1193 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001194 } else {
1195 if ("media".equals(packageName)) {
1196 pkgUid = Process.MEDIA_UID;
1197 isPrivileged = false;
Andy Hunged0ea402015-10-30 14:11:46 -07001198 } else if ("audioserver".equals(packageName)) {
1199 pkgUid = Process.AUDIOSERVER_UID;
1200 isPrivileged = false;
Chien-Yu Chen75cade02016-01-11 10:56:21 -08001201 } else if ("cameraserver".equals(packageName)) {
1202 pkgUid = Process.CAMERASERVER_UID;
1203 isPrivileged = false;
Jason Monk1c7c3192014-06-26 12:52:18 -04001204 }
Dianne Hackborn713df152013-05-17 11:27:57 -07001205 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001206 } catch (RemoteException e) {
1207 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001208 }
1209 if (pkgUid != uid) {
1210 // Oops! The package name is not valid for the uid they are calling
1211 // under. Abort.
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001212 RuntimeException ex = new RuntimeException("here");
1213 ex.fillInStackTrace();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001214 Slog.w(TAG, "Bad call: specified package " + packageName
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001215 + " under uid " + uid + " but it is really " + pkgUid, ex);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001216 return null;
1217 }
1218 } finally {
1219 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001220 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001221 }
Svet Ganov2af57082015-07-30 08:44:20 -07001222 ops = new Ops(packageName, uidState, isPrivileged);
1223 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001224 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08001225 return ops;
1226 }
1227
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001228 private void scheduleWriteLocked() {
1229 if (!mWriteScheduled) {
1230 mWriteScheduled = true;
1231 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
1232 }
1233 }
1234
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001235 private void scheduleFastWriteLocked() {
1236 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001237 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001238 mFastWriteScheduled = true;
1239 mHandler.removeCallbacks(mWriteRunner);
1240 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001241 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001242 }
1243
Dianne Hackborn72e39832013-01-18 18:36:09 -08001244 private Op getOpLocked(int code, int uid, String packageName, boolean edit) {
1245 Ops ops = getOpsLocked(uid, packageName, edit);
1246 if (ops == null) {
1247 return null;
1248 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001249 return getOpLocked(ops, code, edit);
1250 }
1251
1252 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001253 Op op = ops.get(code);
1254 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001255 if (!edit) {
1256 return null;
1257 }
Svet Ganov2af57082015-07-30 08:44:20 -07001258 op = new Op(ops.uidState.uid, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001259 ops.put(code, op);
1260 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001261 if (edit) {
1262 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001263 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001264 return op;
1265 }
1266
Jason Monk1c7c3192014-06-26 12:52:18 -04001267 private boolean isOpRestricted(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04001268 int userHandle = UserHandle.getUserId(uid);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001269 final int restrictionSetCount = mOpUserRestrictions.size();
1270 for (int i = 0; i < restrictionSetCount; i++) {
1271 SparseArray<boolean[]> perUserRestrictions = mOpUserRestrictions.valueAt(i);
1272 boolean[] opRestrictions = perUserRestrictions.get(userHandle);
1273 if (opRestrictions != null && opRestrictions[code]) {
1274 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
1275 synchronized (this) {
1276 Ops ops = getOpsLocked(uid, packageName, true);
1277 if ((ops != null) && ops.isPrivileged) {
1278 return false;
1279 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001280 }
1281 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001282 return true;
Jason Monk1c7c3192014-06-26 12:52:18 -04001283 }
Jason Monk62062992014-05-06 09:55:28 -04001284 }
1285 return false;
1286 }
1287
Dianne Hackborn35654b62013-01-14 17:38:02 -08001288 void readState() {
1289 synchronized (mFile) {
1290 synchronized (this) {
1291 FileInputStream stream;
1292 try {
1293 stream = mFile.openRead();
1294 } catch (FileNotFoundException e) {
1295 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
1296 return;
1297 }
1298 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001299 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001300 try {
1301 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001302 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001303 int type;
1304 while ((type = parser.next()) != XmlPullParser.START_TAG
1305 && type != XmlPullParser.END_DOCUMENT) {
1306 ;
1307 }
1308
1309 if (type != XmlPullParser.START_TAG) {
1310 throw new IllegalStateException("no start tag found");
1311 }
1312
1313 int outerDepth = parser.getDepth();
1314 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1315 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1316 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1317 continue;
1318 }
1319
1320 String tagName = parser.getName();
1321 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001322 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07001323 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07001324 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001325 } else {
1326 Slog.w(TAG, "Unknown element under <app-ops>: "
1327 + parser.getName());
1328 XmlUtils.skipCurrentTag(parser);
1329 }
1330 }
1331 success = true;
1332 } catch (IllegalStateException e) {
1333 Slog.w(TAG, "Failed parsing " + e);
1334 } catch (NullPointerException e) {
1335 Slog.w(TAG, "Failed parsing " + e);
1336 } catch (NumberFormatException e) {
1337 Slog.w(TAG, "Failed parsing " + e);
1338 } catch (XmlPullParserException e) {
1339 Slog.w(TAG, "Failed parsing " + e);
1340 } catch (IOException e) {
1341 Slog.w(TAG, "Failed parsing " + e);
1342 } catch (IndexOutOfBoundsException e) {
1343 Slog.w(TAG, "Failed parsing " + e);
1344 } finally {
1345 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07001346 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001347 }
1348 try {
1349 stream.close();
1350 } catch (IOException e) {
1351 }
1352 }
1353 }
1354 }
1355 }
1356
Svet Ganov2af57082015-07-30 08:44:20 -07001357 void readUidOps(XmlPullParser parser) throws NumberFormatException,
1358 XmlPullParserException, IOException {
1359 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
1360 int outerDepth = parser.getDepth();
1361 int type;
1362 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1363 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1364 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1365 continue;
1366 }
1367
1368 String tagName = parser.getName();
1369 if (tagName.equals("op")) {
1370 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
1371 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
1372 UidState uidState = getUidStateLocked(uid, true);
1373 if (uidState.opModes == null) {
1374 uidState.opModes = new SparseIntArray();
1375 }
1376 uidState.opModes.put(code, mode);
1377 } else {
1378 Slog.w(TAG, "Unknown element under <uid-ops>: "
1379 + parser.getName());
1380 XmlUtils.skipCurrentTag(parser);
1381 }
1382 }
1383 }
1384
Dave Burke0997c5bd2013-08-02 20:25:02 +00001385 void readPackage(XmlPullParser parser) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001386 XmlPullParserException, IOException {
1387 String pkgName = parser.getAttributeValue(null, "n");
1388 int outerDepth = parser.getDepth();
1389 int type;
1390 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1391 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1392 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1393 continue;
1394 }
1395
1396 String tagName = parser.getName();
1397 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001398 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001399 } else {
1400 Slog.w(TAG, "Unknown element under <pkg>: "
1401 + parser.getName());
1402 XmlUtils.skipCurrentTag(parser);
1403 }
1404 }
1405 }
1406
Dave Burke0997c5bd2013-08-02 20:25:02 +00001407 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001408 XmlPullParserException, IOException {
1409 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Jason Monk1c7c3192014-06-26 12:52:18 -04001410 String isPrivilegedString = parser.getAttributeValue(null, "p");
1411 boolean isPrivileged = false;
1412 if (isPrivilegedString == null) {
1413 try {
1414 IPackageManager packageManager = ActivityThread.getPackageManager();
1415 if (packageManager != null) {
1416 ApplicationInfo appInfo = ActivityThread.getPackageManager()
1417 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
1418 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001419 isPrivileged = (appInfo.privateFlags
1420 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001421 }
1422 } else {
1423 // Could not load data, don't add to cache so it will be loaded later.
1424 return;
1425 }
1426 } catch (RemoteException e) {
1427 Slog.w(TAG, "Could not contact PackageManager", e);
1428 }
1429 } else {
1430 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
1431 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001432 int outerDepth = parser.getDepth();
1433 int type;
1434 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1435 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1436 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1437 continue;
1438 }
1439
1440 String tagName = parser.getName();
1441 if (tagName.equals("op")) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001442 Op op = new Op(uid, pkgName, Integer.parseInt(parser.getAttributeValue(null, "n")));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001443 String mode = parser.getAttributeValue(null, "m");
1444 if (mode != null) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001445 op.mode = Integer.parseInt(mode);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001446 }
1447 String time = parser.getAttributeValue(null, "t");
1448 if (time != null) {
1449 op.time = Long.parseLong(time);
1450 }
1451 time = parser.getAttributeValue(null, "r");
1452 if (time != null) {
1453 op.rejectTime = Long.parseLong(time);
1454 }
1455 String dur = parser.getAttributeValue(null, "d");
1456 if (dur != null) {
1457 op.duration = Integer.parseInt(dur);
1458 }
Svet Ganov99b60432015-06-27 13:15:22 -07001459 String proxyUid = parser.getAttributeValue(null, "pu");
1460 if (proxyUid != null) {
1461 op.proxyUid = Integer.parseInt(proxyUid);
1462 }
1463 String proxyPackageName = parser.getAttributeValue(null, "pp");
1464 if (proxyPackageName != null) {
1465 op.proxyPackageName = proxyPackageName;
1466 }
Svet Ganov2af57082015-07-30 08:44:20 -07001467
1468 UidState uidState = getUidStateLocked(uid, true);
1469 if (uidState.pkgOps == null) {
1470 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001471 }
Svet Ganov2af57082015-07-30 08:44:20 -07001472
1473 Ops ops = uidState.pkgOps.get(pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001474 if (ops == null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001475 ops = new Ops(pkgName, uidState, isPrivileged);
1476 uidState.pkgOps.put(pkgName, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001477 }
1478 ops.put(op.op, op);
1479 } else {
1480 Slog.w(TAG, "Unknown element under <pkg>: "
1481 + parser.getName());
1482 XmlUtils.skipCurrentTag(parser);
1483 }
1484 }
1485 }
1486
1487 void writeState() {
1488 synchronized (mFile) {
1489 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
1490
1491 FileOutputStream stream;
1492 try {
1493 stream = mFile.startWrite();
1494 } catch (IOException e) {
1495 Slog.w(TAG, "Failed to write state: " + e);
1496 return;
1497 }
1498
1499 try {
1500 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001501 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001502 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001503 out.startTag(null, "app-ops");
Svet Ganov2af57082015-07-30 08:44:20 -07001504
1505 final int uidStateCount = mUidStates.size();
1506 for (int i = 0; i < uidStateCount; i++) {
1507 UidState uidState = mUidStates.valueAt(i);
1508 if (uidState.opModes != null && uidState.opModes.size() > 0) {
1509 out.startTag(null, "uid");
1510 out.attribute(null, "n", Integer.toString(uidState.uid));
1511 SparseIntArray uidOpModes = uidState.opModes;
1512 final int opCount = uidOpModes.size();
1513 for (int j = 0; j < opCount; j++) {
1514 final int op = uidOpModes.keyAt(j);
1515 final int mode = uidOpModes.valueAt(j);
1516 out.startTag(null, "op");
1517 out.attribute(null, "n", Integer.toString(op));
1518 out.attribute(null, "m", Integer.toString(mode));
1519 out.endTag(null, "op");
1520 }
1521 out.endTag(null, "uid");
1522 }
1523 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001524
1525 if (allOps != null) {
1526 String lastPkg = null;
1527 for (int i=0; i<allOps.size(); i++) {
1528 AppOpsManager.PackageOps pkg = allOps.get(i);
1529 if (!pkg.getPackageName().equals(lastPkg)) {
1530 if (lastPkg != null) {
1531 out.endTag(null, "pkg");
1532 }
1533 lastPkg = pkg.getPackageName();
1534 out.startTag(null, "pkg");
1535 out.attribute(null, "n", lastPkg);
1536 }
1537 out.startTag(null, "uid");
1538 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04001539 synchronized (this) {
1540 Ops ops = getOpsLocked(pkg.getUid(), pkg.getPackageName(), false);
1541 // Should always be present as the list of PackageOps is generated
1542 // from Ops.
1543 if (ops != null) {
1544 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
1545 } else {
1546 out.attribute(null, "p", Boolean.toString(false));
1547 }
1548 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001549 List<AppOpsManager.OpEntry> ops = pkg.getOps();
1550 for (int j=0; j<ops.size(); j++) {
1551 AppOpsManager.OpEntry op = ops.get(j);
1552 out.startTag(null, "op");
1553 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07001554 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001555 out.attribute(null, "m", Integer.toString(op.getMode()));
1556 }
1557 long time = op.getTime();
1558 if (time != 0) {
1559 out.attribute(null, "t", Long.toString(time));
1560 }
1561 time = op.getRejectTime();
1562 if (time != 0) {
1563 out.attribute(null, "r", Long.toString(time));
1564 }
1565 int dur = op.getDuration();
1566 if (dur != 0) {
1567 out.attribute(null, "d", Integer.toString(dur));
1568 }
Svet Ganov99b60432015-06-27 13:15:22 -07001569 int proxyUid = op.getProxyUid();
1570 if (proxyUid != -1) {
1571 out.attribute(null, "pu", Integer.toString(proxyUid));
1572 }
1573 String proxyPackageName = op.getProxyPackageName();
1574 if (proxyPackageName != null) {
1575 out.attribute(null, "pp", proxyPackageName);
1576 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001577 out.endTag(null, "op");
1578 }
1579 out.endTag(null, "uid");
1580 }
1581 if (lastPkg != null) {
1582 out.endTag(null, "pkg");
1583 }
1584 }
1585
1586 out.endTag(null, "app-ops");
1587 out.endDocument();
1588 mFile.finishWrite(stream);
1589 } catch (IOException e) {
1590 Slog.w(TAG, "Failed to write state, restoring backup.", e);
1591 mFile.failWrite(stream);
1592 }
1593 }
1594 }
1595
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001596 static class Shell extends ShellCommand {
1597 final IAppOpsService mInterface;
1598 final AppOpsService mInternal;
1599
1600 int userId = UserHandle.USER_SYSTEM;
1601 String packageName;
1602 String opStr;
1603 int op;
1604 int packageUid;
1605
1606 Shell(IAppOpsService iface, AppOpsService internal) {
1607 mInterface = iface;
1608 mInternal = internal;
1609 }
1610
1611 @Override
1612 public int onCommand(String cmd) {
1613 return onShellCommand(this, cmd);
1614 }
1615
1616 @Override
1617 public void onHelp() {
1618 PrintWriter pw = getOutPrintWriter();
1619 dumpCommandHelp(pw);
1620 }
1621
1622 private int strOpToOp(String op, PrintWriter err) {
1623 try {
1624 return AppOpsManager.strOpToOp(op);
1625 } catch (IllegalArgumentException e) {
1626 }
1627 try {
1628 return Integer.parseInt(op);
1629 } catch (NumberFormatException e) {
1630 }
1631 try {
1632 return AppOpsManager.strDebugOpToOp(op);
1633 } catch (IllegalArgumentException e) {
1634 err.println("Error: " + e.getMessage());
1635 return -1;
1636 }
1637 }
1638
1639 int parseUserPackageOp(boolean reqOp, PrintWriter err) throws RemoteException {
1640 userId = UserHandle.USER_CURRENT;
1641 packageName = null;
1642 opStr = null;
1643 for (String argument; (argument = getNextArg()) != null;) {
1644 if ("--user".equals(argument)) {
1645 userId = UserHandle.parseUserArg(getNextArgRequired());
1646 } else {
1647 if (packageName == null) {
1648 packageName = argument;
1649 } else if (opStr == null) {
1650 opStr = argument;
1651 break;
1652 }
1653 }
1654 }
1655 if (packageName == null) {
1656 err.println("Error: Package name not specified.");
1657 return -1;
1658 } else if (opStr == null && reqOp) {
1659 err.println("Error: Operation not specified.");
1660 return -1;
1661 }
1662 if (opStr != null) {
1663 op = strOpToOp(opStr, err);
1664 if (op < 0) {
1665 return -1;
1666 }
1667 } else {
1668 op = AppOpsManager.OP_NONE;
1669 }
1670 if (userId == UserHandle.USER_CURRENT) {
1671 userId = ActivityManager.getCurrentUser();
1672 }
1673 if ("root".equals(packageName)) {
1674 packageUid = 0;
1675 } else {
Jeff Sharkeycd654482016-01-08 17:42:11 -07001676 packageUid = AppGlobals.getPackageManager().getPackageUid(packageName,
1677 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001678 }
1679 if (packageUid < 0) {
1680 err.println("Error: No UID for " + packageName + " in user " + userId);
1681 return -1;
1682 }
1683 return 0;
1684 }
1685 }
1686
1687 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
1688 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
1689 (new Shell(this, this)).exec(this, in, out, err, args, resultReceiver);
1690 }
1691
1692 static void dumpCommandHelp(PrintWriter pw) {
1693 pw.println("AppOps service (appops) commands:");
1694 pw.println(" help");
1695 pw.println(" Print this help text.");
1696 pw.println(" set [--user <USER_ID>] <PACKAGE> <OP> <MODE>");
1697 pw.println(" Set the mode for a particular application and operation.");
1698 pw.println(" get [--user <USER_ID>] <PACKAGE> [<OP>]");
1699 pw.println(" Return the mode for a particular application and optional operation.");
1700 pw.println(" reset [--user <USER_ID>] [<PACKAGE>]");
1701 pw.println(" Reset the given application or all applications to default modes.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001702 pw.println(" write-settings");
1703 pw.println(" Immediately write pending changes to storage.");
1704 pw.println(" read-settings");
1705 pw.println(" Read the last written settings, replacing current state in RAM.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001706 pw.println(" options:");
1707 pw.println(" <PACKAGE> an Android package name.");
1708 pw.println(" <OP> an AppOps operation.");
1709 pw.println(" <MODE> one of allow, ignore, deny, or default");
1710 pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
1711 pw.println(" specified, the current user is assumed.");
1712 }
1713
1714 static int onShellCommand(Shell shell, String cmd) {
1715 if (cmd == null) {
1716 return shell.handleDefaultCommands(cmd);
1717 }
1718 PrintWriter pw = shell.getOutPrintWriter();
1719 PrintWriter err = shell.getErrPrintWriter();
1720 try {
1721 switch (cmd) {
1722 case "set": {
1723 int res = shell.parseUserPackageOp(true, err);
1724 if (res < 0) {
1725 return res;
1726 }
1727 String modeStr = shell.getNextArg();
1728 if (modeStr == null) {
1729 err.println("Error: Mode not specified.");
1730 return -1;
1731 }
1732
1733 final int mode;
1734 switch (modeStr) {
1735 case "allow":
1736 mode = AppOpsManager.MODE_ALLOWED;
1737 break;
1738 case "deny":
1739 mode = AppOpsManager.MODE_ERRORED;
1740 break;
1741 case "ignore":
1742 mode = AppOpsManager.MODE_IGNORED;
1743 break;
1744 case "default":
1745 mode = AppOpsManager.MODE_DEFAULT;
1746 break;
1747 default:
1748 err.println("Error: Mode " + modeStr + " is not valid,");
1749 return -1;
1750 }
1751
1752 shell.mInterface.setMode(shell.op, shell.packageUid, shell.packageName, mode);
1753 return 0;
1754 }
1755 case "get": {
1756 int res = shell.parseUserPackageOp(false, err);
1757 if (res < 0) {
1758 return res;
1759 }
1760
1761 List<AppOpsManager.PackageOps> ops = shell.mInterface.getOpsForPackage(
1762 shell.packageUid, shell.packageName,
1763 shell.op != AppOpsManager.OP_NONE ? new int[] {shell.op} : null);
1764 if (ops == null || ops.size() <= 0) {
1765 pw.println("No operations.");
1766 return 0;
1767 }
1768 final long now = System.currentTimeMillis();
1769 for (int i=0; i<ops.size(); i++) {
1770 List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
1771 for (int j=0; j<entries.size(); j++) {
1772 AppOpsManager.OpEntry ent = entries.get(j);
1773 pw.print(AppOpsManager.opToName(ent.getOp()));
1774 pw.print(": ");
1775 switch (ent.getMode()) {
1776 case AppOpsManager.MODE_ALLOWED:
1777 pw.print("allow");
1778 break;
1779 case AppOpsManager.MODE_IGNORED:
1780 pw.print("ignore");
1781 break;
1782 case AppOpsManager.MODE_ERRORED:
1783 pw.print("deny");
1784 break;
1785 case AppOpsManager.MODE_DEFAULT:
1786 pw.print("default");
1787 break;
1788 default:
1789 pw.print("mode=");
1790 pw.print(ent.getMode());
1791 break;
1792 }
1793 if (ent.getTime() != 0) {
1794 pw.print("; time=");
1795 TimeUtils.formatDuration(now - ent.getTime(), pw);
1796 pw.print(" ago");
1797 }
1798 if (ent.getRejectTime() != 0) {
1799 pw.print("; rejectTime=");
1800 TimeUtils.formatDuration(now - ent.getRejectTime(), pw);
1801 pw.print(" ago");
1802 }
1803 if (ent.getDuration() == -1) {
1804 pw.print(" (running)");
1805 } else if (ent.getDuration() != 0) {
1806 pw.print("; duration=");
1807 TimeUtils.formatDuration(ent.getDuration(), pw);
1808 }
1809 pw.println();
1810 }
1811 }
1812 return 0;
1813 }
1814 case "reset": {
1815 String packageName = null;
1816 int userId = UserHandle.USER_CURRENT;
1817 for (String argument; (argument = shell.getNextArg()) != null;) {
1818 if ("--user".equals(argument)) {
1819 String userStr = shell.getNextArgRequired();
1820 userId = UserHandle.parseUserArg(userStr);
1821 } else {
1822 if (packageName == null) {
1823 packageName = argument;
1824 } else {
1825 err.println("Error: Unsupported argument: " + argument);
1826 return -1;
1827 }
1828 }
1829 }
1830
1831 if (userId == UserHandle.USER_CURRENT) {
1832 userId = ActivityManager.getCurrentUser();
1833 }
1834
1835 shell.mInterface.resetAllModes(userId, packageName);
1836 pw.print("Reset all modes for: ");
1837 if (userId == UserHandle.USER_ALL) {
1838 pw.print("all users");
1839 } else {
1840 pw.print("user "); pw.print(userId);
1841 }
1842 pw.print(", ");
1843 if (packageName == null) {
1844 pw.println("all packages");
1845 } else {
1846 pw.print("package "); pw.println(packageName);
1847 }
1848 return 0;
1849 }
1850 case "write-settings": {
1851 shell.mInternal.mContext.enforcePermission(
1852 android.Manifest.permission.UPDATE_APP_OPS_STATS,
1853 Binder.getCallingPid(), Binder.getCallingUid(), null);
1854 long token = Binder.clearCallingIdentity();
1855 try {
1856 synchronized (shell.mInternal) {
1857 shell.mInternal.mHandler.removeCallbacks(shell.mInternal.mWriteRunner);
1858 }
1859 shell.mInternal.writeState();
1860 pw.println("Current settings written.");
1861 } finally {
1862 Binder.restoreCallingIdentity(token);
1863 }
1864 return 0;
1865 }
1866 case "read-settings": {
1867 shell.mInternal.mContext.enforcePermission(
1868 android.Manifest.permission.UPDATE_APP_OPS_STATS,
1869 Binder.getCallingPid(), Binder.getCallingUid(), null);
1870 long token = Binder.clearCallingIdentity();
1871 try {
1872 shell.mInternal.readState();
1873 pw.println("Last settings read.");
1874 } finally {
1875 Binder.restoreCallingIdentity(token);
1876 }
1877 return 0;
1878 }
1879 default:
1880 return shell.handleDefaultCommands(cmd);
1881 }
1882 } catch (RemoteException e) {
1883 pw.println("Remote exception: " + e);
1884 }
1885 return -1;
1886 }
1887
1888 private void dumpHelp(PrintWriter pw) {
1889 pw.println("AppOps service (appops) dump options:");
1890 pw.println(" none");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001891 }
1892
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001893 @Override
1894 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1895 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1896 != PackageManager.PERMISSION_GRANTED) {
1897 pw.println("Permission Denial: can't dump ApOps service from from pid="
1898 + Binder.getCallingPid()
1899 + ", uid=" + Binder.getCallingUid());
1900 return;
1901 }
1902
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001903 if (args != null) {
1904 for (int i=0; i<args.length; i++) {
1905 String arg = args[i];
1906 if ("-h".equals(arg)) {
1907 dumpHelp(pw);
1908 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07001909 } else if ("-a".equals(arg)) {
1910 // dump all data
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001911 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
1912 pw.println("Unknown option: " + arg);
1913 return;
1914 } else {
1915 pw.println("Unknown command: " + arg);
1916 return;
1917 }
1918 }
1919 }
1920
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001921 synchronized (this) {
1922 pw.println("Current AppOps Service state:");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001923 final long now = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001924 boolean needSep = false;
1925 if (mOpModeWatchers.size() > 0) {
1926 needSep = true;
1927 pw.println(" Op mode watchers:");
1928 for (int i=0; i<mOpModeWatchers.size(); i++) {
1929 pw.print(" Op "); pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
1930 pw.println(":");
1931 ArrayList<Callback> callbacks = mOpModeWatchers.valueAt(i);
1932 for (int j=0; j<callbacks.size(); j++) {
1933 pw.print(" #"); pw.print(j); pw.print(": ");
1934 pw.println(callbacks.get(j));
1935 }
1936 }
1937 }
1938 if (mPackageModeWatchers.size() > 0) {
1939 needSep = true;
1940 pw.println(" Package mode watchers:");
1941 for (int i=0; i<mPackageModeWatchers.size(); i++) {
1942 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
1943 pw.println(":");
1944 ArrayList<Callback> callbacks = mPackageModeWatchers.valueAt(i);
1945 for (int j=0; j<callbacks.size(); j++) {
1946 pw.print(" #"); pw.print(j); pw.print(": ");
1947 pw.println(callbacks.get(j));
1948 }
1949 }
1950 }
1951 if (mModeWatchers.size() > 0) {
1952 needSep = true;
1953 pw.println(" All mode watchers:");
1954 for (int i=0; i<mModeWatchers.size(); i++) {
1955 pw.print(" "); pw.print(mModeWatchers.keyAt(i));
1956 pw.print(" -> "); pw.println(mModeWatchers.valueAt(i));
1957 }
1958 }
1959 if (mClients.size() > 0) {
1960 needSep = true;
1961 pw.println(" Clients:");
1962 for (int i=0; i<mClients.size(); i++) {
1963 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
1964 ClientState cs = mClients.valueAt(i);
1965 pw.print(" "); pw.println(cs);
1966 if (cs.mStartedOps != null && cs.mStartedOps.size() > 0) {
1967 pw.println(" Started ops:");
1968 for (int j=0; j<cs.mStartedOps.size(); j++) {
1969 Op op = cs.mStartedOps.get(j);
1970 pw.print(" "); pw.print("uid="); pw.print(op.uid);
1971 pw.print(" pkg="); pw.print(op.packageName);
1972 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
1973 }
1974 }
1975 }
1976 }
John Spurlock1af30c72014-03-10 08:33:35 -04001977 if (mAudioRestrictions.size() > 0) {
1978 boolean printedHeader = false;
1979 for (int o=0; o<mAudioRestrictions.size(); o++) {
1980 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
1981 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
1982 for (int i=0; i<restrictions.size(); i++) {
1983 if (!printedHeader){
1984 pw.println(" Audio Restrictions:");
1985 printedHeader = true;
1986 needSep = true;
1987 }
John Spurlock7b414672014-07-18 13:02:39 -04001988 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04001989 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04001990 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04001991 Restriction r = restrictions.valueAt(i);
1992 pw.print(": mode="); pw.println(r.mode);
1993 if (!r.exceptionPackages.isEmpty()) {
1994 pw.println(" Exceptions:");
1995 for (int j=0; j<r.exceptionPackages.size(); j++) {
1996 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
1997 }
1998 }
1999 }
2000 }
2001 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002002 if (needSep) {
2003 pw.println();
2004 }
Svet Ganov2af57082015-07-30 08:44:20 -07002005 for (int i=0; i<mUidStates.size(); i++) {
2006 UidState uidState = mUidStates.valueAt(i);
2007
2008 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
2009
2010 SparseIntArray opModes = uidState.opModes;
2011 if (opModes != null) {
2012 final int opModeCount = opModes.size();
2013 for (int j = 0; j < opModeCount; j++) {
2014 final int code = opModes.keyAt(j);
2015 final int mode = opModes.valueAt(j);
2016 pw.print(" "); pw.print(AppOpsManager.opToName(code));
2017 pw.print(": mode="); pw.println(mode);
2018 }
2019 }
2020
2021 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
2022 if (pkgOps == null) {
2023 continue;
2024 }
2025
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002026 for (Ops ops : pkgOps.values()) {
2027 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
2028 for (int j=0; j<ops.size(); j++) {
2029 Op op = ops.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002030 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
2031 pw.print(": mode="); pw.print(op.mode);
2032 if (op.time != 0) {
2033 pw.print("; time="); TimeUtils.formatDuration(now-op.time, pw);
2034 pw.print(" ago");
2035 }
2036 if (op.rejectTime != 0) {
2037 pw.print("; rejectTime="); TimeUtils.formatDuration(now-op.rejectTime, pw);
2038 pw.print(" ago");
2039 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002040 if (op.duration == -1) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002041 pw.print(" (running)");
2042 } else if (op.duration != 0) {
2043 pw.print("; duration="); TimeUtils.formatDuration(op.duration, pw);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002044 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002045 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002046 }
2047 }
2048 }
2049 }
2050 }
John Spurlock1af30c72014-03-10 08:33:35 -04002051
2052 private static final class Restriction {
2053 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
2054 int mode;
2055 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
2056 }
Jason Monk62062992014-05-06 09:55:28 -04002057
2058 @Override
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002059 public void setUserRestrictions(Bundle restrictions, IBinder token, int userHandle) {
Jason Monk62062992014-05-06 09:55:28 -04002060 checkSystemUid("setUserRestrictions");
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002061 Preconditions.checkNotNull(token);
2062 final boolean[] opRestrictions = getOrCreateUserRestrictionsForToken(token, userHandle);
Jason Monk62062992014-05-06 09:55:28 -04002063 for (int i = 0; i < opRestrictions.length; ++i) {
2064 String restriction = AppOpsManager.opToRestriction(i);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002065 final boolean restricted = restriction != null
2066 && restrictions.getBoolean(restriction, false);
2067 setUserRestrictionNoCheck(i, restricted, token, userHandle);
2068 }
2069 }
2070
2071 @Override
2072 public void setUserRestriction(int code, boolean restricted, IBinder token, int userHandle) {
2073 if (Binder.getCallingPid() != Process.myPid()) {
2074 mContext.enforcePermission(Manifest.permission.MANAGE_APP_OPS_RESTRICTIONS,
2075 Binder.getCallingPid(), Binder.getCallingUid(), null);
2076 }
2077 if (userHandle != UserHandle.getCallingUserId()) {
2078 if (mContext.checkCallingOrSelfPermission(Manifest.permission
2079 .INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
2080 && mContext.checkCallingOrSelfPermission(Manifest.permission
2081 .INTERACT_ACROSS_USERS) != PackageManager.PERMISSION_GRANTED) {
2082 throw new SecurityException("Need INTERACT_ACROSS_USERS_FULL or"
2083 + " INTERACT_ACROSS_USERS to interact cross user ");
Jason Monk62062992014-05-06 09:55:28 -04002084 }
2085 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002086 verifyIncomingOp(code);
2087 Preconditions.checkNotNull(token);
2088 setUserRestrictionNoCheck(code, restricted, token, userHandle);
2089 }
2090
2091 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
2092 int userHandle) {
2093 final boolean[] opRestrictions = getOrCreateUserRestrictionsForToken(token, userHandle);
2094 if (opRestrictions[code] == restricted) {
2095 return;
2096 }
2097 opRestrictions[code] = restricted;
2098 if (!restricted) {
2099 pruneUserRestrictionsForToken(token, userHandle);
2100 }
2101
2102 final ArrayList<Callback> clonedCallbacks;
2103 synchronized (this) {
2104 ArrayList<Callback> callbacks = mOpModeWatchers.get(code);
2105 if (callbacks == null) {
2106 return;
2107 }
2108 clonedCallbacks = new ArrayList<>(callbacks);
2109 }
2110
2111 // There are components watching for mode changes such as window manager
2112 // and location manager which are in our process. The callbacks in these
2113 // components may require permissions our remote caller does not have.
2114 final long identity = Binder.clearCallingIdentity();
2115 try {
2116 final int callbackCount = clonedCallbacks.size();
2117 for (int i = 0; i < callbackCount; i++) {
2118 Callback callback = clonedCallbacks.get(i);
2119 try {
2120 callback.mCallback.opChanged(code, -1, null);
2121 } catch (RemoteException e) {
2122 Log.w(TAG, "Error dispatching op op change", e);
2123 }
2124 }
2125 } finally {
2126 Binder.restoreCallingIdentity(identity);
2127 }
Jason Monk62062992014-05-06 09:55:28 -04002128 }
2129
2130 @Override
2131 public void removeUser(int userHandle) throws RemoteException {
2132 checkSystemUid("removeUser");
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002133 final int tokenCount = mOpUserRestrictions.size();
2134 for (int i = tokenCount - 1; i >= 0; i--) {
2135 SparseArray<boolean[]> opRestrictions = mOpUserRestrictions.valueAt(i);
2136 if (opRestrictions != null) {
2137 opRestrictions.remove(userHandle);
2138 if (opRestrictions.size() <= 0) {
2139 mOpUserRestrictions.removeAt(i);
2140 }
2141 }
2142 }
2143 }
2144
2145
2146 private void pruneUserRestrictionsForToken(IBinder token, int userHandle) {
2147 SparseArray<boolean[]> perTokenRestrictions = mOpUserRestrictions.get(token);
2148 if (perTokenRestrictions != null) {
2149 final boolean[] opRestrictions = perTokenRestrictions.get(userHandle);
2150 if (opRestrictions != null) {
2151 for (boolean restriction : opRestrictions) {
2152 if (restriction) {
2153 return;
2154 }
2155 }
2156 perTokenRestrictions.remove(userHandle);
2157 if (perTokenRestrictions.size() <= 0) {
2158 mOpUserRestrictions.remove(token);
2159 }
2160 }
2161 }
2162 }
2163
2164 private boolean[] getOrCreateUserRestrictionsForToken(IBinder token, int userHandle) {
2165 SparseArray<boolean[]> perTokenRestrictions = mOpUserRestrictions.get(token);
2166 if (perTokenRestrictions == null) {
2167 perTokenRestrictions = new SparseArray<>();
2168 mOpUserRestrictions.put(token, perTokenRestrictions);
2169 }
2170 boolean[] opRestrictions = perTokenRestrictions.get(userHandle);
2171 if (opRestrictions == null) {
2172 opRestrictions = new boolean[AppOpsManager._NUM_OP];
2173 perTokenRestrictions.put(userHandle, opRestrictions);
2174 }
2175 return opRestrictions;
Jason Monk62062992014-05-06 09:55:28 -04002176 }
2177
2178 private void checkSystemUid(String function) {
2179 int uid = Binder.getCallingUid();
2180 if (uid != Process.SYSTEM_UID) {
2181 throw new SecurityException(function + " must by called by the system");
2182 }
2183 }
2184
Svet Ganov2af57082015-07-30 08:44:20 -07002185 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07002186 String[] packageNames = null;
Svet Ganov2af57082015-07-30 08:44:20 -07002187 try {
riddle_hsu40b300f2015-11-23 13:22:03 +08002188 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -07002189 } catch (RemoteException e) {
2190 /* ignore - local call */
2191 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07002192 if (packageNames == null) {
2193 return EmptyArray.STRING;
2194 }
2195 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07002196 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002197}