blob: 07d472dc53756417e0a2d901b8d55e71a440b381 [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
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +000019import static android.content.pm.ApplicationInfo.FLAG_SUSPENDED;
20
Dianne Hackborna06de0f2012-12-11 16:34:47 -080021import java.io.File;
22import java.io.FileDescriptor;
Dianne Hackborn35654b62013-01-14 17:38:02 -080023import java.io.FileInputStream;
24import java.io.FileNotFoundException;
25import java.io.FileOutputStream;
26import java.io.IOException;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080027import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010028import java.nio.charset.StandardCharsets;
Dianne Hackborn35654b62013-01-14 17:38:02 -080029import java.util.ArrayList;
Svetoslav215b44a2015-08-04 19:03:40 -070030import java.util.Collections;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080031import java.util.HashMap;
Dianne Hackbornc2293022013-02-06 23:14:49 -080032import java.util.Iterator;
Dianne Hackborn35654b62013-01-14 17:38:02 -080033import java.util.List;
Dianne Hackborn607b4142013-08-02 18:10:10 -070034import java.util.Map;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080035
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -080036import android.app.ActivityManager;
Jason Monk1c7c3192014-06-26 12:52:18 -040037import android.app.ActivityThread;
Svet Ganov2af57082015-07-30 08:44:20 -070038import android.app.AppGlobals;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080039import android.app.AppOpsManager;
40import android.content.Context;
Jason Monk1c7c3192014-06-26 12:52:18 -040041import android.content.pm.ApplicationInfo;
42import android.content.pm.IPackageManager;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080043import android.content.pm.PackageManager;
John Spurlock7b414672014-07-18 13:02:39 -040044import android.media.AudioAttributes;
Dianne Hackborn35654b62013-01-14 17:38:02 -080045import android.os.AsyncTask;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080046import android.os.Binder;
Jason Monk62062992014-05-06 09:55:28 -040047import android.os.Bundle;
Dianne Hackborn35654b62013-01-14 17:38:02 -080048import android.os.Handler;
Dianne Hackbornc2293022013-02-06 23:14:49 -080049import android.os.IBinder;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080050import android.os.Process;
Dianne Hackbornc2293022013-02-06 23:14:49 -080051import android.os.RemoteException;
Dianne Hackborn268e4e32015-11-18 16:29:56 -080052import android.os.ResultReceiver;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080053import android.os.ServiceManager;
Dianne Hackborn268e4e32015-11-18 16:29:56 -080054import android.os.ShellCommand;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080055import android.os.UserHandle;
Svet Ganov6ee871e2015-07-10 14:29:33 -070056import android.os.storage.MountServiceInternal;
Dianne Hackborne98f5db2013-07-17 17:23:25 -070057import android.util.ArrayMap;
John Spurlock1af30c72014-03-10 08:33:35 -040058import android.util.ArraySet;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080059import android.util.AtomicFile;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -080060import android.util.Log;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080061import android.util.Slog;
62import android.util.SparseArray;
Svet Ganov2af57082015-07-30 08:44:20 -070063import android.util.SparseIntArray;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080064import android.util.TimeUtils;
Dianne Hackborn35654b62013-01-14 17:38:02 -080065import android.util.Xml;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080066
67import com.android.internal.app.IAppOpsService;
Dianne Hackbornc2293022013-02-06 23:14:49 -080068import com.android.internal.app.IAppOpsCallback;
Svet Ganov6ee871e2015-07-10 14:29:33 -070069import com.android.internal.os.Zygote;
Svet Ganov2af57082015-07-30 08:44:20 -070070import com.android.internal.util.ArrayUtils;
Dianne Hackborn35654b62013-01-14 17:38:02 -080071import com.android.internal.util.FastXmlSerializer;
72import 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 Ganov2af57082015-07-30 08:44:20 -0700108 final SparseArray<UidState> mUidStates = new SparseArray<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800109
Jason Monk62062992014-05-06 09:55:28 -0400110 private final SparseArray<boolean[]> mOpRestrictions = new SparseArray<boolean[]>();
111
Svet Ganov2af57082015-07-30 08:44:20 -0700112 private static final class UidState {
113 public final int uid;
114 public ArrayMap<String, Ops> pkgOps;
115 public SparseIntArray opModes;
116
117 public UidState(int uid) {
118 this.uid = uid;
119 }
120
121 public void clear() {
122 pkgOps = null;
123 opModes = null;
124 }
125
126 public boolean isDefault() {
127 return (pkgOps == null || pkgOps.isEmpty())
128 && (opModes == null || opModes.size() <= 0);
129 }
130 }
131
Dianne Hackbornc2293022013-02-06 23:14:49 -0800132 public final static class Ops extends SparseArray<Op> {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800133 public final String packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700134 public final UidState uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400135 public final boolean isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800136
Svet Ganov2af57082015-07-30 08:44:20 -0700137 public Ops(String _packageName, UidState _uidState, boolean _isPrivileged) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800138 packageName = _packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700139 uidState = _uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400140 isPrivileged = _isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800141 }
142 }
143
Dianne Hackbornc2293022013-02-06 23:14:49 -0800144 public final static class Op {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700145 public final int uid;
146 public final String packageName;
Svet Ganov99b60432015-06-27 13:15:22 -0700147 public int proxyUid = -1;
148 public String proxyPackageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800149 public final int op;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800150 public int mode;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800151 public int duration;
152 public long time;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800153 public long rejectTime;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800154 public int nesting;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800155
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700156 public Op(int _uid, String _packageName, int _op) {
157 uid = _uid;
158 packageName = _packageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800159 op = _op;
David Braunf5d83192013-09-16 13:43:51 -0700160 mode = AppOpsManager.opToDefaultMode(op);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800161 }
162 }
163
Dianne Hackbornc2293022013-02-06 23:14:49 -0800164 final SparseArray<ArrayList<Callback>> mOpModeWatchers
165 = new SparseArray<ArrayList<Callback>>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700166 final ArrayMap<String, ArrayList<Callback>> mPackageModeWatchers
167 = new ArrayMap<String, ArrayList<Callback>>();
168 final ArrayMap<IBinder, Callback> mModeWatchers
169 = new ArrayMap<IBinder, Callback>();
John Spurlock1af30c72014-03-10 08:33:35 -0400170 final SparseArray<SparseArray<Restriction>> mAudioRestrictions
171 = new SparseArray<SparseArray<Restriction>>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800172
173 public final class Callback implements DeathRecipient {
174 final IAppOpsCallback mCallback;
175
176 public Callback(IAppOpsCallback callback) {
177 mCallback = callback;
178 try {
179 mCallback.asBinder().linkToDeath(this, 0);
180 } catch (RemoteException e) {
181 }
182 }
183
184 public void unlinkToDeath() {
185 mCallback.asBinder().unlinkToDeath(this, 0);
186 }
187
188 @Override
189 public void binderDied() {
190 stopWatchingMode(mCallback);
191 }
192 }
193
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700194 final ArrayMap<IBinder, ClientState> mClients = new ArrayMap<IBinder, ClientState>();
195
196 public final class ClientState extends Binder implements DeathRecipient {
197 final IBinder mAppToken;
198 final int mPid;
199 final ArrayList<Op> mStartedOps;
200
201 public ClientState(IBinder appToken) {
202 mAppToken = appToken;
203 mPid = Binder.getCallingPid();
204 if (appToken instanceof Binder) {
205 // For local clients, there is no reason to track them.
206 mStartedOps = null;
207 } else {
208 mStartedOps = new ArrayList<Op>();
209 try {
210 mAppToken.linkToDeath(this, 0);
211 } catch (RemoteException e) {
212 }
213 }
214 }
215
216 @Override
217 public String toString() {
218 return "ClientState{" +
219 "mAppToken=" + mAppToken +
220 ", " + (mStartedOps != null ? ("pid=" + mPid) : "local") +
221 '}';
222 }
223
224 @Override
225 public void binderDied() {
226 synchronized (AppOpsService.this) {
227 for (int i=mStartedOps.size()-1; i>=0; i--) {
228 finishOperationLocked(mStartedOps.get(i));
229 }
230 mClients.remove(mAppToken);
231 }
232 }
233 }
234
Jeff Brown6f357d32014-01-15 20:40:55 -0800235 public AppOpsService(File storagePath, Handler handler) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800236 mFile = new AtomicFile(storagePath);
Jeff Brown6f357d32014-01-15 20:40:55 -0800237 mHandler = handler;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800238 readState();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800239 }
David Braunf5d83192013-09-16 13:43:51 -0700240
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800241 public void publish(Context context) {
242 mContext = context;
243 ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
244 }
245
Dianne Hackborn514074f2013-02-11 10:52:46 -0800246 public void systemReady() {
247 synchronized (this) {
248 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700249 for (int i = mUidStates.size() - 1; i >= 0; i--) {
250 UidState uidState = mUidStates.valueAt(i);
251
252 String[] packageNames = getPackagesForUid(uidState.uid);
253 if (ArrayUtils.isEmpty(packageNames)) {
254 uidState.clear();
255 mUidStates.removeAt(i);
256 changed = true;
257 continue;
258 }
259
260 ArrayMap<String, Ops> pkgs = uidState.pkgOps;
261 if (pkgs == null) {
262 continue;
263 }
264
Dianne Hackborn514074f2013-02-11 10:52:46 -0800265 Iterator<Ops> it = pkgs.values().iterator();
266 while (it.hasNext()) {
267 Ops ops = it.next();
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700268 int curUid = -1;
Dianne Hackborn514074f2013-02-11 10:52:46 -0800269 try {
Jeff Sharkeycd654482016-01-08 17:42:11 -0700270 curUid = AppGlobals.getPackageManager().getPackageUid(ops.packageName,
271 PackageManager.MATCH_UNINSTALLED_PACKAGES,
Svet Ganov2af57082015-07-30 08:44:20 -0700272 UserHandle.getUserId(ops.uidState.uid));
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700273 } catch (RemoteException ignored) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800274 }
Svet Ganov2af57082015-07-30 08:44:20 -0700275 if (curUid != ops.uidState.uid) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800276 Slog.i(TAG, "Pruning old package " + ops.packageName
Svet Ganov2af57082015-07-30 08:44:20 -0700277 + "/" + ops.uidState + ": new uid=" + curUid);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800278 it.remove();
279 changed = true;
280 }
281 }
Svet Ganov2af57082015-07-30 08:44:20 -0700282
283 if (uidState.isDefault()) {
284 mUidStates.removeAt(i);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800285 }
286 }
287 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800288 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800289 }
290 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700291
292 MountServiceInternal mountServiceInternal = LocalServices.getService(
293 MountServiceInternal.class);
294 mountServiceInternal.addExternalStoragePolicy(
295 new MountServiceInternal.ExternalStorageMountPolicy() {
296 @Override
297 public int getMountMode(int uid, String packageName) {
298 if (Process.isIsolated(uid)) {
299 return Zygote.MOUNT_EXTERNAL_NONE;
300 }
301 if (noteOperation(AppOpsManager.OP_READ_EXTERNAL_STORAGE, uid,
302 packageName) != AppOpsManager.MODE_ALLOWED) {
303 return Zygote.MOUNT_EXTERNAL_NONE;
304 }
305 if (noteOperation(AppOpsManager.OP_WRITE_EXTERNAL_STORAGE, uid,
306 packageName) != AppOpsManager.MODE_ALLOWED) {
307 return Zygote.MOUNT_EXTERNAL_READ;
308 }
309 return Zygote.MOUNT_EXTERNAL_WRITE;
310 }
311
312 @Override
313 public boolean hasExternalStorage(int uid, String packageName) {
314 final int mountMode = getMountMode(uid, packageName);
315 return mountMode == Zygote.MOUNT_EXTERNAL_READ
316 || mountMode == Zygote.MOUNT_EXTERNAL_WRITE;
317 }
318 });
Dianne Hackborn514074f2013-02-11 10:52:46 -0800319 }
320
321 public void packageRemoved(int uid, String packageName) {
322 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700323 UidState uidState = mUidStates.get(uid);
324 if (uidState == null) {
325 return;
326 }
327
328 boolean changed = false;
329
330 // Remove any package state if such.
331 if (uidState.pkgOps != null && uidState.pkgOps.remove(packageName) != null) {
332 changed = true;
333 }
334
335 // If we just nuked the last package state check if the UID is valid.
336 if (changed && uidState.pkgOps.isEmpty()
337 && getPackagesForUid(uid).length <= 0) {
338 mUidStates.remove(uid);
339 }
340
341 if (changed) {
342 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800343 }
344 }
345 }
346
347 public void uidRemoved(int uid) {
348 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700349 if (mUidStates.indexOfKey(uid) >= 0) {
350 mUidStates.remove(uid);
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800351 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800352 }
353 }
354 }
355
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800356 public void shutdown() {
357 Slog.w(TAG, "Writing app ops before shutdown...");
Dianne Hackborn35654b62013-01-14 17:38:02 -0800358 boolean doWrite = false;
359 synchronized (this) {
360 if (mWriteScheduled) {
361 mWriteScheduled = false;
362 doWrite = true;
363 }
364 }
365 if (doWrite) {
366 writeState();
367 }
368 }
369
Dianne Hackborn72e39832013-01-18 18:36:09 -0800370 private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
371 ArrayList<AppOpsManager.OpEntry> resOps = null;
372 if (ops == null) {
373 resOps = new ArrayList<AppOpsManager.OpEntry>();
374 for (int j=0; j<pkgOps.size(); j++) {
375 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800376 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Svet Ganov99b60432015-06-27 13:15:22 -0700377 curOp.rejectTime, curOp.duration, curOp.proxyUid,
378 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800379 }
380 } else {
381 for (int j=0; j<ops.length; j++) {
382 Op curOp = pkgOps.get(ops[j]);
383 if (curOp != null) {
384 if (resOps == null) {
385 resOps = new ArrayList<AppOpsManager.OpEntry>();
386 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800387 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Svet Ganov99b60432015-06-27 13:15:22 -0700388 curOp.rejectTime, curOp.duration, curOp.proxyUid,
389 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800390 }
391 }
392 }
393 return resOps;
394 }
395
Dianne Hackborn35654b62013-01-14 17:38:02 -0800396 @Override
397 public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
398 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
399 Binder.getCallingPid(), Binder.getCallingUid(), null);
400 ArrayList<AppOpsManager.PackageOps> res = null;
401 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700402 final int uidStateCount = mUidStates.size();
403 for (int i = 0; i < uidStateCount; i++) {
404 UidState uidState = mUidStates.valueAt(i);
405 if (uidState.pkgOps == null || uidState.pkgOps.isEmpty()) {
406 continue;
407 }
408 ArrayMap<String, Ops> packages = uidState.pkgOps;
409 final int packageCount = packages.size();
410 for (int j = 0; j < packageCount; j++) {
411 Ops pkgOps = packages.valueAt(j);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800412 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800413 if (resOps != null) {
414 if (res == null) {
415 res = new ArrayList<AppOpsManager.PackageOps>();
416 }
417 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700418 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800419 res.add(resPackage);
420 }
421 }
422 }
423 }
424 return res;
425 }
426
427 @Override
Dianne Hackborn72e39832013-01-18 18:36:09 -0800428 public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
429 int[] ops) {
430 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
431 Binder.getCallingPid(), Binder.getCallingUid(), null);
432 synchronized (this) {
433 Ops pkgOps = getOpsLocked(uid, packageName, false);
434 if (pkgOps == null) {
435 return null;
436 }
437 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
438 if (resOps == null) {
439 return null;
440 }
441 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
442 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700443 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800444 res.add(resPackage);
445 return res;
446 }
447 }
448
Dianne Hackborn607b4142013-08-02 18:10:10 -0700449 private void pruneOp(Op op, int uid, String packageName) {
450 if (op.time == 0 && op.rejectTime == 0) {
451 Ops ops = getOpsLocked(uid, packageName, false);
452 if (ops != null) {
453 ops.remove(op.op);
454 if (ops.size() <= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -0700455 UidState uidState = ops.uidState;
456 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700457 if (pkgOps != null) {
458 pkgOps.remove(ops.packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700459 if (pkgOps.isEmpty()) {
460 uidState.pkgOps = null;
461 }
462 if (uidState.isDefault()) {
463 mUidStates.remove(uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700464 }
465 }
466 }
467 }
468 }
469 }
470
Dianne Hackborn72e39832013-01-18 18:36:09 -0800471 @Override
Svet Ganov2af57082015-07-30 08:44:20 -0700472 public void setUidMode(int code, int uid, int mode) {
473 if (Binder.getCallingPid() != Process.myPid()) {
474 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
475 Binder.getCallingPid(), Binder.getCallingUid(), null);
476 }
477 verifyIncomingOp(code);
478 code = AppOpsManager.opToSwitch(code);
479
480 synchronized (this) {
481 final int defaultMode = AppOpsManager.opToDefaultMode(code);
482
483 UidState uidState = getUidStateLocked(uid, false);
484 if (uidState == null) {
485 if (mode == defaultMode) {
486 return;
487 }
488 uidState = new UidState(uid);
489 uidState.opModes = new SparseIntArray();
490 uidState.opModes.put(code, mode);
491 mUidStates.put(uid, uidState);
492 scheduleWriteLocked();
493 } else if (uidState.opModes == null) {
494 if (mode != defaultMode) {
495 uidState.opModes = new SparseIntArray();
496 uidState.opModes.put(code, mode);
497 scheduleWriteLocked();
498 }
499 } else {
500 if (uidState.opModes.get(code) == mode) {
501 return;
502 }
503 if (mode == defaultMode) {
504 uidState.opModes.delete(code);
505 if (uidState.opModes.size() <= 0) {
506 uidState.opModes = null;
507 }
508 } else {
509 uidState.opModes.put(code, mode);
510 }
511 scheduleWriteLocked();
512 }
513 }
514
Svetoslav215b44a2015-08-04 19:03:40 -0700515 String[] uidPackageNames = getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -0700516 ArrayMap<Callback, ArraySet<String>> callbackSpecs = null;
517
riddle_hsu40b300f2015-11-23 13:22:03 +0800518 synchronized (this) {
519 ArrayList<Callback> callbacks = mOpModeWatchers.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -0700520 if (callbacks != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700521 final int callbackCount = callbacks.size();
522 for (int i = 0; i < callbackCount; i++) {
523 Callback callback = callbacks.get(i);
riddle_hsu40b300f2015-11-23 13:22:03 +0800524 ArraySet<String> changedPackages = new ArraySet<>();
525 Collections.addAll(changedPackages, uidPackageNames);
526 callbackSpecs = new ArrayMap<>();
527 callbackSpecs.put(callback, changedPackages);
528 }
529 }
530
531 for (String uidPackageName : uidPackageNames) {
532 callbacks = mPackageModeWatchers.get(uidPackageName);
533 if (callbacks != null) {
534 if (callbackSpecs == null) {
535 callbackSpecs = new ArrayMap<>();
Svet Ganov2af57082015-07-30 08:44:20 -0700536 }
riddle_hsu40b300f2015-11-23 13:22:03 +0800537 final int callbackCount = callbacks.size();
538 for (int i = 0; i < callbackCount; i++) {
539 Callback callback = callbacks.get(i);
540 ArraySet<String> changedPackages = callbackSpecs.get(callback);
541 if (changedPackages == null) {
542 changedPackages = new ArraySet<>();
543 callbackSpecs.put(callback, changedPackages);
544 }
545 changedPackages.add(uidPackageName);
546 }
Svet Ganov2af57082015-07-30 08:44:20 -0700547 }
548 }
549 }
550
551 if (callbackSpecs == null) {
552 return;
553 }
554
555 // There are components watching for mode changes such as window manager
556 // and location manager which are in our process. The callbacks in these
557 // components may require permissions our remote caller does not have.
558 final long identity = Binder.clearCallingIdentity();
559 try {
560 for (int i = 0; i < callbackSpecs.size(); i++) {
561 Callback callback = callbackSpecs.keyAt(i);
562 ArraySet<String> reportedPackageNames = callbackSpecs.valueAt(i);
563 try {
564 if (reportedPackageNames == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700565 callback.mCallback.opChanged(code, uid, null);
Svet Ganov2af57082015-07-30 08:44:20 -0700566 } else {
567 final int reportedPackageCount = reportedPackageNames.size();
568 for (int j = 0; j < reportedPackageCount; j++) {
569 String reportedPackageName = reportedPackageNames.valueAt(j);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700570 callback.mCallback.opChanged(code, uid, reportedPackageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700571 }
572 }
573 } catch (RemoteException e) {
574 Log.w(TAG, "Error dispatching op op change", e);
575 }
576 }
577 } finally {
578 Binder.restoreCallingIdentity(identity);
579 }
580 }
581
582 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800583 public void setMode(int code, int uid, String packageName, int mode) {
Dianne Hackbornb64afe12014-07-22 16:29:04 -0700584 if (Binder.getCallingPid() != Process.myPid()) {
585 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
586 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborn133b9df2014-07-01 13:06:10 -0700587 }
Dianne Hackborn961321f2013-02-05 17:22:41 -0800588 verifyIncomingOp(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800589 ArrayList<Callback> repCbs = null;
590 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800591 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700592 UidState uidState = getUidStateLocked(uid, false);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800593 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800594 if (op != null) {
595 if (op.mode != mode) {
596 op.mode = mode;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800597 ArrayList<Callback> cbs = mOpModeWatchers.get(code);
598 if (cbs != null) {
599 if (repCbs == null) {
600 repCbs = new ArrayList<Callback>();
601 }
602 repCbs.addAll(cbs);
603 }
604 cbs = mPackageModeWatchers.get(packageName);
605 if (cbs != null) {
606 if (repCbs == null) {
607 repCbs = new ArrayList<Callback>();
608 }
609 repCbs.addAll(cbs);
610 }
David Braunf5d83192013-09-16 13:43:51 -0700611 if (mode == AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800612 // If going into the default mode, prune this op
613 // if there is nothing else interesting in it.
Dianne Hackborn607b4142013-08-02 18:10:10 -0700614 pruneOp(op, uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800615 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800616 scheduleFastWriteLocked();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800617 }
618 }
619 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800620 if (repCbs != null) {
Svet Ganov38536112015-05-19 12:45:52 -0700621 // There are components watching for mode changes such as window manager
622 // and location manager which are in our process. The callbacks in these
623 // components may require permissions our remote caller does not have.
624 final long identity = Binder.clearCallingIdentity();
625 try {
626 for (int i = 0; i < repCbs.size(); i++) {
627 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700628 repCbs.get(i).mCallback.opChanged(code, uid, packageName);
Svet Ganov38536112015-05-19 12:45:52 -0700629 } catch (RemoteException e) {
630 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800631 }
Svet Ganov38536112015-05-19 12:45:52 -0700632 } finally {
633 Binder.restoreCallingIdentity(identity);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800634 }
635 }
636 }
637
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700638 private static HashMap<Callback, ArrayList<ChangeRec>> addCallbacks(
639 HashMap<Callback, ArrayList<ChangeRec>> callbacks,
640 int op, int uid, String packageName, ArrayList<Callback> cbs) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700641 if (cbs == null) {
642 return callbacks;
643 }
644 if (callbacks == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700645 callbacks = new HashMap<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700646 }
Svet Ganov2af57082015-07-30 08:44:20 -0700647 boolean duplicate = false;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700648 for (int i=0; i<cbs.size(); i++) {
649 Callback cb = cbs.get(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700650 ArrayList<ChangeRec> reports = callbacks.get(cb);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700651 if (reports == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700652 reports = new ArrayList<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700653 callbacks.put(cb, reports);
Svet Ganov2af57082015-07-30 08:44:20 -0700654 } else {
655 final int reportCount = reports.size();
656 for (int j = 0; j < reportCount; j++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700657 ChangeRec report = reports.get(j);
658 if (report.op == op && report.pkg.equals(packageName)) {
Svet Ganov2af57082015-07-30 08:44:20 -0700659 duplicate = true;
660 break;
661 }
662 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700663 }
Svet Ganov2af57082015-07-30 08:44:20 -0700664 if (!duplicate) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700665 reports.add(new ChangeRec(op, uid, packageName));
Svet Ganov2af57082015-07-30 08:44:20 -0700666 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700667 }
668 return callbacks;
669 }
670
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700671 static final class ChangeRec {
672 final int op;
673 final int uid;
674 final String pkg;
675
676 ChangeRec(int _op, int _uid, String _pkg) {
677 op = _op;
678 uid = _uid;
679 pkg = _pkg;
680 }
681 }
682
Dianne Hackborn607b4142013-08-02 18:10:10 -0700683 @Override
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800684 public void resetAllModes(int reqUserId, String reqPackageName) {
685 final int callingPid = Binder.getCallingPid();
686 final int callingUid = Binder.getCallingUid();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700687 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800688 callingPid, callingUid, null);
689 reqUserId = ActivityManager.handleIncomingUser(callingPid, callingUid, reqUserId,
690 true, true, "resetAllModes", null);
Svet Ganov2af57082015-07-30 08:44:20 -0700691
692 int reqUid = -1;
693 if (reqPackageName != null) {
694 try {
695 reqUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -0700696 reqPackageName, PackageManager.MATCH_UNINSTALLED_PACKAGES, reqUserId);
Svet Ganov2af57082015-07-30 08:44:20 -0700697 } catch (RemoteException e) {
698 /* ignore - local call */
699 }
700 }
701
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700702 HashMap<Callback, ArrayList<ChangeRec>> callbacks = null;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700703 synchronized (this) {
704 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700705 for (int i = mUidStates.size() - 1; i >= 0; i--) {
706 UidState uidState = mUidStates.valueAt(i);
707
708 SparseIntArray opModes = uidState.opModes;
709 if (opModes != null && (uidState.uid == reqUid || reqUid == -1)) {
710 final int uidOpCount = opModes.size();
711 for (int j = uidOpCount - 1; j >= 0; j--) {
712 final int code = opModes.keyAt(j);
713 if (AppOpsManager.opAllowsReset(code)) {
714 opModes.removeAt(j);
715 if (opModes.size() <= 0) {
716 uidState.opModes = null;
717 }
718 for (String packageName : getPackagesForUid(uidState.uid)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700719 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700720 mOpModeWatchers.get(code));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700721 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700722 mPackageModeWatchers.get(packageName));
723 }
724 }
725 }
726 }
727
728 if (uidState.pkgOps == null) {
729 continue;
730 }
731
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800732 if (reqUserId != UserHandle.USER_ALL
Svet Ganov2af57082015-07-30 08:44:20 -0700733 && reqUserId != UserHandle.getUserId(uidState.uid)) {
Alexandra Gherghinad6a98972014-08-04 17:05:34 +0100734 // Skip any ops for a different user
735 continue;
736 }
Svet Ganov2af57082015-07-30 08:44:20 -0700737
738 Map<String, Ops> packages = uidState.pkgOps;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700739 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
740 while (it.hasNext()) {
741 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700742 String packageName = ent.getKey();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800743 if (reqPackageName != null && !reqPackageName.equals(packageName)) {
744 // Skip any ops for a different package
745 continue;
746 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700747 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700748 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700749 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -0700750 if (AppOpsManager.opAllowsReset(curOp.op)
751 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -0700752 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700753 changed = true;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700754 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -0700755 mOpModeWatchers.get(curOp.op));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700756 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -0700757 mPackageModeWatchers.get(packageName));
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700758 if (curOp.time == 0 && curOp.rejectTime == 0) {
759 pkgOps.removeAt(j);
760 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700761 }
762 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700763 if (pkgOps.size() == 0) {
764 it.remove();
765 }
766 }
Svet Ganov2af57082015-07-30 08:44:20 -0700767 if (uidState.isDefault()) {
768 mUidStates.remove(uidState.uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700769 }
770 }
Svet Ganov2af57082015-07-30 08:44:20 -0700771
Dianne Hackborn607b4142013-08-02 18:10:10 -0700772 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800773 scheduleFastWriteLocked();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700774 }
775 }
776 if (callbacks != null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700777 for (Map.Entry<Callback, ArrayList<ChangeRec>> ent : callbacks.entrySet()) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700778 Callback cb = ent.getKey();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700779 ArrayList<ChangeRec> reports = ent.getValue();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700780 for (int i=0; i<reports.size(); i++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700781 ChangeRec rep = reports.get(i);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700782 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700783 cb.mCallback.opChanged(rep.op, rep.uid, rep.pkg);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700784 } catch (RemoteException e) {
785 }
786 }
787 }
788 }
789 }
790
Dianne Hackbornc2293022013-02-06 23:14:49 -0800791 @Override
792 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -0800793 if (callback == null) {
794 return;
795 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800796 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700797 op = (op != AppOpsManager.OP_NONE) ? AppOpsManager.opToSwitch(op) : op;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800798 Callback cb = mModeWatchers.get(callback.asBinder());
799 if (cb == null) {
800 cb = new Callback(callback);
801 mModeWatchers.put(callback.asBinder(), cb);
802 }
803 if (op != AppOpsManager.OP_NONE) {
804 ArrayList<Callback> cbs = mOpModeWatchers.get(op);
805 if (cbs == null) {
806 cbs = new ArrayList<Callback>();
807 mOpModeWatchers.put(op, cbs);
808 }
809 cbs.add(cb);
810 }
811 if (packageName != null) {
812 ArrayList<Callback> cbs = mPackageModeWatchers.get(packageName);
813 if (cbs == null) {
814 cbs = new ArrayList<Callback>();
815 mPackageModeWatchers.put(packageName, cbs);
816 }
817 cbs.add(cb);
818 }
819 }
820 }
821
822 @Override
823 public void stopWatchingMode(IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -0800824 if (callback == null) {
825 return;
826 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800827 synchronized (this) {
828 Callback cb = mModeWatchers.remove(callback.asBinder());
829 if (cb != null) {
830 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700831 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800832 ArrayList<Callback> cbs = mOpModeWatchers.valueAt(i);
833 cbs.remove(cb);
834 if (cbs.size() <= 0) {
835 mOpModeWatchers.removeAt(i);
836 }
837 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700838 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
839 ArrayList<Callback> cbs = mPackageModeWatchers.valueAt(i);
840 cbs.remove(cb);
841 if (cbs.size() <= 0) {
842 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800843 }
844 }
845 }
846 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800847 }
848
849 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700850 public IBinder getToken(IBinder clientToken) {
851 synchronized (this) {
852 ClientState cs = mClients.get(clientToken);
853 if (cs == null) {
854 cs = new ClientState(clientToken);
855 mClients.put(clientToken, cs);
856 }
857 return cs;
858 }
859 }
860
861 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800862 public int checkOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800863 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800864 verifyIncomingOp(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800865 synchronized (this) {
Jason Monk1c7c3192014-06-26 12:52:18 -0400866 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -0400867 return AppOpsManager.MODE_IGNORED;
868 }
Svet Ganov2af57082015-07-30 08:44:20 -0700869 code = AppOpsManager.opToSwitch(code);
870 UidState uidState = getUidStateLocked(uid, false);
871 if (uidState != null && uidState.opModes != null) {
872 final int uidMode = uidState.opModes.get(code);
873 if (uidMode != AppOpsManager.MODE_ALLOWED) {
874 return uidMode;
875 }
876 }
877 Op op = getOpLocked(code, uid, packageName, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800878 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -0700879 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800880 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800881 return op.mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800882 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800883 }
884
885 @Override
John Spurlock7b414672014-07-18 13:02:39 -0400886 public int checkAudioOperation(int code, int usage, int uid, String packageName) {
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000887 if (isApplicationSuspended(packageName, uid)) {
888 Log.i(TAG, "Audio disabled for suspended package=" + packageName + " for uid=" + uid);
889 return AppOpsManager.MODE_IGNORED;
890 }
891
John Spurlock1af30c72014-03-10 08:33:35 -0400892 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -0400893 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -0400894 if (mode != AppOpsManager.MODE_ALLOWED) {
895 return mode;
896 }
897 }
898 return checkOperation(code, uid, packageName);
899 }
900
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000901 private boolean isApplicationSuspended(String pkg, int uid) {
902 int userId = UserHandle.getUserId(uid);
903
904 ApplicationInfo ai;
905 try {
906 ai = AppGlobals.getPackageManager().getApplicationInfo(pkg, 0, userId);
907 if (ai == null) {
908 Log.w(TAG, "No application info for package " + pkg + " and user " + userId);
909 return false;
910 }
911 } catch (RemoteException re) {
912 throw new SecurityException("Could not talk to package manager service");
913 }
914
915 return ((ai.flags & FLAG_SUSPENDED) != 0);
916 }
917
John Spurlock7b414672014-07-18 13:02:39 -0400918 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
919 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
920 if (usageRestrictions != null) {
921 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -0400922 if (r != null && !r.exceptionPackages.contains(packageName)) {
923 return r.mode;
924 }
925 }
926 return AppOpsManager.MODE_ALLOWED;
927 }
928
929 @Override
John Spurlock7b414672014-07-18 13:02:39 -0400930 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -0400931 String[] exceptionPackages) {
932 verifyIncomingUid(uid);
933 verifyIncomingOp(code);
934 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -0400935 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
936 if (usageRestrictions == null) {
937 usageRestrictions = new SparseArray<Restriction>();
938 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -0400939 }
John Spurlock7b414672014-07-18 13:02:39 -0400940 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -0400941 if (mode != AppOpsManager.MODE_ALLOWED) {
942 final Restriction r = new Restriction();
943 r.mode = mode;
944 if (exceptionPackages != null) {
945 final int N = exceptionPackages.length;
946 r.exceptionPackages = new ArraySet<String>(N);
947 for (int i = 0; i < N; i++) {
948 final String pkg = exceptionPackages[i];
949 if (pkg != null) {
950 r.exceptionPackages.add(pkg.trim());
951 }
952 }
953 }
John Spurlock7b414672014-07-18 13:02:39 -0400954 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -0400955 }
956 }
957 }
958
959 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700960 public int checkPackage(int uid, String packageName) {
961 synchronized (this) {
Dianne Hackborn0fcef842014-09-12 15:38:33 -0700962 if (getOpsRawLocked(uid, packageName, true) != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700963 return AppOpsManager.MODE_ALLOWED;
964 } else {
965 return AppOpsManager.MODE_ERRORED;
966 }
967 }
968 }
969
970 @Override
Svet Ganov99b60432015-06-27 13:15:22 -0700971 public int noteProxyOperation(int code, String proxyPackageName,
972 int proxiedUid, String proxiedPackageName) {
973 verifyIncomingOp(code);
974 final int proxyMode = noteOperationUnchecked(code, Binder.getCallingUid(),
975 proxyPackageName, -1, null);
976 if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
977 return proxyMode;
978 }
979 return noteOperationUnchecked(code, proxiedUid, proxiedPackageName,
980 Binder.getCallingUid(), proxyPackageName);
Svet Ganov99b60432015-06-27 13:15:22 -0700981 }
982
983 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800984 public int noteOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800985 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800986 verifyIncomingOp(code);
Svet Ganov99b60432015-06-27 13:15:22 -0700987 return noteOperationUnchecked(code, uid, packageName, 0, null);
988 }
989
990 private int noteOperationUnchecked(int code, int uid, String packageName,
991 int proxyUid, String proxyPackageName) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800992 synchronized (this) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800993 Ops ops = getOpsLocked(uid, packageName, true);
994 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800995 if (DEBUG) Log.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
996 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700997 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800998 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800999 Op op = getOpLocked(ops, code, true);
Jason Monk1c7c3192014-06-26 12:52:18 -04001000 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001001 return AppOpsManager.MODE_IGNORED;
1002 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001003 if (op.duration == -1) {
1004 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
1005 + " code " + code + " time=" + op.time + " duration=" + op.duration);
1006 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001007 op.duration = 0;
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001008 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001009 UidState uidState = ops.uidState;
1010 if (uidState.opModes != null) {
1011 final int uidMode = uidState.opModes.get(switchCode);
1012 if (uidMode != AppOpsManager.MODE_ALLOWED) {
1013 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1014 + switchCode + " (" + code + ") uid " + uid + " package "
1015 + packageName);
1016 op.rejectTime = System.currentTimeMillis();
1017 return uidMode;
1018 }
1019 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001020 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
1021 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
1022 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1023 + switchCode + " (" + code + ") uid " + uid + " package " + packageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001024 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001025 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001026 }
1027 if (DEBUG) Log.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
1028 + " package " + packageName);
1029 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001030 op.rejectTime = 0;
Svet Ganov99b60432015-06-27 13:15:22 -07001031 op.proxyUid = proxyUid;
1032 op.proxyPackageName = proxyPackageName;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001033 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001034 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001035 }
1036
1037 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001038 public int startOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001039 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001040 verifyIncomingOp(code);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001041 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001042 synchronized (this) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001043 Ops ops = getOpsLocked(uid, packageName, true);
1044 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001045 if (DEBUG) Log.d(TAG, "startOperation: no op for code " + code + " uid " + uid
1046 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001047 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001048 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001049 Op op = getOpLocked(ops, code, true);
Jason Monk1c7c3192014-06-26 12:52:18 -04001050 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001051 return AppOpsManager.MODE_IGNORED;
1052 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001053 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001054 UidState uidState = ops.uidState;
1055 if (uidState.opModes != null) {
1056 final int uidMode = uidState.opModes.get(switchCode);
1057 if (uidMode != AppOpsManager.MODE_ALLOWED) {
1058 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1059 + switchCode + " (" + code + ") uid " + uid + " package "
1060 + packageName);
1061 op.rejectTime = System.currentTimeMillis();
1062 return uidMode;
1063 }
1064 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001065 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
1066 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
1067 if (DEBUG) Log.d(TAG, "startOperation: reject #" + op.mode + " for code "
1068 + switchCode + " (" + code + ") uid " + uid + " package " + packageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001069 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001070 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001071 }
1072 if (DEBUG) Log.d(TAG, "startOperation: allowing code " + code + " uid " + uid
1073 + " package " + packageName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001074 if (op.nesting == 0) {
1075 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001076 op.rejectTime = 0;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001077 op.duration = -1;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001078 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001079 op.nesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001080 if (client.mStartedOps != null) {
1081 client.mStartedOps.add(op);
1082 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001083 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001084 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001085 }
1086
1087 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001088 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001089 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001090 verifyIncomingOp(code);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001091 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001092 synchronized (this) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001093 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001094 if (op == null) {
1095 return;
1096 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001097 if (client.mStartedOps != null) {
1098 if (!client.mStartedOps.remove(op)) {
1099 throw new IllegalStateException("Operation not started: uid" + op.uid
1100 + " pkg=" + op.packageName + " op=" + op.op);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001101 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001102 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001103 finishOperationLocked(op);
1104 }
1105 }
1106
Svet Ganovb9d71a62015-04-30 10:38:13 -07001107 @Override
1108 public int permissionToOpCode(String permission) {
1109 return AppOpsManager.permissionToOpCode(permission);
1110 }
1111
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001112 void finishOperationLocked(Op op) {
1113 if (op.nesting <= 1) {
1114 if (op.nesting == 1) {
1115 op.duration = (int)(System.currentTimeMillis() - op.time);
1116 op.time += op.duration;
1117 } else {
1118 Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
1119 + op.packageName + " code " + op.op + " time=" + op.time
1120 + " duration=" + op.duration + " nesting=" + op.nesting);
1121 }
1122 op.nesting = 0;
1123 } else {
1124 op.nesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001125 }
1126 }
1127
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001128 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001129 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001130 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001131 }
1132 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001133 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001134 }
1135 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
1136 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001137 }
1138
Dianne Hackborn961321f2013-02-05 17:22:41 -08001139 private void verifyIncomingOp(int op) {
1140 if (op >= 0 && op < AppOpsManager._NUM_OP) {
1141 return;
1142 }
1143 throw new IllegalArgumentException("Bad operation #" + op);
1144 }
1145
Svet Ganov2af57082015-07-30 08:44:20 -07001146 private UidState getUidStateLocked(int uid, boolean edit) {
1147 UidState uidState = mUidStates.get(uid);
1148 if (uidState == null) {
1149 if (!edit) {
1150 return null;
1151 }
1152 uidState = new UidState(uid);
1153 mUidStates.put(uid, uidState);
1154 }
1155 return uidState;
1156 }
1157
Dianne Hackborn72e39832013-01-18 18:36:09 -08001158 private Ops getOpsLocked(int uid, String packageName, boolean edit) {
Dianne Hackborn0fcef842014-09-12 15:38:33 -07001159 if (uid == 0) {
1160 packageName = "root";
1161 } else if (uid == Process.SHELL_UID) {
1162 packageName = "com.android.shell";
1163 }
1164 return getOpsRawLocked(uid, packageName, edit);
1165 }
1166
1167 private Ops getOpsRawLocked(int uid, String packageName, boolean edit) {
Svet Ganov2af57082015-07-30 08:44:20 -07001168 UidState uidState = getUidStateLocked(uid, edit);
1169 if (uidState == null) {
1170 return null;
1171 }
1172
1173 if (uidState.pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001174 if (!edit) {
1175 return null;
1176 }
Svet Ganov2af57082015-07-30 08:44:20 -07001177 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001178 }
Svet Ganov2af57082015-07-30 08:44:20 -07001179
1180 Ops ops = uidState.pkgOps.get(packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001181 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001182 if (!edit) {
1183 return null;
1184 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001185 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001186 // This is the first time we have seen this package name under this uid,
1187 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -08001188 if (uid != 0) {
1189 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001190 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001191 int pkgUid = -1;
1192 try {
Jason Monk1c7c3192014-06-26 12:52:18 -04001193 ApplicationInfo appInfo = ActivityThread.getPackageManager()
Jeff Sharkeycd654482016-01-08 17:42:11 -07001194 .getApplicationInfo(packageName,
1195 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1196 UserHandle.getUserId(uid));
Jason Monk1c7c3192014-06-26 12:52:18 -04001197 if (appInfo != null) {
1198 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001199 isPrivileged = (appInfo.privateFlags
1200 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001201 } else {
1202 if ("media".equals(packageName)) {
1203 pkgUid = Process.MEDIA_UID;
1204 isPrivileged = false;
Andy Hunged0ea402015-10-30 14:11:46 -07001205 } else if ("audioserver".equals(packageName)) {
1206 pkgUid = Process.AUDIOSERVER_UID;
1207 isPrivileged = false;
Chien-Yu Chen75cade02016-01-11 10:56:21 -08001208 } else if ("cameraserver".equals(packageName)) {
1209 pkgUid = Process.CAMERASERVER_UID;
1210 isPrivileged = false;
Jason Monk1c7c3192014-06-26 12:52:18 -04001211 }
Dianne Hackborn713df152013-05-17 11:27:57 -07001212 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001213 } catch (RemoteException e) {
1214 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001215 }
1216 if (pkgUid != uid) {
1217 // Oops! The package name is not valid for the uid they are calling
1218 // under. Abort.
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001219 RuntimeException ex = new RuntimeException("here");
1220 ex.fillInStackTrace();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001221 Slog.w(TAG, "Bad call: specified package " + packageName
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001222 + " under uid " + uid + " but it is really " + pkgUid, ex);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001223 return null;
1224 }
1225 } finally {
1226 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001227 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001228 }
Svet Ganov2af57082015-07-30 08:44:20 -07001229 ops = new Ops(packageName, uidState, isPrivileged);
1230 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001231 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08001232 return ops;
1233 }
1234
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001235 private void scheduleWriteLocked() {
1236 if (!mWriteScheduled) {
1237 mWriteScheduled = true;
1238 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
1239 }
1240 }
1241
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001242 private void scheduleFastWriteLocked() {
1243 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001244 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001245 mFastWriteScheduled = true;
1246 mHandler.removeCallbacks(mWriteRunner);
1247 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001248 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001249 }
1250
Dianne Hackborn72e39832013-01-18 18:36:09 -08001251 private Op getOpLocked(int code, int uid, String packageName, boolean edit) {
1252 Ops ops = getOpsLocked(uid, packageName, edit);
1253 if (ops == null) {
1254 return null;
1255 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001256 return getOpLocked(ops, code, edit);
1257 }
1258
1259 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001260 Op op = ops.get(code);
1261 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001262 if (!edit) {
1263 return null;
1264 }
Svet Ganov2af57082015-07-30 08:44:20 -07001265 op = new Op(ops.uidState.uid, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001266 ops.put(code, op);
1267 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001268 if (edit) {
1269 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001270 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001271 return op;
1272 }
1273
Jason Monk1c7c3192014-06-26 12:52:18 -04001274 private boolean isOpRestricted(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04001275 int userHandle = UserHandle.getUserId(uid);
1276 boolean[] opRestrictions = mOpRestrictions.get(userHandle);
1277 if ((opRestrictions != null) && opRestrictions[code]) {
Jason Monk1c7c3192014-06-26 12:52:18 -04001278 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
1279 synchronized (this) {
1280 Ops ops = getOpsLocked(uid, packageName, true);
1281 if ((ops != null) && ops.isPrivileged) {
1282 return false;
1283 }
1284 }
1285 }
Julia Reynolds401de172014-07-24 18:21:29 -04001286 return true;
Jason Monk62062992014-05-06 09:55:28 -04001287 }
1288 return false;
1289 }
1290
Dianne Hackborn35654b62013-01-14 17:38:02 -08001291 void readState() {
1292 synchronized (mFile) {
1293 synchronized (this) {
1294 FileInputStream stream;
1295 try {
1296 stream = mFile.openRead();
1297 } catch (FileNotFoundException e) {
1298 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
1299 return;
1300 }
1301 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001302 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001303 try {
1304 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001305 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001306 int type;
1307 while ((type = parser.next()) != XmlPullParser.START_TAG
1308 && type != XmlPullParser.END_DOCUMENT) {
1309 ;
1310 }
1311
1312 if (type != XmlPullParser.START_TAG) {
1313 throw new IllegalStateException("no start tag found");
1314 }
1315
1316 int outerDepth = parser.getDepth();
1317 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1318 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1319 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1320 continue;
1321 }
1322
1323 String tagName = parser.getName();
1324 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001325 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07001326 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07001327 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001328 } else {
1329 Slog.w(TAG, "Unknown element under <app-ops>: "
1330 + parser.getName());
1331 XmlUtils.skipCurrentTag(parser);
1332 }
1333 }
1334 success = true;
1335 } catch (IllegalStateException e) {
1336 Slog.w(TAG, "Failed parsing " + e);
1337 } catch (NullPointerException e) {
1338 Slog.w(TAG, "Failed parsing " + e);
1339 } catch (NumberFormatException e) {
1340 Slog.w(TAG, "Failed parsing " + e);
1341 } catch (XmlPullParserException e) {
1342 Slog.w(TAG, "Failed parsing " + e);
1343 } catch (IOException e) {
1344 Slog.w(TAG, "Failed parsing " + e);
1345 } catch (IndexOutOfBoundsException e) {
1346 Slog.w(TAG, "Failed parsing " + e);
1347 } finally {
1348 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07001349 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001350 }
1351 try {
1352 stream.close();
1353 } catch (IOException e) {
1354 }
1355 }
1356 }
1357 }
1358 }
1359
Svet Ganov2af57082015-07-30 08:44:20 -07001360 void readUidOps(XmlPullParser parser) throws NumberFormatException,
1361 XmlPullParserException, IOException {
1362 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
1363 int outerDepth = parser.getDepth();
1364 int type;
1365 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1366 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1367 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1368 continue;
1369 }
1370
1371 String tagName = parser.getName();
1372 if (tagName.equals("op")) {
1373 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
1374 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
1375 UidState uidState = getUidStateLocked(uid, true);
1376 if (uidState.opModes == null) {
1377 uidState.opModes = new SparseIntArray();
1378 }
1379 uidState.opModes.put(code, mode);
1380 } else {
1381 Slog.w(TAG, "Unknown element under <uid-ops>: "
1382 + parser.getName());
1383 XmlUtils.skipCurrentTag(parser);
1384 }
1385 }
1386 }
1387
Dave Burke0997c5bd2013-08-02 20:25:02 +00001388 void readPackage(XmlPullParser parser) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001389 XmlPullParserException, IOException {
1390 String pkgName = parser.getAttributeValue(null, "n");
1391 int outerDepth = parser.getDepth();
1392 int type;
1393 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1394 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1395 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1396 continue;
1397 }
1398
1399 String tagName = parser.getName();
1400 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001401 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001402 } else {
1403 Slog.w(TAG, "Unknown element under <pkg>: "
1404 + parser.getName());
1405 XmlUtils.skipCurrentTag(parser);
1406 }
1407 }
1408 }
1409
Dave Burke0997c5bd2013-08-02 20:25:02 +00001410 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001411 XmlPullParserException, IOException {
1412 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Jason Monk1c7c3192014-06-26 12:52:18 -04001413 String isPrivilegedString = parser.getAttributeValue(null, "p");
1414 boolean isPrivileged = false;
1415 if (isPrivilegedString == null) {
1416 try {
1417 IPackageManager packageManager = ActivityThread.getPackageManager();
1418 if (packageManager != null) {
1419 ApplicationInfo appInfo = ActivityThread.getPackageManager()
1420 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
1421 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001422 isPrivileged = (appInfo.privateFlags
1423 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001424 }
1425 } else {
1426 // Could not load data, don't add to cache so it will be loaded later.
1427 return;
1428 }
1429 } catch (RemoteException e) {
1430 Slog.w(TAG, "Could not contact PackageManager", e);
1431 }
1432 } else {
1433 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
1434 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001435 int outerDepth = parser.getDepth();
1436 int type;
1437 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1438 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1439 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1440 continue;
1441 }
1442
1443 String tagName = parser.getName();
1444 if (tagName.equals("op")) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001445 Op op = new Op(uid, pkgName, Integer.parseInt(parser.getAttributeValue(null, "n")));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001446 String mode = parser.getAttributeValue(null, "m");
1447 if (mode != null) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001448 op.mode = Integer.parseInt(mode);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001449 }
1450 String time = parser.getAttributeValue(null, "t");
1451 if (time != null) {
1452 op.time = Long.parseLong(time);
1453 }
1454 time = parser.getAttributeValue(null, "r");
1455 if (time != null) {
1456 op.rejectTime = Long.parseLong(time);
1457 }
1458 String dur = parser.getAttributeValue(null, "d");
1459 if (dur != null) {
1460 op.duration = Integer.parseInt(dur);
1461 }
Svet Ganov99b60432015-06-27 13:15:22 -07001462 String proxyUid = parser.getAttributeValue(null, "pu");
1463 if (proxyUid != null) {
1464 op.proxyUid = Integer.parseInt(proxyUid);
1465 }
1466 String proxyPackageName = parser.getAttributeValue(null, "pp");
1467 if (proxyPackageName != null) {
1468 op.proxyPackageName = proxyPackageName;
1469 }
Svet Ganov2af57082015-07-30 08:44:20 -07001470
1471 UidState uidState = getUidStateLocked(uid, true);
1472 if (uidState.pkgOps == null) {
1473 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001474 }
Svet Ganov2af57082015-07-30 08:44:20 -07001475
1476 Ops ops = uidState.pkgOps.get(pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001477 if (ops == null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001478 ops = new Ops(pkgName, uidState, isPrivileged);
1479 uidState.pkgOps.put(pkgName, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001480 }
1481 ops.put(op.op, op);
1482 } else {
1483 Slog.w(TAG, "Unknown element under <pkg>: "
1484 + parser.getName());
1485 XmlUtils.skipCurrentTag(parser);
1486 }
1487 }
1488 }
1489
1490 void writeState() {
1491 synchronized (mFile) {
1492 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
1493
1494 FileOutputStream stream;
1495 try {
1496 stream = mFile.startWrite();
1497 } catch (IOException e) {
1498 Slog.w(TAG, "Failed to write state: " + e);
1499 return;
1500 }
1501
1502 try {
1503 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001504 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001505 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001506 out.startTag(null, "app-ops");
Svet Ganov2af57082015-07-30 08:44:20 -07001507
1508 final int uidStateCount = mUidStates.size();
1509 for (int i = 0; i < uidStateCount; i++) {
1510 UidState uidState = mUidStates.valueAt(i);
1511 if (uidState.opModes != null && uidState.opModes.size() > 0) {
1512 out.startTag(null, "uid");
1513 out.attribute(null, "n", Integer.toString(uidState.uid));
1514 SparseIntArray uidOpModes = uidState.opModes;
1515 final int opCount = uidOpModes.size();
1516 for (int j = 0; j < opCount; j++) {
1517 final int op = uidOpModes.keyAt(j);
1518 final int mode = uidOpModes.valueAt(j);
1519 out.startTag(null, "op");
1520 out.attribute(null, "n", Integer.toString(op));
1521 out.attribute(null, "m", Integer.toString(mode));
1522 out.endTag(null, "op");
1523 }
1524 out.endTag(null, "uid");
1525 }
1526 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001527
1528 if (allOps != null) {
1529 String lastPkg = null;
1530 for (int i=0; i<allOps.size(); i++) {
1531 AppOpsManager.PackageOps pkg = allOps.get(i);
1532 if (!pkg.getPackageName().equals(lastPkg)) {
1533 if (lastPkg != null) {
1534 out.endTag(null, "pkg");
1535 }
1536 lastPkg = pkg.getPackageName();
1537 out.startTag(null, "pkg");
1538 out.attribute(null, "n", lastPkg);
1539 }
1540 out.startTag(null, "uid");
1541 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04001542 synchronized (this) {
1543 Ops ops = getOpsLocked(pkg.getUid(), pkg.getPackageName(), false);
1544 // Should always be present as the list of PackageOps is generated
1545 // from Ops.
1546 if (ops != null) {
1547 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
1548 } else {
1549 out.attribute(null, "p", Boolean.toString(false));
1550 }
1551 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001552 List<AppOpsManager.OpEntry> ops = pkg.getOps();
1553 for (int j=0; j<ops.size(); j++) {
1554 AppOpsManager.OpEntry op = ops.get(j);
1555 out.startTag(null, "op");
1556 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07001557 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001558 out.attribute(null, "m", Integer.toString(op.getMode()));
1559 }
1560 long time = op.getTime();
1561 if (time != 0) {
1562 out.attribute(null, "t", Long.toString(time));
1563 }
1564 time = op.getRejectTime();
1565 if (time != 0) {
1566 out.attribute(null, "r", Long.toString(time));
1567 }
1568 int dur = op.getDuration();
1569 if (dur != 0) {
1570 out.attribute(null, "d", Integer.toString(dur));
1571 }
Svet Ganov99b60432015-06-27 13:15:22 -07001572 int proxyUid = op.getProxyUid();
1573 if (proxyUid != -1) {
1574 out.attribute(null, "pu", Integer.toString(proxyUid));
1575 }
1576 String proxyPackageName = op.getProxyPackageName();
1577 if (proxyPackageName != null) {
1578 out.attribute(null, "pp", proxyPackageName);
1579 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001580 out.endTag(null, "op");
1581 }
1582 out.endTag(null, "uid");
1583 }
1584 if (lastPkg != null) {
1585 out.endTag(null, "pkg");
1586 }
1587 }
1588
1589 out.endTag(null, "app-ops");
1590 out.endDocument();
1591 mFile.finishWrite(stream);
1592 } catch (IOException e) {
1593 Slog.w(TAG, "Failed to write state, restoring backup.", e);
1594 mFile.failWrite(stream);
1595 }
1596 }
1597 }
1598
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001599 static class Shell extends ShellCommand {
1600 final IAppOpsService mInterface;
1601 final AppOpsService mInternal;
1602
1603 int userId = UserHandle.USER_SYSTEM;
1604 String packageName;
1605 String opStr;
1606 int op;
1607 int packageUid;
1608
1609 Shell(IAppOpsService iface, AppOpsService internal) {
1610 mInterface = iface;
1611 mInternal = internal;
1612 }
1613
1614 @Override
1615 public int onCommand(String cmd) {
1616 return onShellCommand(this, cmd);
1617 }
1618
1619 @Override
1620 public void onHelp() {
1621 PrintWriter pw = getOutPrintWriter();
1622 dumpCommandHelp(pw);
1623 }
1624
1625 private int strOpToOp(String op, PrintWriter err) {
1626 try {
1627 return AppOpsManager.strOpToOp(op);
1628 } catch (IllegalArgumentException e) {
1629 }
1630 try {
1631 return Integer.parseInt(op);
1632 } catch (NumberFormatException e) {
1633 }
1634 try {
1635 return AppOpsManager.strDebugOpToOp(op);
1636 } catch (IllegalArgumentException e) {
1637 err.println("Error: " + e.getMessage());
1638 return -1;
1639 }
1640 }
1641
1642 int parseUserPackageOp(boolean reqOp, PrintWriter err) throws RemoteException {
1643 userId = UserHandle.USER_CURRENT;
1644 packageName = null;
1645 opStr = null;
1646 for (String argument; (argument = getNextArg()) != null;) {
1647 if ("--user".equals(argument)) {
1648 userId = UserHandle.parseUserArg(getNextArgRequired());
1649 } else {
1650 if (packageName == null) {
1651 packageName = argument;
1652 } else if (opStr == null) {
1653 opStr = argument;
1654 break;
1655 }
1656 }
1657 }
1658 if (packageName == null) {
1659 err.println("Error: Package name not specified.");
1660 return -1;
1661 } else if (opStr == null && reqOp) {
1662 err.println("Error: Operation not specified.");
1663 return -1;
1664 }
1665 if (opStr != null) {
1666 op = strOpToOp(opStr, err);
1667 if (op < 0) {
1668 return -1;
1669 }
1670 } else {
1671 op = AppOpsManager.OP_NONE;
1672 }
1673 if (userId == UserHandle.USER_CURRENT) {
1674 userId = ActivityManager.getCurrentUser();
1675 }
1676 if ("root".equals(packageName)) {
1677 packageUid = 0;
1678 } else {
Jeff Sharkeycd654482016-01-08 17:42:11 -07001679 packageUid = AppGlobals.getPackageManager().getPackageUid(packageName,
1680 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001681 }
1682 if (packageUid < 0) {
1683 err.println("Error: No UID for " + packageName + " in user " + userId);
1684 return -1;
1685 }
1686 return 0;
1687 }
1688 }
1689
1690 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
1691 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
1692 (new Shell(this, this)).exec(this, in, out, err, args, resultReceiver);
1693 }
1694
1695 static void dumpCommandHelp(PrintWriter pw) {
1696 pw.println("AppOps service (appops) commands:");
1697 pw.println(" help");
1698 pw.println(" Print this help text.");
1699 pw.println(" set [--user <USER_ID>] <PACKAGE> <OP> <MODE>");
1700 pw.println(" Set the mode for a particular application and operation.");
1701 pw.println(" get [--user <USER_ID>] <PACKAGE> [<OP>]");
1702 pw.println(" Return the mode for a particular application and optional operation.");
1703 pw.println(" reset [--user <USER_ID>] [<PACKAGE>]");
1704 pw.println(" Reset the given application or all applications to default modes.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001705 pw.println(" write-settings");
1706 pw.println(" Immediately write pending changes to storage.");
1707 pw.println(" read-settings");
1708 pw.println(" Read the last written settings, replacing current state in RAM.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001709 pw.println(" options:");
1710 pw.println(" <PACKAGE> an Android package name.");
1711 pw.println(" <OP> an AppOps operation.");
1712 pw.println(" <MODE> one of allow, ignore, deny, or default");
1713 pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
1714 pw.println(" specified, the current user is assumed.");
1715 }
1716
1717 static int onShellCommand(Shell shell, String cmd) {
1718 if (cmd == null) {
1719 return shell.handleDefaultCommands(cmd);
1720 }
1721 PrintWriter pw = shell.getOutPrintWriter();
1722 PrintWriter err = shell.getErrPrintWriter();
1723 try {
1724 switch (cmd) {
1725 case "set": {
1726 int res = shell.parseUserPackageOp(true, err);
1727 if (res < 0) {
1728 return res;
1729 }
1730 String modeStr = shell.getNextArg();
1731 if (modeStr == null) {
1732 err.println("Error: Mode not specified.");
1733 return -1;
1734 }
1735
1736 final int mode;
1737 switch (modeStr) {
1738 case "allow":
1739 mode = AppOpsManager.MODE_ALLOWED;
1740 break;
1741 case "deny":
1742 mode = AppOpsManager.MODE_ERRORED;
1743 break;
1744 case "ignore":
1745 mode = AppOpsManager.MODE_IGNORED;
1746 break;
1747 case "default":
1748 mode = AppOpsManager.MODE_DEFAULT;
1749 break;
1750 default:
1751 err.println("Error: Mode " + modeStr + " is not valid,");
1752 return -1;
1753 }
1754
1755 shell.mInterface.setMode(shell.op, shell.packageUid, shell.packageName, mode);
1756 return 0;
1757 }
1758 case "get": {
1759 int res = shell.parseUserPackageOp(false, err);
1760 if (res < 0) {
1761 return res;
1762 }
1763
1764 List<AppOpsManager.PackageOps> ops = shell.mInterface.getOpsForPackage(
1765 shell.packageUid, shell.packageName,
1766 shell.op != AppOpsManager.OP_NONE ? new int[] {shell.op} : null);
1767 if (ops == null || ops.size() <= 0) {
1768 pw.println("No operations.");
1769 return 0;
1770 }
1771 final long now = System.currentTimeMillis();
1772 for (int i=0; i<ops.size(); i++) {
1773 List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
1774 for (int j=0; j<entries.size(); j++) {
1775 AppOpsManager.OpEntry ent = entries.get(j);
1776 pw.print(AppOpsManager.opToName(ent.getOp()));
1777 pw.print(": ");
1778 switch (ent.getMode()) {
1779 case AppOpsManager.MODE_ALLOWED:
1780 pw.print("allow");
1781 break;
1782 case AppOpsManager.MODE_IGNORED:
1783 pw.print("ignore");
1784 break;
1785 case AppOpsManager.MODE_ERRORED:
1786 pw.print("deny");
1787 break;
1788 case AppOpsManager.MODE_DEFAULT:
1789 pw.print("default");
1790 break;
1791 default:
1792 pw.print("mode=");
1793 pw.print(ent.getMode());
1794 break;
1795 }
1796 if (ent.getTime() != 0) {
1797 pw.print("; time=");
1798 TimeUtils.formatDuration(now - ent.getTime(), pw);
1799 pw.print(" ago");
1800 }
1801 if (ent.getRejectTime() != 0) {
1802 pw.print("; rejectTime=");
1803 TimeUtils.formatDuration(now - ent.getRejectTime(), pw);
1804 pw.print(" ago");
1805 }
1806 if (ent.getDuration() == -1) {
1807 pw.print(" (running)");
1808 } else if (ent.getDuration() != 0) {
1809 pw.print("; duration=");
1810 TimeUtils.formatDuration(ent.getDuration(), pw);
1811 }
1812 pw.println();
1813 }
1814 }
1815 return 0;
1816 }
1817 case "reset": {
1818 String packageName = null;
1819 int userId = UserHandle.USER_CURRENT;
1820 for (String argument; (argument = shell.getNextArg()) != null;) {
1821 if ("--user".equals(argument)) {
1822 String userStr = shell.getNextArgRequired();
1823 userId = UserHandle.parseUserArg(userStr);
1824 } else {
1825 if (packageName == null) {
1826 packageName = argument;
1827 } else {
1828 err.println("Error: Unsupported argument: " + argument);
1829 return -1;
1830 }
1831 }
1832 }
1833
1834 if (userId == UserHandle.USER_CURRENT) {
1835 userId = ActivityManager.getCurrentUser();
1836 }
1837
1838 shell.mInterface.resetAllModes(userId, packageName);
1839 pw.print("Reset all modes for: ");
1840 if (userId == UserHandle.USER_ALL) {
1841 pw.print("all users");
1842 } else {
1843 pw.print("user "); pw.print(userId);
1844 }
1845 pw.print(", ");
1846 if (packageName == null) {
1847 pw.println("all packages");
1848 } else {
1849 pw.print("package "); pw.println(packageName);
1850 }
1851 return 0;
1852 }
1853 case "write-settings": {
1854 shell.mInternal.mContext.enforcePermission(
1855 android.Manifest.permission.UPDATE_APP_OPS_STATS,
1856 Binder.getCallingPid(), Binder.getCallingUid(), null);
1857 long token = Binder.clearCallingIdentity();
1858 try {
1859 synchronized (shell.mInternal) {
1860 shell.mInternal.mHandler.removeCallbacks(shell.mInternal.mWriteRunner);
1861 }
1862 shell.mInternal.writeState();
1863 pw.println("Current settings written.");
1864 } finally {
1865 Binder.restoreCallingIdentity(token);
1866 }
1867 return 0;
1868 }
1869 case "read-settings": {
1870 shell.mInternal.mContext.enforcePermission(
1871 android.Manifest.permission.UPDATE_APP_OPS_STATS,
1872 Binder.getCallingPid(), Binder.getCallingUid(), null);
1873 long token = Binder.clearCallingIdentity();
1874 try {
1875 shell.mInternal.readState();
1876 pw.println("Last settings read.");
1877 } finally {
1878 Binder.restoreCallingIdentity(token);
1879 }
1880 return 0;
1881 }
1882 default:
1883 return shell.handleDefaultCommands(cmd);
1884 }
1885 } catch (RemoteException e) {
1886 pw.println("Remote exception: " + e);
1887 }
1888 return -1;
1889 }
1890
1891 private void dumpHelp(PrintWriter pw) {
1892 pw.println("AppOps service (appops) dump options:");
1893 pw.println(" none");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001894 }
1895
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001896 @Override
1897 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1898 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1899 != PackageManager.PERMISSION_GRANTED) {
1900 pw.println("Permission Denial: can't dump ApOps service from from pid="
1901 + Binder.getCallingPid()
1902 + ", uid=" + Binder.getCallingUid());
1903 return;
1904 }
1905
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001906 if (args != null) {
1907 for (int i=0; i<args.length; i++) {
1908 String arg = args[i];
1909 if ("-h".equals(arg)) {
1910 dumpHelp(pw);
1911 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07001912 } else if ("-a".equals(arg)) {
1913 // dump all data
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001914 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
1915 pw.println("Unknown option: " + arg);
1916 return;
1917 } else {
1918 pw.println("Unknown command: " + arg);
1919 return;
1920 }
1921 }
1922 }
1923
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001924 synchronized (this) {
1925 pw.println("Current AppOps Service state:");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001926 final long now = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001927 boolean needSep = false;
1928 if (mOpModeWatchers.size() > 0) {
1929 needSep = true;
1930 pw.println(" Op mode watchers:");
1931 for (int i=0; i<mOpModeWatchers.size(); i++) {
1932 pw.print(" Op "); pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
1933 pw.println(":");
1934 ArrayList<Callback> callbacks = mOpModeWatchers.valueAt(i);
1935 for (int j=0; j<callbacks.size(); j++) {
1936 pw.print(" #"); pw.print(j); pw.print(": ");
1937 pw.println(callbacks.get(j));
1938 }
1939 }
1940 }
1941 if (mPackageModeWatchers.size() > 0) {
1942 needSep = true;
1943 pw.println(" Package mode watchers:");
1944 for (int i=0; i<mPackageModeWatchers.size(); i++) {
1945 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
1946 pw.println(":");
1947 ArrayList<Callback> callbacks = mPackageModeWatchers.valueAt(i);
1948 for (int j=0; j<callbacks.size(); j++) {
1949 pw.print(" #"); pw.print(j); pw.print(": ");
1950 pw.println(callbacks.get(j));
1951 }
1952 }
1953 }
1954 if (mModeWatchers.size() > 0) {
1955 needSep = true;
1956 pw.println(" All mode watchers:");
1957 for (int i=0; i<mModeWatchers.size(); i++) {
1958 pw.print(" "); pw.print(mModeWatchers.keyAt(i));
1959 pw.print(" -> "); pw.println(mModeWatchers.valueAt(i));
1960 }
1961 }
1962 if (mClients.size() > 0) {
1963 needSep = true;
1964 pw.println(" Clients:");
1965 for (int i=0; i<mClients.size(); i++) {
1966 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
1967 ClientState cs = mClients.valueAt(i);
1968 pw.print(" "); pw.println(cs);
1969 if (cs.mStartedOps != null && cs.mStartedOps.size() > 0) {
1970 pw.println(" Started ops:");
1971 for (int j=0; j<cs.mStartedOps.size(); j++) {
1972 Op op = cs.mStartedOps.get(j);
1973 pw.print(" "); pw.print("uid="); pw.print(op.uid);
1974 pw.print(" pkg="); pw.print(op.packageName);
1975 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
1976 }
1977 }
1978 }
1979 }
John Spurlock1af30c72014-03-10 08:33:35 -04001980 if (mAudioRestrictions.size() > 0) {
1981 boolean printedHeader = false;
1982 for (int o=0; o<mAudioRestrictions.size(); o++) {
1983 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
1984 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
1985 for (int i=0; i<restrictions.size(); i++) {
1986 if (!printedHeader){
1987 pw.println(" Audio Restrictions:");
1988 printedHeader = true;
1989 needSep = true;
1990 }
John Spurlock7b414672014-07-18 13:02:39 -04001991 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04001992 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04001993 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04001994 Restriction r = restrictions.valueAt(i);
1995 pw.print(": mode="); pw.println(r.mode);
1996 if (!r.exceptionPackages.isEmpty()) {
1997 pw.println(" Exceptions:");
1998 for (int j=0; j<r.exceptionPackages.size(); j++) {
1999 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
2000 }
2001 }
2002 }
2003 }
2004 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002005 if (needSep) {
2006 pw.println();
2007 }
Svet Ganov2af57082015-07-30 08:44:20 -07002008 for (int i=0; i<mUidStates.size(); i++) {
2009 UidState uidState = mUidStates.valueAt(i);
2010
2011 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
2012
2013 SparseIntArray opModes = uidState.opModes;
2014 if (opModes != null) {
2015 final int opModeCount = opModes.size();
2016 for (int j = 0; j < opModeCount; j++) {
2017 final int code = opModes.keyAt(j);
2018 final int mode = opModes.valueAt(j);
2019 pw.print(" "); pw.print(AppOpsManager.opToName(code));
2020 pw.print(": mode="); pw.println(mode);
2021 }
2022 }
2023
2024 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
2025 if (pkgOps == null) {
2026 continue;
2027 }
2028
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002029 for (Ops ops : pkgOps.values()) {
2030 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
2031 for (int j=0; j<ops.size(); j++) {
2032 Op op = ops.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002033 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
2034 pw.print(": mode="); pw.print(op.mode);
2035 if (op.time != 0) {
2036 pw.print("; time="); TimeUtils.formatDuration(now-op.time, pw);
2037 pw.print(" ago");
2038 }
2039 if (op.rejectTime != 0) {
2040 pw.print("; rejectTime="); TimeUtils.formatDuration(now-op.rejectTime, pw);
2041 pw.print(" ago");
2042 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002043 if (op.duration == -1) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002044 pw.print(" (running)");
2045 } else if (op.duration != 0) {
2046 pw.print("; duration="); TimeUtils.formatDuration(op.duration, pw);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002047 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002048 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002049 }
2050 }
2051 }
2052 }
2053 }
John Spurlock1af30c72014-03-10 08:33:35 -04002054
2055 private static final class Restriction {
2056 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
2057 int mode;
2058 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
2059 }
Jason Monk62062992014-05-06 09:55:28 -04002060
2061 @Override
Jason Monk62062992014-05-06 09:55:28 -04002062 public void setUserRestrictions(Bundle restrictions, int userHandle) throws RemoteException {
2063 checkSystemUid("setUserRestrictions");
2064 boolean[] opRestrictions = mOpRestrictions.get(userHandle);
2065 if (opRestrictions == null) {
2066 opRestrictions = new boolean[AppOpsManager._NUM_OP];
2067 mOpRestrictions.put(userHandle, opRestrictions);
2068 }
2069 for (int i = 0; i < opRestrictions.length; ++i) {
2070 String restriction = AppOpsManager.opToRestriction(i);
2071 if (restriction != null) {
2072 opRestrictions[i] = restrictions.getBoolean(restriction, false);
2073 } else {
2074 opRestrictions[i] = false;
2075 }
2076 }
2077 }
2078
2079 @Override
2080 public void removeUser(int userHandle) throws RemoteException {
2081 checkSystemUid("removeUser");
2082 mOpRestrictions.remove(userHandle);
Jason Monk62062992014-05-06 09:55:28 -04002083 }
2084
2085 private void checkSystemUid(String function) {
2086 int uid = Binder.getCallingUid();
2087 if (uid != Process.SYSTEM_UID) {
2088 throw new SecurityException(function + " must by called by the system");
2089 }
2090 }
2091
Svet Ganov2af57082015-07-30 08:44:20 -07002092 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07002093 String[] packageNames = null;
Svet Ganov2af57082015-07-30 08:44:20 -07002094 try {
riddle_hsu40b300f2015-11-23 13:22:03 +08002095 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -07002096 } catch (RemoteException e) {
2097 /* ignore - local call */
2098 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07002099 if (packageNames == null) {
2100 return EmptyArray.STRING;
2101 }
2102 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07002103 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002104}