blob: e6e69b1c604766b09ceb6f306b6c2230eee0c287 [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
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -080034import android.app.ActivityManager;
Jason Monk1c7c3192014-06-26 12:52:18 -040035import android.app.ActivityThread;
Svet Ganov2af57082015-07-30 08:44:20 -070036import android.app.AppGlobals;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080037import android.app.AppOpsManager;
38import android.content.Context;
Jason Monk1c7c3192014-06-26 12:52:18 -040039import android.content.pm.ApplicationInfo;
40import android.content.pm.IPackageManager;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080041import android.content.pm.PackageManager;
John Spurlock7b414672014-07-18 13:02:39 -040042import android.media.AudioAttributes;
Dianne Hackborn35654b62013-01-14 17:38:02 -080043import android.os.AsyncTask;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080044import android.os.Binder;
Jason Monk62062992014-05-06 09:55:28 -040045import android.os.Bundle;
Dianne Hackborn35654b62013-01-14 17:38:02 -080046import android.os.Handler;
Dianne Hackbornc2293022013-02-06 23:14:49 -080047import android.os.IBinder;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080048import android.os.Process;
Dianne Hackbornc2293022013-02-06 23:14:49 -080049import android.os.RemoteException;
Dianne Hackborn268e4e32015-11-18 16:29:56 -080050import android.os.ResultReceiver;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080051import android.os.ServiceManager;
Dianne Hackborn268e4e32015-11-18 16:29:56 -080052import android.os.ShellCommand;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080053import android.os.UserHandle;
Svet Ganov6ee871e2015-07-10 14:29:33 -070054import android.os.storage.MountServiceInternal;
Dianne Hackborne98f5db2013-07-17 17:23:25 -070055import android.util.ArrayMap;
John Spurlock1af30c72014-03-10 08:33:35 -040056import android.util.ArraySet;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080057import android.util.AtomicFile;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -080058import android.util.Log;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080059import android.util.Slog;
60import android.util.SparseArray;
Svet Ganov2af57082015-07-30 08:44:20 -070061import android.util.SparseIntArray;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080062import android.util.TimeUtils;
Dianne Hackborn35654b62013-01-14 17:38:02 -080063import android.util.Xml;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080064
65import com.android.internal.app.IAppOpsService;
Dianne Hackbornc2293022013-02-06 23:14:49 -080066import com.android.internal.app.IAppOpsCallback;
Svet Ganov6ee871e2015-07-10 14:29:33 -070067import com.android.internal.os.Zygote;
Svet Ganov2af57082015-07-30 08:44:20 -070068import com.android.internal.util.ArrayUtils;
Dianne Hackborn35654b62013-01-14 17:38:02 -080069import com.android.internal.util.FastXmlSerializer;
70import com.android.internal.util.XmlUtils;
71
Svet Ganov2af57082015-07-30 08:44:20 -070072import libcore.util.EmptyArray;
Dianne Hackborn35654b62013-01-14 17:38:02 -080073import org.xmlpull.v1.XmlPullParser;
74import org.xmlpull.v1.XmlPullParserException;
75import org.xmlpull.v1.XmlSerializer;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080076
77public class AppOpsService extends IAppOpsService.Stub {
78 static final String TAG = "AppOps";
Dianne Hackborn35654b62013-01-14 17:38:02 -080079 static final boolean DEBUG = false;
80
81 // Write at most every 30 minutes.
82 static final long WRITE_DELAY = DEBUG ? 1000 : 30*60*1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080083
84 Context mContext;
85 final AtomicFile mFile;
Dianne Hackborn35654b62013-01-14 17:38:02 -080086 final Handler mHandler;
87
88 boolean mWriteScheduled;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -080089 boolean mFastWriteScheduled;
Dianne Hackborn35654b62013-01-14 17:38:02 -080090 final Runnable mWriteRunner = new Runnable() {
91 public void run() {
92 synchronized (AppOpsService.this) {
93 mWriteScheduled = false;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -080094 mFastWriteScheduled = false;
Dianne Hackborn35654b62013-01-14 17:38:02 -080095 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
96 @Override protected Void doInBackground(Void... params) {
97 writeState();
98 return null;
99 }
100 };
101 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
102 }
103 }
104 };
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800105
Svet Ganov2af57082015-07-30 08:44:20 -0700106 final SparseArray<UidState> mUidStates = new SparseArray<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800107
Jason Monk62062992014-05-06 09:55:28 -0400108 private final SparseArray<boolean[]> mOpRestrictions = new SparseArray<boolean[]>();
109
Svet Ganov2af57082015-07-30 08:44:20 -0700110 private static final class UidState {
111 public final int uid;
112 public ArrayMap<String, Ops> pkgOps;
113 public SparseIntArray opModes;
114
115 public UidState(int uid) {
116 this.uid = uid;
117 }
118
119 public void clear() {
120 pkgOps = null;
121 opModes = null;
122 }
123
124 public boolean isDefault() {
125 return (pkgOps == null || pkgOps.isEmpty())
126 && (opModes == null || opModes.size() <= 0);
127 }
128 }
129
Dianne Hackbornc2293022013-02-06 23:14:49 -0800130 public final static class Ops extends SparseArray<Op> {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800131 public final String packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700132 public final UidState uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400133 public final boolean isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800134
Svet Ganov2af57082015-07-30 08:44:20 -0700135 public Ops(String _packageName, UidState _uidState, boolean _isPrivileged) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800136 packageName = _packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700137 uidState = _uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400138 isPrivileged = _isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800139 }
140 }
141
Dianne Hackbornc2293022013-02-06 23:14:49 -0800142 public final static class Op {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700143 public final int uid;
144 public final String packageName;
Svet Ganov99b60432015-06-27 13:15:22 -0700145 public int proxyUid = -1;
146 public String proxyPackageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800147 public final int op;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800148 public int mode;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800149 public int duration;
150 public long time;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800151 public long rejectTime;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800152 public int nesting;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800153
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700154 public Op(int _uid, String _packageName, int _op) {
155 uid = _uid;
156 packageName = _packageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800157 op = _op;
David Braunf5d83192013-09-16 13:43:51 -0700158 mode = AppOpsManager.opToDefaultMode(op);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800159 }
160 }
161
Dianne Hackbornc2293022013-02-06 23:14:49 -0800162 final SparseArray<ArrayList<Callback>> mOpModeWatchers
163 = new SparseArray<ArrayList<Callback>>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700164 final ArrayMap<String, ArrayList<Callback>> mPackageModeWatchers
165 = new ArrayMap<String, ArrayList<Callback>>();
166 final ArrayMap<IBinder, Callback> mModeWatchers
167 = new ArrayMap<IBinder, Callback>();
John Spurlock1af30c72014-03-10 08:33:35 -0400168 final SparseArray<SparseArray<Restriction>> mAudioRestrictions
169 = new SparseArray<SparseArray<Restriction>>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800170
171 public final class Callback implements DeathRecipient {
172 final IAppOpsCallback mCallback;
173
174 public Callback(IAppOpsCallback callback) {
175 mCallback = callback;
176 try {
177 mCallback.asBinder().linkToDeath(this, 0);
178 } catch (RemoteException e) {
179 }
180 }
181
182 public void unlinkToDeath() {
183 mCallback.asBinder().unlinkToDeath(this, 0);
184 }
185
186 @Override
187 public void binderDied() {
188 stopWatchingMode(mCallback);
189 }
190 }
191
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700192 final ArrayMap<IBinder, ClientState> mClients = new ArrayMap<IBinder, ClientState>();
193
194 public final class ClientState extends Binder implements DeathRecipient {
195 final IBinder mAppToken;
196 final int mPid;
197 final ArrayList<Op> mStartedOps;
198
199 public ClientState(IBinder appToken) {
200 mAppToken = appToken;
201 mPid = Binder.getCallingPid();
202 if (appToken instanceof Binder) {
203 // For local clients, there is no reason to track them.
204 mStartedOps = null;
205 } else {
206 mStartedOps = new ArrayList<Op>();
207 try {
208 mAppToken.linkToDeath(this, 0);
209 } catch (RemoteException e) {
210 }
211 }
212 }
213
214 @Override
215 public String toString() {
216 return "ClientState{" +
217 "mAppToken=" + mAppToken +
218 ", " + (mStartedOps != null ? ("pid=" + mPid) : "local") +
219 '}';
220 }
221
222 @Override
223 public void binderDied() {
224 synchronized (AppOpsService.this) {
225 for (int i=mStartedOps.size()-1; i>=0; i--) {
226 finishOperationLocked(mStartedOps.get(i));
227 }
228 mClients.remove(mAppToken);
229 }
230 }
231 }
232
Jeff Brown6f357d32014-01-15 20:40:55 -0800233 public AppOpsService(File storagePath, Handler handler) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800234 mFile = new AtomicFile(storagePath);
Jeff Brown6f357d32014-01-15 20:40:55 -0800235 mHandler = handler;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800236 readState();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800237 }
David Braunf5d83192013-09-16 13:43:51 -0700238
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800239 public void publish(Context context) {
240 mContext = context;
241 ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
242 }
243
Dianne Hackborn514074f2013-02-11 10:52:46 -0800244 public void systemReady() {
245 synchronized (this) {
246 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700247 for (int i = mUidStates.size() - 1; i >= 0; i--) {
248 UidState uidState = mUidStates.valueAt(i);
249
250 String[] packageNames = getPackagesForUid(uidState.uid);
251 if (ArrayUtils.isEmpty(packageNames)) {
252 uidState.clear();
253 mUidStates.removeAt(i);
254 changed = true;
255 continue;
256 }
257
258 ArrayMap<String, Ops> pkgs = uidState.pkgOps;
259 if (pkgs == null) {
260 continue;
261 }
262
Dianne Hackborn514074f2013-02-11 10:52:46 -0800263 Iterator<Ops> it = pkgs.values().iterator();
264 while (it.hasNext()) {
265 Ops ops = it.next();
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700266 int curUid = -1;
Dianne Hackborn514074f2013-02-11 10:52:46 -0800267 try {
Jeff Sharkeycd654482016-01-08 17:42:11 -0700268 curUid = AppGlobals.getPackageManager().getPackageUid(ops.packageName,
269 PackageManager.MATCH_UNINSTALLED_PACKAGES,
Svet Ganov2af57082015-07-30 08:44:20 -0700270 UserHandle.getUserId(ops.uidState.uid));
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700271 } catch (RemoteException ignored) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800272 }
Svet Ganov2af57082015-07-30 08:44:20 -0700273 if (curUid != ops.uidState.uid) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800274 Slog.i(TAG, "Pruning old package " + ops.packageName
Svet Ganov2af57082015-07-30 08:44:20 -0700275 + "/" + ops.uidState + ": new uid=" + curUid);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800276 it.remove();
277 changed = true;
278 }
279 }
Svet Ganov2af57082015-07-30 08:44:20 -0700280
281 if (uidState.isDefault()) {
282 mUidStates.removeAt(i);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800283 }
284 }
285 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800286 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800287 }
288 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700289
290 MountServiceInternal mountServiceInternal = LocalServices.getService(
291 MountServiceInternal.class);
292 mountServiceInternal.addExternalStoragePolicy(
293 new MountServiceInternal.ExternalStorageMountPolicy() {
294 @Override
295 public int getMountMode(int uid, String packageName) {
296 if (Process.isIsolated(uid)) {
297 return Zygote.MOUNT_EXTERNAL_NONE;
298 }
299 if (noteOperation(AppOpsManager.OP_READ_EXTERNAL_STORAGE, uid,
300 packageName) != AppOpsManager.MODE_ALLOWED) {
301 return Zygote.MOUNT_EXTERNAL_NONE;
302 }
303 if (noteOperation(AppOpsManager.OP_WRITE_EXTERNAL_STORAGE, uid,
304 packageName) != AppOpsManager.MODE_ALLOWED) {
305 return Zygote.MOUNT_EXTERNAL_READ;
306 }
307 return Zygote.MOUNT_EXTERNAL_WRITE;
308 }
309
310 @Override
311 public boolean hasExternalStorage(int uid, String packageName) {
312 final int mountMode = getMountMode(uid, packageName);
313 return mountMode == Zygote.MOUNT_EXTERNAL_READ
314 || mountMode == Zygote.MOUNT_EXTERNAL_WRITE;
315 }
316 });
Dianne Hackborn514074f2013-02-11 10:52:46 -0800317 }
318
319 public void packageRemoved(int uid, String packageName) {
320 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700321 UidState uidState = mUidStates.get(uid);
322 if (uidState == null) {
323 return;
324 }
325
326 boolean changed = false;
327
328 // Remove any package state if such.
329 if (uidState.pkgOps != null && uidState.pkgOps.remove(packageName) != null) {
330 changed = true;
331 }
332
333 // If we just nuked the last package state check if the UID is valid.
334 if (changed && uidState.pkgOps.isEmpty()
335 && getPackagesForUid(uid).length <= 0) {
336 mUidStates.remove(uid);
337 }
338
339 if (changed) {
340 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800341 }
342 }
343 }
344
345 public void uidRemoved(int uid) {
346 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700347 if (mUidStates.indexOfKey(uid) >= 0) {
348 mUidStates.remove(uid);
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800349 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800350 }
351 }
352 }
353
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800354 public void shutdown() {
355 Slog.w(TAG, "Writing app ops before shutdown...");
Dianne Hackborn35654b62013-01-14 17:38:02 -0800356 boolean doWrite = false;
357 synchronized (this) {
358 if (mWriteScheduled) {
359 mWriteScheduled = false;
360 doWrite = true;
361 }
362 }
363 if (doWrite) {
364 writeState();
365 }
366 }
367
Dianne Hackborn72e39832013-01-18 18:36:09 -0800368 private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
369 ArrayList<AppOpsManager.OpEntry> resOps = null;
370 if (ops == null) {
371 resOps = new ArrayList<AppOpsManager.OpEntry>();
372 for (int j=0; j<pkgOps.size(); j++) {
373 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800374 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Svet Ganov99b60432015-06-27 13:15:22 -0700375 curOp.rejectTime, curOp.duration, curOp.proxyUid,
376 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800377 }
378 } else {
379 for (int j=0; j<ops.length; j++) {
380 Op curOp = pkgOps.get(ops[j]);
381 if (curOp != null) {
382 if (resOps == null) {
383 resOps = new ArrayList<AppOpsManager.OpEntry>();
384 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800385 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Svet Ganov99b60432015-06-27 13:15:22 -0700386 curOp.rejectTime, curOp.duration, curOp.proxyUid,
387 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800388 }
389 }
390 }
391 return resOps;
392 }
393
Dianne Hackborn35654b62013-01-14 17:38:02 -0800394 @Override
395 public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
396 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
397 Binder.getCallingPid(), Binder.getCallingUid(), null);
398 ArrayList<AppOpsManager.PackageOps> res = null;
399 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700400 final int uidStateCount = mUidStates.size();
401 for (int i = 0; i < uidStateCount; i++) {
402 UidState uidState = mUidStates.valueAt(i);
403 if (uidState.pkgOps == null || uidState.pkgOps.isEmpty()) {
404 continue;
405 }
406 ArrayMap<String, Ops> packages = uidState.pkgOps;
407 final int packageCount = packages.size();
408 for (int j = 0; j < packageCount; j++) {
409 Ops pkgOps = packages.valueAt(j);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800410 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800411 if (resOps != null) {
412 if (res == null) {
413 res = new ArrayList<AppOpsManager.PackageOps>();
414 }
415 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700416 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800417 res.add(resPackage);
418 }
419 }
420 }
421 }
422 return res;
423 }
424
425 @Override
Dianne Hackborn72e39832013-01-18 18:36:09 -0800426 public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
427 int[] ops) {
428 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
429 Binder.getCallingPid(), Binder.getCallingUid(), null);
430 synchronized (this) {
431 Ops pkgOps = getOpsLocked(uid, packageName, false);
432 if (pkgOps == null) {
433 return null;
434 }
435 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
436 if (resOps == null) {
437 return null;
438 }
439 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
440 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700441 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800442 res.add(resPackage);
443 return res;
444 }
445 }
446
Dianne Hackborn607b4142013-08-02 18:10:10 -0700447 private void pruneOp(Op op, int uid, String packageName) {
448 if (op.time == 0 && op.rejectTime == 0) {
449 Ops ops = getOpsLocked(uid, packageName, false);
450 if (ops != null) {
451 ops.remove(op.op);
452 if (ops.size() <= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -0700453 UidState uidState = ops.uidState;
454 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700455 if (pkgOps != null) {
456 pkgOps.remove(ops.packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700457 if (pkgOps.isEmpty()) {
458 uidState.pkgOps = null;
459 }
460 if (uidState.isDefault()) {
461 mUidStates.remove(uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700462 }
463 }
464 }
465 }
466 }
467 }
468
Dianne Hackborn72e39832013-01-18 18:36:09 -0800469 @Override
Svet Ganov2af57082015-07-30 08:44:20 -0700470 public void setUidMode(int code, int uid, int mode) {
471 if (Binder.getCallingPid() != Process.myPid()) {
472 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
473 Binder.getCallingPid(), Binder.getCallingUid(), null);
474 }
475 verifyIncomingOp(code);
476 code = AppOpsManager.opToSwitch(code);
477
478 synchronized (this) {
479 final int defaultMode = AppOpsManager.opToDefaultMode(code);
480
481 UidState uidState = getUidStateLocked(uid, false);
482 if (uidState == null) {
483 if (mode == defaultMode) {
484 return;
485 }
486 uidState = new UidState(uid);
487 uidState.opModes = new SparseIntArray();
488 uidState.opModes.put(code, mode);
489 mUidStates.put(uid, uidState);
490 scheduleWriteLocked();
491 } else if (uidState.opModes == null) {
492 if (mode != defaultMode) {
493 uidState.opModes = new SparseIntArray();
494 uidState.opModes.put(code, mode);
495 scheduleWriteLocked();
496 }
497 } else {
498 if (uidState.opModes.get(code) == mode) {
499 return;
500 }
501 if (mode == defaultMode) {
502 uidState.opModes.delete(code);
503 if (uidState.opModes.size() <= 0) {
504 uidState.opModes = null;
505 }
506 } else {
507 uidState.opModes.put(code, mode);
508 }
509 scheduleWriteLocked();
510 }
511 }
512
Svetoslav215b44a2015-08-04 19:03:40 -0700513 String[] uidPackageNames = getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -0700514 ArrayMap<Callback, ArraySet<String>> callbackSpecs = null;
515
riddle_hsu40b300f2015-11-23 13:22:03 +0800516 synchronized (this) {
517 ArrayList<Callback> callbacks = mOpModeWatchers.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -0700518 if (callbacks != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700519 final int callbackCount = callbacks.size();
520 for (int i = 0; i < callbackCount; i++) {
521 Callback callback = callbacks.get(i);
riddle_hsu40b300f2015-11-23 13:22:03 +0800522 ArraySet<String> changedPackages = new ArraySet<>();
523 Collections.addAll(changedPackages, uidPackageNames);
524 callbackSpecs = new ArrayMap<>();
525 callbackSpecs.put(callback, changedPackages);
526 }
527 }
528
529 for (String uidPackageName : uidPackageNames) {
530 callbacks = mPackageModeWatchers.get(uidPackageName);
531 if (callbacks != null) {
532 if (callbackSpecs == null) {
533 callbackSpecs = new ArrayMap<>();
Svet Ganov2af57082015-07-30 08:44:20 -0700534 }
riddle_hsu40b300f2015-11-23 13:22:03 +0800535 final int callbackCount = callbacks.size();
536 for (int i = 0; i < callbackCount; i++) {
537 Callback callback = callbacks.get(i);
538 ArraySet<String> changedPackages = callbackSpecs.get(callback);
539 if (changedPackages == null) {
540 changedPackages = new ArraySet<>();
541 callbackSpecs.put(callback, changedPackages);
542 }
543 changedPackages.add(uidPackageName);
544 }
Svet Ganov2af57082015-07-30 08:44:20 -0700545 }
546 }
547 }
548
549 if (callbackSpecs == null) {
550 return;
551 }
552
553 // There are components watching for mode changes such as window manager
554 // and location manager which are in our process. The callbacks in these
555 // components may require permissions our remote caller does not have.
556 final long identity = Binder.clearCallingIdentity();
557 try {
558 for (int i = 0; i < callbackSpecs.size(); i++) {
559 Callback callback = callbackSpecs.keyAt(i);
560 ArraySet<String> reportedPackageNames = callbackSpecs.valueAt(i);
561 try {
562 if (reportedPackageNames == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700563 callback.mCallback.opChanged(code, uid, null);
Svet Ganov2af57082015-07-30 08:44:20 -0700564 } else {
565 final int reportedPackageCount = reportedPackageNames.size();
566 for (int j = 0; j < reportedPackageCount; j++) {
567 String reportedPackageName = reportedPackageNames.valueAt(j);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700568 callback.mCallback.opChanged(code, uid, reportedPackageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700569 }
570 }
571 } catch (RemoteException e) {
572 Log.w(TAG, "Error dispatching op op change", e);
573 }
574 }
575 } finally {
576 Binder.restoreCallingIdentity(identity);
577 }
578 }
579
580 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800581 public void setMode(int code, int uid, String packageName, int mode) {
Dianne Hackbornb64afe12014-07-22 16:29:04 -0700582 if (Binder.getCallingPid() != Process.myPid()) {
583 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
584 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborn133b9df2014-07-01 13:06:10 -0700585 }
Dianne Hackborn961321f2013-02-05 17:22:41 -0800586 verifyIncomingOp(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800587 ArrayList<Callback> repCbs = null;
588 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800589 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700590 UidState uidState = getUidStateLocked(uid, false);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800591 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800592 if (op != null) {
593 if (op.mode != mode) {
594 op.mode = mode;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800595 ArrayList<Callback> cbs = mOpModeWatchers.get(code);
596 if (cbs != null) {
597 if (repCbs == null) {
598 repCbs = new ArrayList<Callback>();
599 }
600 repCbs.addAll(cbs);
601 }
602 cbs = mPackageModeWatchers.get(packageName);
603 if (cbs != null) {
604 if (repCbs == null) {
605 repCbs = new ArrayList<Callback>();
606 }
607 repCbs.addAll(cbs);
608 }
David Braunf5d83192013-09-16 13:43:51 -0700609 if (mode == AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800610 // If going into the default mode, prune this op
611 // if there is nothing else interesting in it.
Dianne Hackborn607b4142013-08-02 18:10:10 -0700612 pruneOp(op, uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800613 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800614 scheduleFastWriteLocked();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800615 }
616 }
617 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800618 if (repCbs != null) {
Svet Ganov38536112015-05-19 12:45:52 -0700619 // There are components watching for mode changes such as window manager
620 // and location manager which are in our process. The callbacks in these
621 // components may require permissions our remote caller does not have.
622 final long identity = Binder.clearCallingIdentity();
623 try {
624 for (int i = 0; i < repCbs.size(); i++) {
625 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700626 repCbs.get(i).mCallback.opChanged(code, uid, packageName);
Svet Ganov38536112015-05-19 12:45:52 -0700627 } catch (RemoteException e) {
628 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800629 }
Svet Ganov38536112015-05-19 12:45:52 -0700630 } finally {
631 Binder.restoreCallingIdentity(identity);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800632 }
633 }
634 }
635
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700636 private static HashMap<Callback, ArrayList<ChangeRec>> addCallbacks(
637 HashMap<Callback, ArrayList<ChangeRec>> callbacks,
638 int op, int uid, String packageName, ArrayList<Callback> cbs) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700639 if (cbs == null) {
640 return callbacks;
641 }
642 if (callbacks == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700643 callbacks = new HashMap<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700644 }
Svet Ganov2af57082015-07-30 08:44:20 -0700645 boolean duplicate = false;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700646 for (int i=0; i<cbs.size(); i++) {
647 Callback cb = cbs.get(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700648 ArrayList<ChangeRec> reports = callbacks.get(cb);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700649 if (reports == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700650 reports = new ArrayList<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700651 callbacks.put(cb, reports);
Svet Ganov2af57082015-07-30 08:44:20 -0700652 } else {
653 final int reportCount = reports.size();
654 for (int j = 0; j < reportCount; j++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700655 ChangeRec report = reports.get(j);
656 if (report.op == op && report.pkg.equals(packageName)) {
Svet Ganov2af57082015-07-30 08:44:20 -0700657 duplicate = true;
658 break;
659 }
660 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700661 }
Svet Ganov2af57082015-07-30 08:44:20 -0700662 if (!duplicate) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700663 reports.add(new ChangeRec(op, uid, packageName));
Svet Ganov2af57082015-07-30 08:44:20 -0700664 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700665 }
666 return callbacks;
667 }
668
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700669 static final class ChangeRec {
670 final int op;
671 final int uid;
672 final String pkg;
673
674 ChangeRec(int _op, int _uid, String _pkg) {
675 op = _op;
676 uid = _uid;
677 pkg = _pkg;
678 }
679 }
680
Dianne Hackborn607b4142013-08-02 18:10:10 -0700681 @Override
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800682 public void resetAllModes(int reqUserId, String reqPackageName) {
683 final int callingPid = Binder.getCallingPid();
684 final int callingUid = Binder.getCallingUid();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700685 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800686 callingPid, callingUid, null);
687 reqUserId = ActivityManager.handleIncomingUser(callingPid, callingUid, reqUserId,
688 true, true, "resetAllModes", null);
Svet Ganov2af57082015-07-30 08:44:20 -0700689
690 int reqUid = -1;
691 if (reqPackageName != null) {
692 try {
693 reqUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -0700694 reqPackageName, PackageManager.MATCH_UNINSTALLED_PACKAGES, reqUserId);
Svet Ganov2af57082015-07-30 08:44:20 -0700695 } catch (RemoteException e) {
696 /* ignore - local call */
697 }
698 }
699
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700700 HashMap<Callback, ArrayList<ChangeRec>> callbacks = null;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700701 synchronized (this) {
702 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700703 for (int i = mUidStates.size() - 1; i >= 0; i--) {
704 UidState uidState = mUidStates.valueAt(i);
705
706 SparseIntArray opModes = uidState.opModes;
707 if (opModes != null && (uidState.uid == reqUid || reqUid == -1)) {
708 final int uidOpCount = opModes.size();
709 for (int j = uidOpCount - 1; j >= 0; j--) {
710 final int code = opModes.keyAt(j);
711 if (AppOpsManager.opAllowsReset(code)) {
712 opModes.removeAt(j);
713 if (opModes.size() <= 0) {
714 uidState.opModes = null;
715 }
716 for (String packageName : getPackagesForUid(uidState.uid)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700717 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700718 mOpModeWatchers.get(code));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700719 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700720 mPackageModeWatchers.get(packageName));
721 }
722 }
723 }
724 }
725
726 if (uidState.pkgOps == null) {
727 continue;
728 }
729
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800730 if (reqUserId != UserHandle.USER_ALL
Svet Ganov2af57082015-07-30 08:44:20 -0700731 && reqUserId != UserHandle.getUserId(uidState.uid)) {
Alexandra Gherghinad6a98972014-08-04 17:05:34 +0100732 // Skip any ops for a different user
733 continue;
734 }
Svet Ganov2af57082015-07-30 08:44:20 -0700735
736 Map<String, Ops> packages = uidState.pkgOps;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700737 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
738 while (it.hasNext()) {
739 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700740 String packageName = ent.getKey();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800741 if (reqPackageName != null && !reqPackageName.equals(packageName)) {
742 // Skip any ops for a different package
743 continue;
744 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700745 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700746 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700747 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -0700748 if (AppOpsManager.opAllowsReset(curOp.op)
749 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -0700750 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700751 changed = true;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700752 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -0700753 mOpModeWatchers.get(curOp.op));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700754 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -0700755 mPackageModeWatchers.get(packageName));
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700756 if (curOp.time == 0 && curOp.rejectTime == 0) {
757 pkgOps.removeAt(j);
758 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700759 }
760 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700761 if (pkgOps.size() == 0) {
762 it.remove();
763 }
764 }
Svet Ganov2af57082015-07-30 08:44:20 -0700765 if (uidState.isDefault()) {
766 mUidStates.remove(uidState.uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700767 }
768 }
Svet Ganov2af57082015-07-30 08:44:20 -0700769
Dianne Hackborn607b4142013-08-02 18:10:10 -0700770 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800771 scheduleFastWriteLocked();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700772 }
773 }
774 if (callbacks != null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700775 for (Map.Entry<Callback, ArrayList<ChangeRec>> ent : callbacks.entrySet()) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700776 Callback cb = ent.getKey();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700777 ArrayList<ChangeRec> reports = ent.getValue();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700778 for (int i=0; i<reports.size(); i++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700779 ChangeRec rep = reports.get(i);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700780 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700781 cb.mCallback.opChanged(rep.op, rep.uid, rep.pkg);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700782 } catch (RemoteException e) {
783 }
784 }
785 }
786 }
787 }
788
Dianne Hackbornc2293022013-02-06 23:14:49 -0800789 @Override
790 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -0800791 if (callback == null) {
792 return;
793 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800794 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700795 op = (op != AppOpsManager.OP_NONE) ? AppOpsManager.opToSwitch(op) : op;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800796 Callback cb = mModeWatchers.get(callback.asBinder());
797 if (cb == null) {
798 cb = new Callback(callback);
799 mModeWatchers.put(callback.asBinder(), cb);
800 }
801 if (op != AppOpsManager.OP_NONE) {
802 ArrayList<Callback> cbs = mOpModeWatchers.get(op);
803 if (cbs == null) {
804 cbs = new ArrayList<Callback>();
805 mOpModeWatchers.put(op, cbs);
806 }
807 cbs.add(cb);
808 }
809 if (packageName != null) {
810 ArrayList<Callback> cbs = mPackageModeWatchers.get(packageName);
811 if (cbs == null) {
812 cbs = new ArrayList<Callback>();
813 mPackageModeWatchers.put(packageName, cbs);
814 }
815 cbs.add(cb);
816 }
817 }
818 }
819
820 @Override
821 public void stopWatchingMode(IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -0800822 if (callback == null) {
823 return;
824 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800825 synchronized (this) {
826 Callback cb = mModeWatchers.remove(callback.asBinder());
827 if (cb != null) {
828 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700829 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800830 ArrayList<Callback> cbs = mOpModeWatchers.valueAt(i);
831 cbs.remove(cb);
832 if (cbs.size() <= 0) {
833 mOpModeWatchers.removeAt(i);
834 }
835 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700836 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
837 ArrayList<Callback> cbs = mPackageModeWatchers.valueAt(i);
838 cbs.remove(cb);
839 if (cbs.size() <= 0) {
840 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800841 }
842 }
843 }
844 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800845 }
846
847 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700848 public IBinder getToken(IBinder clientToken) {
849 synchronized (this) {
850 ClientState cs = mClients.get(clientToken);
851 if (cs == null) {
852 cs = new ClientState(clientToken);
853 mClients.put(clientToken, cs);
854 }
855 return cs;
856 }
857 }
858
859 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800860 public int checkOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800861 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800862 verifyIncomingOp(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800863 synchronized (this) {
Jason Monk1c7c3192014-06-26 12:52:18 -0400864 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -0400865 return AppOpsManager.MODE_IGNORED;
866 }
Svet Ganov2af57082015-07-30 08:44:20 -0700867 code = AppOpsManager.opToSwitch(code);
868 UidState uidState = getUidStateLocked(uid, false);
869 if (uidState != null && uidState.opModes != null) {
870 final int uidMode = uidState.opModes.get(code);
871 if (uidMode != AppOpsManager.MODE_ALLOWED) {
872 return uidMode;
873 }
874 }
875 Op op = getOpLocked(code, uid, packageName, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800876 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -0700877 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800878 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800879 return op.mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800880 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800881 }
882
883 @Override
John Spurlock7b414672014-07-18 13:02:39 -0400884 public int checkAudioOperation(int code, int usage, int uid, String packageName) {
John Spurlock1af30c72014-03-10 08:33:35 -0400885 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -0400886 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -0400887 if (mode != AppOpsManager.MODE_ALLOWED) {
888 return mode;
889 }
890 }
891 return checkOperation(code, uid, packageName);
892 }
893
John Spurlock7b414672014-07-18 13:02:39 -0400894 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
895 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
896 if (usageRestrictions != null) {
897 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -0400898 if (r != null && !r.exceptionPackages.contains(packageName)) {
899 return r.mode;
900 }
901 }
902 return AppOpsManager.MODE_ALLOWED;
903 }
904
905 @Override
John Spurlock7b414672014-07-18 13:02:39 -0400906 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -0400907 String[] exceptionPackages) {
908 verifyIncomingUid(uid);
909 verifyIncomingOp(code);
910 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -0400911 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
912 if (usageRestrictions == null) {
913 usageRestrictions = new SparseArray<Restriction>();
914 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -0400915 }
John Spurlock7b414672014-07-18 13:02:39 -0400916 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -0400917 if (mode != AppOpsManager.MODE_ALLOWED) {
918 final Restriction r = new Restriction();
919 r.mode = mode;
920 if (exceptionPackages != null) {
921 final int N = exceptionPackages.length;
922 r.exceptionPackages = new ArraySet<String>(N);
923 for (int i = 0; i < N; i++) {
924 final String pkg = exceptionPackages[i];
925 if (pkg != null) {
926 r.exceptionPackages.add(pkg.trim());
927 }
928 }
929 }
John Spurlock7b414672014-07-18 13:02:39 -0400930 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -0400931 }
932 }
933 }
934
935 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700936 public int checkPackage(int uid, String packageName) {
937 synchronized (this) {
Dianne Hackborn0fcef842014-09-12 15:38:33 -0700938 if (getOpsRawLocked(uid, packageName, true) != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700939 return AppOpsManager.MODE_ALLOWED;
940 } else {
941 return AppOpsManager.MODE_ERRORED;
942 }
943 }
944 }
945
946 @Override
Svet Ganov99b60432015-06-27 13:15:22 -0700947 public int noteProxyOperation(int code, String proxyPackageName,
948 int proxiedUid, String proxiedPackageName) {
949 verifyIncomingOp(code);
950 final int proxyMode = noteOperationUnchecked(code, Binder.getCallingUid(),
951 proxyPackageName, -1, null);
952 if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
953 return proxyMode;
954 }
955 return noteOperationUnchecked(code, proxiedUid, proxiedPackageName,
956 Binder.getCallingUid(), proxyPackageName);
Svet Ganov99b60432015-06-27 13:15:22 -0700957 }
958
959 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800960 public int noteOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800961 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800962 verifyIncomingOp(code);
Svet Ganov99b60432015-06-27 13:15:22 -0700963 return noteOperationUnchecked(code, uid, packageName, 0, null);
964 }
965
966 private int noteOperationUnchecked(int code, int uid, String packageName,
967 int proxyUid, String proxyPackageName) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800968 synchronized (this) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800969 Ops ops = getOpsLocked(uid, packageName, true);
970 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800971 if (DEBUG) Log.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
972 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700973 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800974 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800975 Op op = getOpLocked(ops, code, true);
Jason Monk1c7c3192014-06-26 12:52:18 -0400976 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -0400977 return AppOpsManager.MODE_IGNORED;
978 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800979 if (op.duration == -1) {
980 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
981 + " code " + code + " time=" + op.time + " duration=" + op.duration);
982 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800983 op.duration = 0;
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800984 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -0700985 UidState uidState = ops.uidState;
986 if (uidState.opModes != null) {
987 final int uidMode = uidState.opModes.get(switchCode);
988 if (uidMode != AppOpsManager.MODE_ALLOWED) {
989 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
990 + switchCode + " (" + code + ") uid " + uid + " package "
991 + packageName);
992 op.rejectTime = System.currentTimeMillis();
993 return uidMode;
994 }
995 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800996 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
997 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
998 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
999 + switchCode + " (" + code + ") uid " + uid + " package " + packageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001000 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001001 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001002 }
1003 if (DEBUG) Log.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
1004 + " package " + packageName);
1005 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001006 op.rejectTime = 0;
Svet Ganov99b60432015-06-27 13:15:22 -07001007 op.proxyUid = proxyUid;
1008 op.proxyPackageName = proxyPackageName;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001009 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001010 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001011 }
1012
1013 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001014 public int startOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001015 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001016 verifyIncomingOp(code);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001017 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001018 synchronized (this) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001019 Ops ops = getOpsLocked(uid, packageName, true);
1020 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001021 if (DEBUG) Log.d(TAG, "startOperation: no op for code " + code + " uid " + uid
1022 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001023 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001024 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001025 Op op = getOpLocked(ops, code, true);
Jason Monk1c7c3192014-06-26 12:52:18 -04001026 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001027 return AppOpsManager.MODE_IGNORED;
1028 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001029 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001030 UidState uidState = ops.uidState;
1031 if (uidState.opModes != null) {
1032 final int uidMode = uidState.opModes.get(switchCode);
1033 if (uidMode != AppOpsManager.MODE_ALLOWED) {
1034 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1035 + switchCode + " (" + code + ") uid " + uid + " package "
1036 + packageName);
1037 op.rejectTime = System.currentTimeMillis();
1038 return uidMode;
1039 }
1040 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001041 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
1042 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
1043 if (DEBUG) Log.d(TAG, "startOperation: reject #" + op.mode + " for code "
1044 + switchCode + " (" + code + ") uid " + uid + " package " + packageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001045 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001046 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001047 }
1048 if (DEBUG) Log.d(TAG, "startOperation: allowing code " + code + " uid " + uid
1049 + " package " + packageName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001050 if (op.nesting == 0) {
1051 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001052 op.rejectTime = 0;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001053 op.duration = -1;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001054 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001055 op.nesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001056 if (client.mStartedOps != null) {
1057 client.mStartedOps.add(op);
1058 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001059 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001060 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001061 }
1062
1063 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001064 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001065 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001066 verifyIncomingOp(code);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001067 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001068 synchronized (this) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001069 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001070 if (op == null) {
1071 return;
1072 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001073 if (client.mStartedOps != null) {
1074 if (!client.mStartedOps.remove(op)) {
1075 throw new IllegalStateException("Operation not started: uid" + op.uid
1076 + " pkg=" + op.packageName + " op=" + op.op);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001077 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001078 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001079 finishOperationLocked(op);
1080 }
1081 }
1082
Svet Ganovb9d71a62015-04-30 10:38:13 -07001083 @Override
1084 public int permissionToOpCode(String permission) {
1085 return AppOpsManager.permissionToOpCode(permission);
1086 }
1087
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001088 void finishOperationLocked(Op op) {
1089 if (op.nesting <= 1) {
1090 if (op.nesting == 1) {
1091 op.duration = (int)(System.currentTimeMillis() - op.time);
1092 op.time += op.duration;
1093 } else {
1094 Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
1095 + op.packageName + " code " + op.op + " time=" + op.time
1096 + " duration=" + op.duration + " nesting=" + op.nesting);
1097 }
1098 op.nesting = 0;
1099 } else {
1100 op.nesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001101 }
1102 }
1103
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001104 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001105 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001106 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001107 }
1108 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001109 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001110 }
1111 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
1112 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001113 }
1114
Dianne Hackborn961321f2013-02-05 17:22:41 -08001115 private void verifyIncomingOp(int op) {
1116 if (op >= 0 && op < AppOpsManager._NUM_OP) {
1117 return;
1118 }
1119 throw new IllegalArgumentException("Bad operation #" + op);
1120 }
1121
Svet Ganov2af57082015-07-30 08:44:20 -07001122 private UidState getUidStateLocked(int uid, boolean edit) {
1123 UidState uidState = mUidStates.get(uid);
1124 if (uidState == null) {
1125 if (!edit) {
1126 return null;
1127 }
1128 uidState = new UidState(uid);
1129 mUidStates.put(uid, uidState);
1130 }
1131 return uidState;
1132 }
1133
Dianne Hackborn72e39832013-01-18 18:36:09 -08001134 private Ops getOpsLocked(int uid, String packageName, boolean edit) {
Dianne Hackborn0fcef842014-09-12 15:38:33 -07001135 if (uid == 0) {
1136 packageName = "root";
1137 } else if (uid == Process.SHELL_UID) {
1138 packageName = "com.android.shell";
1139 }
1140 return getOpsRawLocked(uid, packageName, edit);
1141 }
1142
1143 private Ops getOpsRawLocked(int uid, String packageName, boolean edit) {
Svet Ganov2af57082015-07-30 08:44:20 -07001144 UidState uidState = getUidStateLocked(uid, edit);
1145 if (uidState == null) {
1146 return null;
1147 }
1148
1149 if (uidState.pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001150 if (!edit) {
1151 return null;
1152 }
Svet Ganov2af57082015-07-30 08:44:20 -07001153 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001154 }
Svet Ganov2af57082015-07-30 08:44:20 -07001155
1156 Ops ops = uidState.pkgOps.get(packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001157 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001158 if (!edit) {
1159 return null;
1160 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001161 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001162 // This is the first time we have seen this package name under this uid,
1163 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -08001164 if (uid != 0) {
1165 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001166 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001167 int pkgUid = -1;
1168 try {
Jason Monk1c7c3192014-06-26 12:52:18 -04001169 ApplicationInfo appInfo = ActivityThread.getPackageManager()
Jeff Sharkeycd654482016-01-08 17:42:11 -07001170 .getApplicationInfo(packageName,
1171 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1172 UserHandle.getUserId(uid));
Jason Monk1c7c3192014-06-26 12:52:18 -04001173 if (appInfo != null) {
1174 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001175 isPrivileged = (appInfo.privateFlags
1176 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001177 } else {
1178 if ("media".equals(packageName)) {
1179 pkgUid = Process.MEDIA_UID;
1180 isPrivileged = false;
Andy Hunged0ea402015-10-30 14:11:46 -07001181 } else if ("audioserver".equals(packageName)) {
1182 pkgUid = Process.AUDIOSERVER_UID;
1183 isPrivileged = false;
Jason Monk1c7c3192014-06-26 12:52:18 -04001184 }
Dianne Hackborn713df152013-05-17 11:27:57 -07001185 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001186 } catch (RemoteException e) {
1187 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001188 }
1189 if (pkgUid != uid) {
1190 // Oops! The package name is not valid for the uid they are calling
1191 // under. Abort.
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001192 RuntimeException ex = new RuntimeException("here");
1193 ex.fillInStackTrace();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001194 Slog.w(TAG, "Bad call: specified package " + packageName
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001195 + " under uid " + uid + " but it is really " + pkgUid, ex);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001196 return null;
1197 }
1198 } finally {
1199 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001200 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001201 }
Svet Ganov2af57082015-07-30 08:44:20 -07001202 ops = new Ops(packageName, uidState, isPrivileged);
1203 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001204 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08001205 return ops;
1206 }
1207
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001208 private void scheduleWriteLocked() {
1209 if (!mWriteScheduled) {
1210 mWriteScheduled = true;
1211 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
1212 }
1213 }
1214
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001215 private void scheduleFastWriteLocked() {
1216 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001217 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001218 mFastWriteScheduled = true;
1219 mHandler.removeCallbacks(mWriteRunner);
1220 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001221 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001222 }
1223
Dianne Hackborn72e39832013-01-18 18:36:09 -08001224 private Op getOpLocked(int code, int uid, String packageName, boolean edit) {
1225 Ops ops = getOpsLocked(uid, packageName, edit);
1226 if (ops == null) {
1227 return null;
1228 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001229 return getOpLocked(ops, code, edit);
1230 }
1231
1232 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001233 Op op = ops.get(code);
1234 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001235 if (!edit) {
1236 return null;
1237 }
Svet Ganov2af57082015-07-30 08:44:20 -07001238 op = new Op(ops.uidState.uid, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001239 ops.put(code, op);
1240 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001241 if (edit) {
1242 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001243 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001244 return op;
1245 }
1246
Jason Monk1c7c3192014-06-26 12:52:18 -04001247 private boolean isOpRestricted(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04001248 int userHandle = UserHandle.getUserId(uid);
1249 boolean[] opRestrictions = mOpRestrictions.get(userHandle);
1250 if ((opRestrictions != null) && opRestrictions[code]) {
Jason Monk1c7c3192014-06-26 12:52:18 -04001251 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
1252 synchronized (this) {
1253 Ops ops = getOpsLocked(uid, packageName, true);
1254 if ((ops != null) && ops.isPrivileged) {
1255 return false;
1256 }
1257 }
1258 }
Julia Reynolds401de172014-07-24 18:21:29 -04001259 return true;
Jason Monk62062992014-05-06 09:55:28 -04001260 }
1261 return false;
1262 }
1263
Dianne Hackborn35654b62013-01-14 17:38:02 -08001264 void readState() {
1265 synchronized (mFile) {
1266 synchronized (this) {
1267 FileInputStream stream;
1268 try {
1269 stream = mFile.openRead();
1270 } catch (FileNotFoundException e) {
1271 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
1272 return;
1273 }
1274 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001275 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001276 try {
1277 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001278 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001279 int type;
1280 while ((type = parser.next()) != XmlPullParser.START_TAG
1281 && type != XmlPullParser.END_DOCUMENT) {
1282 ;
1283 }
1284
1285 if (type != XmlPullParser.START_TAG) {
1286 throw new IllegalStateException("no start tag found");
1287 }
1288
1289 int outerDepth = parser.getDepth();
1290 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1291 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1292 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1293 continue;
1294 }
1295
1296 String tagName = parser.getName();
1297 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001298 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07001299 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07001300 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001301 } else {
1302 Slog.w(TAG, "Unknown element under <app-ops>: "
1303 + parser.getName());
1304 XmlUtils.skipCurrentTag(parser);
1305 }
1306 }
1307 success = true;
1308 } catch (IllegalStateException e) {
1309 Slog.w(TAG, "Failed parsing " + e);
1310 } catch (NullPointerException e) {
1311 Slog.w(TAG, "Failed parsing " + e);
1312 } catch (NumberFormatException e) {
1313 Slog.w(TAG, "Failed parsing " + e);
1314 } catch (XmlPullParserException e) {
1315 Slog.w(TAG, "Failed parsing " + e);
1316 } catch (IOException e) {
1317 Slog.w(TAG, "Failed parsing " + e);
1318 } catch (IndexOutOfBoundsException e) {
1319 Slog.w(TAG, "Failed parsing " + e);
1320 } finally {
1321 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07001322 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001323 }
1324 try {
1325 stream.close();
1326 } catch (IOException e) {
1327 }
1328 }
1329 }
1330 }
1331 }
1332
Svet Ganov2af57082015-07-30 08:44:20 -07001333 void readUidOps(XmlPullParser parser) throws NumberFormatException,
1334 XmlPullParserException, IOException {
1335 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
1336 int outerDepth = parser.getDepth();
1337 int type;
1338 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1339 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1340 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1341 continue;
1342 }
1343
1344 String tagName = parser.getName();
1345 if (tagName.equals("op")) {
1346 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
1347 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
1348 UidState uidState = getUidStateLocked(uid, true);
1349 if (uidState.opModes == null) {
1350 uidState.opModes = new SparseIntArray();
1351 }
1352 uidState.opModes.put(code, mode);
1353 } else {
1354 Slog.w(TAG, "Unknown element under <uid-ops>: "
1355 + parser.getName());
1356 XmlUtils.skipCurrentTag(parser);
1357 }
1358 }
1359 }
1360
Dave Burke0997c5bd2013-08-02 20:25:02 +00001361 void readPackage(XmlPullParser parser) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001362 XmlPullParserException, IOException {
1363 String pkgName = parser.getAttributeValue(null, "n");
1364 int outerDepth = parser.getDepth();
1365 int type;
1366 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1367 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1368 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1369 continue;
1370 }
1371
1372 String tagName = parser.getName();
1373 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001374 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001375 } else {
1376 Slog.w(TAG, "Unknown element under <pkg>: "
1377 + parser.getName());
1378 XmlUtils.skipCurrentTag(parser);
1379 }
1380 }
1381 }
1382
Dave Burke0997c5bd2013-08-02 20:25:02 +00001383 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001384 XmlPullParserException, IOException {
1385 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Jason Monk1c7c3192014-06-26 12:52:18 -04001386 String isPrivilegedString = parser.getAttributeValue(null, "p");
1387 boolean isPrivileged = false;
1388 if (isPrivilegedString == null) {
1389 try {
1390 IPackageManager packageManager = ActivityThread.getPackageManager();
1391 if (packageManager != null) {
1392 ApplicationInfo appInfo = ActivityThread.getPackageManager()
1393 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
1394 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001395 isPrivileged = (appInfo.privateFlags
1396 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001397 }
1398 } else {
1399 // Could not load data, don't add to cache so it will be loaded later.
1400 return;
1401 }
1402 } catch (RemoteException e) {
1403 Slog.w(TAG, "Could not contact PackageManager", e);
1404 }
1405 } else {
1406 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
1407 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001408 int outerDepth = parser.getDepth();
1409 int type;
1410 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1411 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1412 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1413 continue;
1414 }
1415
1416 String tagName = parser.getName();
1417 if (tagName.equals("op")) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001418 Op op = new Op(uid, pkgName, Integer.parseInt(parser.getAttributeValue(null, "n")));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001419 String mode = parser.getAttributeValue(null, "m");
1420 if (mode != null) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001421 op.mode = Integer.parseInt(mode);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001422 }
1423 String time = parser.getAttributeValue(null, "t");
1424 if (time != null) {
1425 op.time = Long.parseLong(time);
1426 }
1427 time = parser.getAttributeValue(null, "r");
1428 if (time != null) {
1429 op.rejectTime = Long.parseLong(time);
1430 }
1431 String dur = parser.getAttributeValue(null, "d");
1432 if (dur != null) {
1433 op.duration = Integer.parseInt(dur);
1434 }
Svet Ganov99b60432015-06-27 13:15:22 -07001435 String proxyUid = parser.getAttributeValue(null, "pu");
1436 if (proxyUid != null) {
1437 op.proxyUid = Integer.parseInt(proxyUid);
1438 }
1439 String proxyPackageName = parser.getAttributeValue(null, "pp");
1440 if (proxyPackageName != null) {
1441 op.proxyPackageName = proxyPackageName;
1442 }
Svet Ganov2af57082015-07-30 08:44:20 -07001443
1444 UidState uidState = getUidStateLocked(uid, true);
1445 if (uidState.pkgOps == null) {
1446 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001447 }
Svet Ganov2af57082015-07-30 08:44:20 -07001448
1449 Ops ops = uidState.pkgOps.get(pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001450 if (ops == null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001451 ops = new Ops(pkgName, uidState, isPrivileged);
1452 uidState.pkgOps.put(pkgName, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001453 }
1454 ops.put(op.op, op);
1455 } else {
1456 Slog.w(TAG, "Unknown element under <pkg>: "
1457 + parser.getName());
1458 XmlUtils.skipCurrentTag(parser);
1459 }
1460 }
1461 }
1462
1463 void writeState() {
1464 synchronized (mFile) {
1465 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
1466
1467 FileOutputStream stream;
1468 try {
1469 stream = mFile.startWrite();
1470 } catch (IOException e) {
1471 Slog.w(TAG, "Failed to write state: " + e);
1472 return;
1473 }
1474
1475 try {
1476 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001477 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001478 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001479 out.startTag(null, "app-ops");
Svet Ganov2af57082015-07-30 08:44:20 -07001480
1481 final int uidStateCount = mUidStates.size();
1482 for (int i = 0; i < uidStateCount; i++) {
1483 UidState uidState = mUidStates.valueAt(i);
1484 if (uidState.opModes != null && uidState.opModes.size() > 0) {
1485 out.startTag(null, "uid");
1486 out.attribute(null, "n", Integer.toString(uidState.uid));
1487 SparseIntArray uidOpModes = uidState.opModes;
1488 final int opCount = uidOpModes.size();
1489 for (int j = 0; j < opCount; j++) {
1490 final int op = uidOpModes.keyAt(j);
1491 final int mode = uidOpModes.valueAt(j);
1492 out.startTag(null, "op");
1493 out.attribute(null, "n", Integer.toString(op));
1494 out.attribute(null, "m", Integer.toString(mode));
1495 out.endTag(null, "op");
1496 }
1497 out.endTag(null, "uid");
1498 }
1499 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001500
1501 if (allOps != null) {
1502 String lastPkg = null;
1503 for (int i=0; i<allOps.size(); i++) {
1504 AppOpsManager.PackageOps pkg = allOps.get(i);
1505 if (!pkg.getPackageName().equals(lastPkg)) {
1506 if (lastPkg != null) {
1507 out.endTag(null, "pkg");
1508 }
1509 lastPkg = pkg.getPackageName();
1510 out.startTag(null, "pkg");
1511 out.attribute(null, "n", lastPkg);
1512 }
1513 out.startTag(null, "uid");
1514 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04001515 synchronized (this) {
1516 Ops ops = getOpsLocked(pkg.getUid(), pkg.getPackageName(), false);
1517 // Should always be present as the list of PackageOps is generated
1518 // from Ops.
1519 if (ops != null) {
1520 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
1521 } else {
1522 out.attribute(null, "p", Boolean.toString(false));
1523 }
1524 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001525 List<AppOpsManager.OpEntry> ops = pkg.getOps();
1526 for (int j=0; j<ops.size(); j++) {
1527 AppOpsManager.OpEntry op = ops.get(j);
1528 out.startTag(null, "op");
1529 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07001530 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001531 out.attribute(null, "m", Integer.toString(op.getMode()));
1532 }
1533 long time = op.getTime();
1534 if (time != 0) {
1535 out.attribute(null, "t", Long.toString(time));
1536 }
1537 time = op.getRejectTime();
1538 if (time != 0) {
1539 out.attribute(null, "r", Long.toString(time));
1540 }
1541 int dur = op.getDuration();
1542 if (dur != 0) {
1543 out.attribute(null, "d", Integer.toString(dur));
1544 }
Svet Ganov99b60432015-06-27 13:15:22 -07001545 int proxyUid = op.getProxyUid();
1546 if (proxyUid != -1) {
1547 out.attribute(null, "pu", Integer.toString(proxyUid));
1548 }
1549 String proxyPackageName = op.getProxyPackageName();
1550 if (proxyPackageName != null) {
1551 out.attribute(null, "pp", proxyPackageName);
1552 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001553 out.endTag(null, "op");
1554 }
1555 out.endTag(null, "uid");
1556 }
1557 if (lastPkg != null) {
1558 out.endTag(null, "pkg");
1559 }
1560 }
1561
1562 out.endTag(null, "app-ops");
1563 out.endDocument();
1564 mFile.finishWrite(stream);
1565 } catch (IOException e) {
1566 Slog.w(TAG, "Failed to write state, restoring backup.", e);
1567 mFile.failWrite(stream);
1568 }
1569 }
1570 }
1571
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001572 static class Shell extends ShellCommand {
1573 final IAppOpsService mInterface;
1574 final AppOpsService mInternal;
1575
1576 int userId = UserHandle.USER_SYSTEM;
1577 String packageName;
1578 String opStr;
1579 int op;
1580 int packageUid;
1581
1582 Shell(IAppOpsService iface, AppOpsService internal) {
1583 mInterface = iface;
1584 mInternal = internal;
1585 }
1586
1587 @Override
1588 public int onCommand(String cmd) {
1589 return onShellCommand(this, cmd);
1590 }
1591
1592 @Override
1593 public void onHelp() {
1594 PrintWriter pw = getOutPrintWriter();
1595 dumpCommandHelp(pw);
1596 }
1597
1598 private int strOpToOp(String op, PrintWriter err) {
1599 try {
1600 return AppOpsManager.strOpToOp(op);
1601 } catch (IllegalArgumentException e) {
1602 }
1603 try {
1604 return Integer.parseInt(op);
1605 } catch (NumberFormatException e) {
1606 }
1607 try {
1608 return AppOpsManager.strDebugOpToOp(op);
1609 } catch (IllegalArgumentException e) {
1610 err.println("Error: " + e.getMessage());
1611 return -1;
1612 }
1613 }
1614
1615 int parseUserPackageOp(boolean reqOp, PrintWriter err) throws RemoteException {
1616 userId = UserHandle.USER_CURRENT;
1617 packageName = null;
1618 opStr = null;
1619 for (String argument; (argument = getNextArg()) != null;) {
1620 if ("--user".equals(argument)) {
1621 userId = UserHandle.parseUserArg(getNextArgRequired());
1622 } else {
1623 if (packageName == null) {
1624 packageName = argument;
1625 } else if (opStr == null) {
1626 opStr = argument;
1627 break;
1628 }
1629 }
1630 }
1631 if (packageName == null) {
1632 err.println("Error: Package name not specified.");
1633 return -1;
1634 } else if (opStr == null && reqOp) {
1635 err.println("Error: Operation not specified.");
1636 return -1;
1637 }
1638 if (opStr != null) {
1639 op = strOpToOp(opStr, err);
1640 if (op < 0) {
1641 return -1;
1642 }
1643 } else {
1644 op = AppOpsManager.OP_NONE;
1645 }
1646 if (userId == UserHandle.USER_CURRENT) {
1647 userId = ActivityManager.getCurrentUser();
1648 }
1649 if ("root".equals(packageName)) {
1650 packageUid = 0;
1651 } else {
Jeff Sharkeycd654482016-01-08 17:42:11 -07001652 packageUid = AppGlobals.getPackageManager().getPackageUid(packageName,
1653 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001654 }
1655 if (packageUid < 0) {
1656 err.println("Error: No UID for " + packageName + " in user " + userId);
1657 return -1;
1658 }
1659 return 0;
1660 }
1661 }
1662
1663 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
1664 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
1665 (new Shell(this, this)).exec(this, in, out, err, args, resultReceiver);
1666 }
1667
1668 static void dumpCommandHelp(PrintWriter pw) {
1669 pw.println("AppOps service (appops) commands:");
1670 pw.println(" help");
1671 pw.println(" Print this help text.");
1672 pw.println(" set [--user <USER_ID>] <PACKAGE> <OP> <MODE>");
1673 pw.println(" Set the mode for a particular application and operation.");
1674 pw.println(" get [--user <USER_ID>] <PACKAGE> [<OP>]");
1675 pw.println(" Return the mode for a particular application and optional operation.");
1676 pw.println(" reset [--user <USER_ID>] [<PACKAGE>]");
1677 pw.println(" Reset the given application or all applications to default modes.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001678 pw.println(" write-settings");
1679 pw.println(" Immediately write pending changes to storage.");
1680 pw.println(" read-settings");
1681 pw.println(" Read the last written settings, replacing current state in RAM.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001682 pw.println(" options:");
1683 pw.println(" <PACKAGE> an Android package name.");
1684 pw.println(" <OP> an AppOps operation.");
1685 pw.println(" <MODE> one of allow, ignore, deny, or default");
1686 pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
1687 pw.println(" specified, the current user is assumed.");
1688 }
1689
1690 static int onShellCommand(Shell shell, String cmd) {
1691 if (cmd == null) {
1692 return shell.handleDefaultCommands(cmd);
1693 }
1694 PrintWriter pw = shell.getOutPrintWriter();
1695 PrintWriter err = shell.getErrPrintWriter();
1696 try {
1697 switch (cmd) {
1698 case "set": {
1699 int res = shell.parseUserPackageOp(true, err);
1700 if (res < 0) {
1701 return res;
1702 }
1703 String modeStr = shell.getNextArg();
1704 if (modeStr == null) {
1705 err.println("Error: Mode not specified.");
1706 return -1;
1707 }
1708
1709 final int mode;
1710 switch (modeStr) {
1711 case "allow":
1712 mode = AppOpsManager.MODE_ALLOWED;
1713 break;
1714 case "deny":
1715 mode = AppOpsManager.MODE_ERRORED;
1716 break;
1717 case "ignore":
1718 mode = AppOpsManager.MODE_IGNORED;
1719 break;
1720 case "default":
1721 mode = AppOpsManager.MODE_DEFAULT;
1722 break;
1723 default:
1724 err.println("Error: Mode " + modeStr + " is not valid,");
1725 return -1;
1726 }
1727
1728 shell.mInterface.setMode(shell.op, shell.packageUid, shell.packageName, mode);
1729 return 0;
1730 }
1731 case "get": {
1732 int res = shell.parseUserPackageOp(false, err);
1733 if (res < 0) {
1734 return res;
1735 }
1736
1737 List<AppOpsManager.PackageOps> ops = shell.mInterface.getOpsForPackage(
1738 shell.packageUid, shell.packageName,
1739 shell.op != AppOpsManager.OP_NONE ? new int[] {shell.op} : null);
1740 if (ops == null || ops.size() <= 0) {
1741 pw.println("No operations.");
1742 return 0;
1743 }
1744 final long now = System.currentTimeMillis();
1745 for (int i=0; i<ops.size(); i++) {
1746 List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
1747 for (int j=0; j<entries.size(); j++) {
1748 AppOpsManager.OpEntry ent = entries.get(j);
1749 pw.print(AppOpsManager.opToName(ent.getOp()));
1750 pw.print(": ");
1751 switch (ent.getMode()) {
1752 case AppOpsManager.MODE_ALLOWED:
1753 pw.print("allow");
1754 break;
1755 case AppOpsManager.MODE_IGNORED:
1756 pw.print("ignore");
1757 break;
1758 case AppOpsManager.MODE_ERRORED:
1759 pw.print("deny");
1760 break;
1761 case AppOpsManager.MODE_DEFAULT:
1762 pw.print("default");
1763 break;
1764 default:
1765 pw.print("mode=");
1766 pw.print(ent.getMode());
1767 break;
1768 }
1769 if (ent.getTime() != 0) {
1770 pw.print("; time=");
1771 TimeUtils.formatDuration(now - ent.getTime(), pw);
1772 pw.print(" ago");
1773 }
1774 if (ent.getRejectTime() != 0) {
1775 pw.print("; rejectTime=");
1776 TimeUtils.formatDuration(now - ent.getRejectTime(), pw);
1777 pw.print(" ago");
1778 }
1779 if (ent.getDuration() == -1) {
1780 pw.print(" (running)");
1781 } else if (ent.getDuration() != 0) {
1782 pw.print("; duration=");
1783 TimeUtils.formatDuration(ent.getDuration(), pw);
1784 }
1785 pw.println();
1786 }
1787 }
1788 return 0;
1789 }
1790 case "reset": {
1791 String packageName = null;
1792 int userId = UserHandle.USER_CURRENT;
1793 for (String argument; (argument = shell.getNextArg()) != null;) {
1794 if ("--user".equals(argument)) {
1795 String userStr = shell.getNextArgRequired();
1796 userId = UserHandle.parseUserArg(userStr);
1797 } else {
1798 if (packageName == null) {
1799 packageName = argument;
1800 } else {
1801 err.println("Error: Unsupported argument: " + argument);
1802 return -1;
1803 }
1804 }
1805 }
1806
1807 if (userId == UserHandle.USER_CURRENT) {
1808 userId = ActivityManager.getCurrentUser();
1809 }
1810
1811 shell.mInterface.resetAllModes(userId, packageName);
1812 pw.print("Reset all modes for: ");
1813 if (userId == UserHandle.USER_ALL) {
1814 pw.print("all users");
1815 } else {
1816 pw.print("user "); pw.print(userId);
1817 }
1818 pw.print(", ");
1819 if (packageName == null) {
1820 pw.println("all packages");
1821 } else {
1822 pw.print("package "); pw.println(packageName);
1823 }
1824 return 0;
1825 }
1826 case "write-settings": {
1827 shell.mInternal.mContext.enforcePermission(
1828 android.Manifest.permission.UPDATE_APP_OPS_STATS,
1829 Binder.getCallingPid(), Binder.getCallingUid(), null);
1830 long token = Binder.clearCallingIdentity();
1831 try {
1832 synchronized (shell.mInternal) {
1833 shell.mInternal.mHandler.removeCallbacks(shell.mInternal.mWriteRunner);
1834 }
1835 shell.mInternal.writeState();
1836 pw.println("Current settings written.");
1837 } finally {
1838 Binder.restoreCallingIdentity(token);
1839 }
1840 return 0;
1841 }
1842 case "read-settings": {
1843 shell.mInternal.mContext.enforcePermission(
1844 android.Manifest.permission.UPDATE_APP_OPS_STATS,
1845 Binder.getCallingPid(), Binder.getCallingUid(), null);
1846 long token = Binder.clearCallingIdentity();
1847 try {
1848 shell.mInternal.readState();
1849 pw.println("Last settings read.");
1850 } finally {
1851 Binder.restoreCallingIdentity(token);
1852 }
1853 return 0;
1854 }
1855 default:
1856 return shell.handleDefaultCommands(cmd);
1857 }
1858 } catch (RemoteException e) {
1859 pw.println("Remote exception: " + e);
1860 }
1861 return -1;
1862 }
1863
1864 private void dumpHelp(PrintWriter pw) {
1865 pw.println("AppOps service (appops) dump options:");
1866 pw.println(" none");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001867 }
1868
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001869 @Override
1870 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1871 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1872 != PackageManager.PERMISSION_GRANTED) {
1873 pw.println("Permission Denial: can't dump ApOps service from from pid="
1874 + Binder.getCallingPid()
1875 + ", uid=" + Binder.getCallingUid());
1876 return;
1877 }
1878
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001879 if (args != null) {
1880 for (int i=0; i<args.length; i++) {
1881 String arg = args[i];
1882 if ("-h".equals(arg)) {
1883 dumpHelp(pw);
1884 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07001885 } else if ("-a".equals(arg)) {
1886 // dump all data
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001887 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
1888 pw.println("Unknown option: " + arg);
1889 return;
1890 } else {
1891 pw.println("Unknown command: " + arg);
1892 return;
1893 }
1894 }
1895 }
1896
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001897 synchronized (this) {
1898 pw.println("Current AppOps Service state:");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001899 final long now = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001900 boolean needSep = false;
1901 if (mOpModeWatchers.size() > 0) {
1902 needSep = true;
1903 pw.println(" Op mode watchers:");
1904 for (int i=0; i<mOpModeWatchers.size(); i++) {
1905 pw.print(" Op "); pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
1906 pw.println(":");
1907 ArrayList<Callback> callbacks = mOpModeWatchers.valueAt(i);
1908 for (int j=0; j<callbacks.size(); j++) {
1909 pw.print(" #"); pw.print(j); pw.print(": ");
1910 pw.println(callbacks.get(j));
1911 }
1912 }
1913 }
1914 if (mPackageModeWatchers.size() > 0) {
1915 needSep = true;
1916 pw.println(" Package mode watchers:");
1917 for (int i=0; i<mPackageModeWatchers.size(); i++) {
1918 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
1919 pw.println(":");
1920 ArrayList<Callback> callbacks = mPackageModeWatchers.valueAt(i);
1921 for (int j=0; j<callbacks.size(); j++) {
1922 pw.print(" #"); pw.print(j); pw.print(": ");
1923 pw.println(callbacks.get(j));
1924 }
1925 }
1926 }
1927 if (mModeWatchers.size() > 0) {
1928 needSep = true;
1929 pw.println(" All mode watchers:");
1930 for (int i=0; i<mModeWatchers.size(); i++) {
1931 pw.print(" "); pw.print(mModeWatchers.keyAt(i));
1932 pw.print(" -> "); pw.println(mModeWatchers.valueAt(i));
1933 }
1934 }
1935 if (mClients.size() > 0) {
1936 needSep = true;
1937 pw.println(" Clients:");
1938 for (int i=0; i<mClients.size(); i++) {
1939 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
1940 ClientState cs = mClients.valueAt(i);
1941 pw.print(" "); pw.println(cs);
1942 if (cs.mStartedOps != null && cs.mStartedOps.size() > 0) {
1943 pw.println(" Started ops:");
1944 for (int j=0; j<cs.mStartedOps.size(); j++) {
1945 Op op = cs.mStartedOps.get(j);
1946 pw.print(" "); pw.print("uid="); pw.print(op.uid);
1947 pw.print(" pkg="); pw.print(op.packageName);
1948 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
1949 }
1950 }
1951 }
1952 }
John Spurlock1af30c72014-03-10 08:33:35 -04001953 if (mAudioRestrictions.size() > 0) {
1954 boolean printedHeader = false;
1955 for (int o=0; o<mAudioRestrictions.size(); o++) {
1956 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
1957 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
1958 for (int i=0; i<restrictions.size(); i++) {
1959 if (!printedHeader){
1960 pw.println(" Audio Restrictions:");
1961 printedHeader = true;
1962 needSep = true;
1963 }
John Spurlock7b414672014-07-18 13:02:39 -04001964 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04001965 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04001966 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04001967 Restriction r = restrictions.valueAt(i);
1968 pw.print(": mode="); pw.println(r.mode);
1969 if (!r.exceptionPackages.isEmpty()) {
1970 pw.println(" Exceptions:");
1971 for (int j=0; j<r.exceptionPackages.size(); j++) {
1972 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
1973 }
1974 }
1975 }
1976 }
1977 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001978 if (needSep) {
1979 pw.println();
1980 }
Svet Ganov2af57082015-07-30 08:44:20 -07001981 for (int i=0; i<mUidStates.size(); i++) {
1982 UidState uidState = mUidStates.valueAt(i);
1983
1984 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
1985
1986 SparseIntArray opModes = uidState.opModes;
1987 if (opModes != null) {
1988 final int opModeCount = opModes.size();
1989 for (int j = 0; j < opModeCount; j++) {
1990 final int code = opModes.keyAt(j);
1991 final int mode = opModes.valueAt(j);
1992 pw.print(" "); pw.print(AppOpsManager.opToName(code));
1993 pw.print(": mode="); pw.println(mode);
1994 }
1995 }
1996
1997 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
1998 if (pkgOps == null) {
1999 continue;
2000 }
2001
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002002 for (Ops ops : pkgOps.values()) {
2003 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
2004 for (int j=0; j<ops.size(); j++) {
2005 Op op = ops.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002006 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
2007 pw.print(": mode="); pw.print(op.mode);
2008 if (op.time != 0) {
2009 pw.print("; time="); TimeUtils.formatDuration(now-op.time, pw);
2010 pw.print(" ago");
2011 }
2012 if (op.rejectTime != 0) {
2013 pw.print("; rejectTime="); TimeUtils.formatDuration(now-op.rejectTime, pw);
2014 pw.print(" ago");
2015 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002016 if (op.duration == -1) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002017 pw.print(" (running)");
2018 } else if (op.duration != 0) {
2019 pw.print("; duration="); TimeUtils.formatDuration(op.duration, pw);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002020 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002021 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002022 }
2023 }
2024 }
2025 }
2026 }
John Spurlock1af30c72014-03-10 08:33:35 -04002027
2028 private static final class Restriction {
2029 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
2030 int mode;
2031 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
2032 }
Jason Monk62062992014-05-06 09:55:28 -04002033
2034 @Override
Jason Monk62062992014-05-06 09:55:28 -04002035 public void setUserRestrictions(Bundle restrictions, int userHandle) throws RemoteException {
2036 checkSystemUid("setUserRestrictions");
2037 boolean[] opRestrictions = mOpRestrictions.get(userHandle);
2038 if (opRestrictions == null) {
2039 opRestrictions = new boolean[AppOpsManager._NUM_OP];
2040 mOpRestrictions.put(userHandle, opRestrictions);
2041 }
2042 for (int i = 0; i < opRestrictions.length; ++i) {
2043 String restriction = AppOpsManager.opToRestriction(i);
2044 if (restriction != null) {
2045 opRestrictions[i] = restrictions.getBoolean(restriction, false);
2046 } else {
2047 opRestrictions[i] = false;
2048 }
2049 }
2050 }
2051
2052 @Override
2053 public void removeUser(int userHandle) throws RemoteException {
2054 checkSystemUid("removeUser");
2055 mOpRestrictions.remove(userHandle);
Jason Monk62062992014-05-06 09:55:28 -04002056 }
2057
2058 private void checkSystemUid(String function) {
2059 int uid = Binder.getCallingUid();
2060 if (uid != Process.SYSTEM_UID) {
2061 throw new SecurityException(function + " must by called by the system");
2062 }
2063 }
2064
Svet Ganov2af57082015-07-30 08:44:20 -07002065 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07002066 String[] packageNames = null;
Svet Ganov2af57082015-07-30 08:44:20 -07002067 try {
riddle_hsu40b300f2015-11-23 13:22:03 +08002068 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -07002069 } catch (RemoteException e) {
2070 /* ignore - local call */
2071 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07002072 if (packageNames == null) {
2073 return EmptyArray.STRING;
2074 }
2075 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07002076 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002077}