blob: 29f8a1130792f5dd3329f5276be038b16faf1994 [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
Philip P. Moltmanne683f192017-06-23 14:05:04 -070019import android.Manifest;
20import android.app.ActivityManager;
21import android.app.ActivityThread;
22import android.app.AppGlobals;
23import android.app.AppOpsManager;
24import android.content.Context;
25import android.content.pm.ApplicationInfo;
26import android.content.pm.IPackageManager;
27import android.content.pm.PackageManager;
28import android.content.pm.PackageManagerInternal;
29import android.content.pm.UserInfo;
30import android.media.AudioAttributes;
31import android.os.AsyncTask;
32import android.os.Binder;
33import android.os.Bundle;
34import android.os.Handler;
35import android.os.IBinder;
36import android.os.Process;
37import android.os.RemoteException;
38import android.os.ResultReceiver;
39import android.os.ServiceManager;
40import android.os.ShellCallback;
41import android.os.ShellCommand;
42import android.os.UserHandle;
43import android.os.UserManager;
44import android.os.storage.StorageManagerInternal;
45import android.util.ArrayMap;
46import android.util.ArraySet;
47import android.util.AtomicFile;
48import android.util.Log;
49import android.util.Slog;
50import android.util.SparseArray;
51import android.util.SparseIntArray;
52import android.util.TimeUtils;
53import android.util.Xml;
54
55import com.android.internal.app.IAppOpsCallback;
56import com.android.internal.app.IAppOpsService;
57import com.android.internal.os.Zygote;
58import com.android.internal.util.ArrayUtils;
59import com.android.internal.util.DumpUtils;
60import com.android.internal.util.FastXmlSerializer;
61import com.android.internal.util.Preconditions;
62import com.android.internal.util.XmlUtils;
63
64import libcore.util.EmptyArray;
65
66import org.xmlpull.v1.XmlPullParser;
67import org.xmlpull.v1.XmlPullParserException;
68import org.xmlpull.v1.XmlSerializer;
69
Dianne Hackborna06de0f2012-12-11 16:34:47 -080070import java.io.File;
71import java.io.FileDescriptor;
Dianne Hackborn35654b62013-01-14 17:38:02 -080072import java.io.FileInputStream;
73import java.io.FileNotFoundException;
74import java.io.FileOutputStream;
75import java.io.IOException;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080076import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010077import java.nio.charset.StandardCharsets;
Dianne Hackborn35654b62013-01-14 17:38:02 -080078import java.util.ArrayList;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -070079import java.util.Arrays;
Svetoslav215b44a2015-08-04 19:03:40 -070080import java.util.Collections;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080081import java.util.HashMap;
Dianne Hackbornc2293022013-02-06 23:14:49 -080082import java.util.Iterator;
Dianne Hackborn35654b62013-01-14 17:38:02 -080083import java.util.List;
Dianne Hackborn607b4142013-08-02 18:10:10 -070084import java.util.Map;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080085
Dianne Hackborna06de0f2012-12-11 16:34:47 -080086public class AppOpsService extends IAppOpsService.Stub {
87 static final String TAG = "AppOps";
Dianne Hackborn35654b62013-01-14 17:38:02 -080088 static final boolean DEBUG = false;
89
90 // Write at most every 30 minutes.
91 static final long WRITE_DELAY = DEBUG ? 1000 : 30*60*1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080092
93 Context mContext;
94 final AtomicFile mFile;
Dianne Hackborn35654b62013-01-14 17:38:02 -080095 final Handler mHandler;
96
97 boolean mWriteScheduled;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -080098 boolean mFastWriteScheduled;
Dianne Hackborn35654b62013-01-14 17:38:02 -080099 final Runnable mWriteRunner = new Runnable() {
100 public void run() {
101 synchronized (AppOpsService.this) {
102 mWriteScheduled = false;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800103 mFastWriteScheduled = false;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800104 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
105 @Override protected Void doInBackground(Void... params) {
106 writeState();
107 return null;
108 }
109 };
110 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
111 }
112 }
113 };
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800114
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800115 private final SparseArray<UidState> mUidStates = new SparseArray<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800116
Ruben Brunk29931bc2016-03-11 00:24:26 -0800117 /*
118 * These are app op restrictions imposed per user from various parties.
Ruben Brunk29931bc2016-03-11 00:24:26 -0800119 */
Svetoslav Ganova8bbd762016-05-13 17:08:16 -0700120 private final ArrayMap<IBinder, ClientRestrictionState> mOpUserRestrictions = new ArrayMap<>();
Jason Monk62062992014-05-06 09:55:28 -0400121
Svet Ganov2af57082015-07-30 08:44:20 -0700122 private static final class UidState {
123 public final int uid;
124 public ArrayMap<String, Ops> pkgOps;
125 public SparseIntArray opModes;
126
127 public UidState(int uid) {
128 this.uid = uid;
129 }
130
131 public void clear() {
132 pkgOps = null;
133 opModes = null;
134 }
135
136 public boolean isDefault() {
137 return (pkgOps == null || pkgOps.isEmpty())
138 && (opModes == null || opModes.size() <= 0);
139 }
140 }
141
Dianne Hackbornc2293022013-02-06 23:14:49 -0800142 public final static class Ops extends SparseArray<Op> {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800143 public final String packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700144 public final UidState uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400145 public final boolean isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800146
Svet Ganov2af57082015-07-30 08:44:20 -0700147 public Ops(String _packageName, UidState _uidState, boolean _isPrivileged) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800148 packageName = _packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700149 uidState = _uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400150 isPrivileged = _isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800151 }
152 }
153
Dianne Hackbornc2293022013-02-06 23:14:49 -0800154 public final static class Op {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700155 public final int uid;
156 public final String packageName;
Svet Ganov99b60432015-06-27 13:15:22 -0700157 public int proxyUid = -1;
158 public String proxyPackageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800159 public final int op;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800160 public int mode;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800161 public int duration;
162 public long time;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800163 public long rejectTime;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800164 public int nesting;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800165
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700166 public Op(int _uid, String _packageName, int _op) {
167 uid = _uid;
168 packageName = _packageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800169 op = _op;
David Braunf5d83192013-09-16 13:43:51 -0700170 mode = AppOpsManager.opToDefaultMode(op);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800171 }
172 }
173
Dianne Hackborn68d76552017-02-27 15:32:03 -0800174 final SparseArray<ArraySet<Callback>> mOpModeWatchers = new SparseArray<>();
175 final ArrayMap<String, ArraySet<Callback>> mPackageModeWatchers = new ArrayMap<>();
176 final ArrayMap<IBinder, Callback> mModeWatchers = new ArrayMap<>();
177 final SparseArray<SparseArray<Restriction>> mAudioRestrictions = new SparseArray<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800178
179 public final class Callback implements DeathRecipient {
180 final IAppOpsCallback mCallback;
181
182 public Callback(IAppOpsCallback callback) {
183 mCallback = callback;
184 try {
185 mCallback.asBinder().linkToDeath(this, 0);
186 } catch (RemoteException e) {
187 }
188 }
189
190 public void unlinkToDeath() {
191 mCallback.asBinder().unlinkToDeath(this, 0);
192 }
193
194 @Override
195 public void binderDied() {
196 stopWatchingMode(mCallback);
197 }
198 }
199
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700200 final ArrayMap<IBinder, ClientState> mClients = new ArrayMap<IBinder, ClientState>();
201
202 public final class ClientState extends Binder implements DeathRecipient {
203 final IBinder mAppToken;
204 final int mPid;
205 final ArrayList<Op> mStartedOps;
206
207 public ClientState(IBinder appToken) {
208 mAppToken = appToken;
209 mPid = Binder.getCallingPid();
210 if (appToken instanceof Binder) {
211 // For local clients, there is no reason to track them.
212 mStartedOps = null;
213 } else {
214 mStartedOps = new ArrayList<Op>();
215 try {
216 mAppToken.linkToDeath(this, 0);
217 } catch (RemoteException e) {
218 }
219 }
220 }
221
222 @Override
223 public String toString() {
224 return "ClientState{" +
225 "mAppToken=" + mAppToken +
226 ", " + (mStartedOps != null ? ("pid=" + mPid) : "local") +
227 '}';
228 }
229
230 @Override
231 public void binderDied() {
232 synchronized (AppOpsService.this) {
233 for (int i=mStartedOps.size()-1; i>=0; i--) {
234 finishOperationLocked(mStartedOps.get(i));
235 }
236 mClients.remove(mAppToken);
237 }
238 }
239 }
240
Jeff Brown6f357d32014-01-15 20:40:55 -0800241 public AppOpsService(File storagePath, Handler handler) {
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600242 LockGuard.installLock(this, LockGuard.INDEX_APP_OPS);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800243 mFile = new AtomicFile(storagePath);
Jeff Brown6f357d32014-01-15 20:40:55 -0800244 mHandler = handler;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800245 readState();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800246 }
David Braunf5d83192013-09-16 13:43:51 -0700247
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800248 public void publish(Context context) {
249 mContext = context;
250 ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
251 }
252
Dianne Hackborn514074f2013-02-11 10:52:46 -0800253 public void systemReady() {
254 synchronized (this) {
255 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700256 for (int i = mUidStates.size() - 1; i >= 0; i--) {
257 UidState uidState = mUidStates.valueAt(i);
258
259 String[] packageNames = getPackagesForUid(uidState.uid);
260 if (ArrayUtils.isEmpty(packageNames)) {
261 uidState.clear();
262 mUidStates.removeAt(i);
263 changed = true;
264 continue;
265 }
266
267 ArrayMap<String, Ops> pkgs = uidState.pkgOps;
268 if (pkgs == null) {
269 continue;
270 }
271
Dianne Hackborn514074f2013-02-11 10:52:46 -0800272 Iterator<Ops> it = pkgs.values().iterator();
273 while (it.hasNext()) {
274 Ops ops = it.next();
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700275 int curUid = -1;
Dianne Hackborn514074f2013-02-11 10:52:46 -0800276 try {
Jeff Sharkeycd654482016-01-08 17:42:11 -0700277 curUid = AppGlobals.getPackageManager().getPackageUid(ops.packageName,
278 PackageManager.MATCH_UNINSTALLED_PACKAGES,
Svet Ganov2af57082015-07-30 08:44:20 -0700279 UserHandle.getUserId(ops.uidState.uid));
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700280 } catch (RemoteException ignored) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800281 }
Svet Ganov2af57082015-07-30 08:44:20 -0700282 if (curUid != ops.uidState.uid) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800283 Slog.i(TAG, "Pruning old package " + ops.packageName
Svet Ganov2af57082015-07-30 08:44:20 -0700284 + "/" + ops.uidState + ": new uid=" + curUid);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800285 it.remove();
286 changed = true;
287 }
288 }
Svet Ganov2af57082015-07-30 08:44:20 -0700289
290 if (uidState.isDefault()) {
291 mUidStates.removeAt(i);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800292 }
293 }
294 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800295 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800296 }
297 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700298
Suprabh Shuklaaef25132017-01-23 18:09:03 -0800299 PackageManagerInternal packageManagerInternal = LocalServices.getService(
300 PackageManagerInternal.class);
301 packageManagerInternal.setExternalSourcesPolicy(
302 new PackageManagerInternal.ExternalSourcesPolicy() {
303 @Override
304 public int getPackageTrustedToInstallApps(String packageName, int uid) {
305 int appOpMode = checkOperation(AppOpsManager.OP_REQUEST_INSTALL_PACKAGES,
306 uid, packageName);
307 switch (appOpMode) {
308 case AppOpsManager.MODE_ALLOWED:
309 return PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
310 case AppOpsManager.MODE_ERRORED:
311 return PackageManagerInternal.ExternalSourcesPolicy.USER_BLOCKED;
312 default:
313 return PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT;
314 }
315 }
316 });
317
Sudheer Shanka2250d562016-11-07 15:41:02 -0800318 StorageManagerInternal storageManagerInternal = LocalServices.getService(
319 StorageManagerInternal.class);
320 storageManagerInternal.addExternalStoragePolicy(
321 new StorageManagerInternal.ExternalStorageMountPolicy() {
Svet Ganov6ee871e2015-07-10 14:29:33 -0700322 @Override
323 public int getMountMode(int uid, String packageName) {
324 if (Process.isIsolated(uid)) {
325 return Zygote.MOUNT_EXTERNAL_NONE;
326 }
327 if (noteOperation(AppOpsManager.OP_READ_EXTERNAL_STORAGE, uid,
328 packageName) != AppOpsManager.MODE_ALLOWED) {
329 return Zygote.MOUNT_EXTERNAL_NONE;
330 }
331 if (noteOperation(AppOpsManager.OP_WRITE_EXTERNAL_STORAGE, uid,
332 packageName) != AppOpsManager.MODE_ALLOWED) {
333 return Zygote.MOUNT_EXTERNAL_READ;
334 }
335 return Zygote.MOUNT_EXTERNAL_WRITE;
336 }
337
338 @Override
339 public boolean hasExternalStorage(int uid, String packageName) {
340 final int mountMode = getMountMode(uid, packageName);
341 return mountMode == Zygote.MOUNT_EXTERNAL_READ
342 || mountMode == Zygote.MOUNT_EXTERNAL_WRITE;
343 }
344 });
Dianne Hackborn514074f2013-02-11 10:52:46 -0800345 }
346
347 public void packageRemoved(int uid, String packageName) {
348 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700349 UidState uidState = mUidStates.get(uid);
350 if (uidState == null) {
351 return;
352 }
353
354 boolean changed = false;
355
356 // Remove any package state if such.
357 if (uidState.pkgOps != null && uidState.pkgOps.remove(packageName) != null) {
358 changed = true;
359 }
360
361 // If we just nuked the last package state check if the UID is valid.
362 if (changed && uidState.pkgOps.isEmpty()
363 && getPackagesForUid(uid).length <= 0) {
364 mUidStates.remove(uid);
365 }
366
367 if (changed) {
368 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800369 }
370 }
371 }
372
373 public void uidRemoved(int uid) {
374 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700375 if (mUidStates.indexOfKey(uid) >= 0) {
376 mUidStates.remove(uid);
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800377 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800378 }
379 }
380 }
381
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800382 public void shutdown() {
383 Slog.w(TAG, "Writing app ops before shutdown...");
Dianne Hackborn35654b62013-01-14 17:38:02 -0800384 boolean doWrite = false;
385 synchronized (this) {
386 if (mWriteScheduled) {
387 mWriteScheduled = false;
388 doWrite = true;
389 }
390 }
391 if (doWrite) {
392 writeState();
393 }
394 }
395
Dianne Hackborn72e39832013-01-18 18:36:09 -0800396 private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
397 ArrayList<AppOpsManager.OpEntry> resOps = null;
398 if (ops == null) {
399 resOps = new ArrayList<AppOpsManager.OpEntry>();
400 for (int j=0; j<pkgOps.size(); j++) {
401 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800402 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Svet Ganov99b60432015-06-27 13:15:22 -0700403 curOp.rejectTime, curOp.duration, curOp.proxyUid,
404 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800405 }
406 } else {
407 for (int j=0; j<ops.length; j++) {
408 Op curOp = pkgOps.get(ops[j]);
409 if (curOp != null) {
410 if (resOps == null) {
411 resOps = new ArrayList<AppOpsManager.OpEntry>();
412 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800413 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Svet Ganov99b60432015-06-27 13:15:22 -0700414 curOp.rejectTime, curOp.duration, curOp.proxyUid,
415 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800416 }
417 }
418 }
419 return resOps;
420 }
421
Dianne Hackbornc7214a32017-04-11 13:32:47 -0700422 private ArrayList<AppOpsManager.OpEntry> collectOps(SparseIntArray uidOps, int[] ops) {
423 ArrayList<AppOpsManager.OpEntry> resOps = null;
424 if (ops == null) {
425 resOps = new ArrayList<>();
426 for (int j=0; j<uidOps.size(); j++) {
427 resOps.add(new AppOpsManager.OpEntry(uidOps.keyAt(j), uidOps.valueAt(j),
428 0, 0, 0, -1, null));
429 }
430 } else {
431 for (int j=0; j<ops.length; j++) {
432 int index = uidOps.indexOfKey(ops[j]);
433 if (index >= 0) {
434 if (resOps == null) {
435 resOps = new ArrayList<>();
436 }
437 resOps.add(new AppOpsManager.OpEntry(uidOps.keyAt(index), uidOps.valueAt(index),
438 0, 0, 0, -1, null));
439 }
440 }
441 }
442 return resOps;
443 }
444
Dianne Hackborn35654b62013-01-14 17:38:02 -0800445 @Override
446 public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
447 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
448 Binder.getCallingPid(), Binder.getCallingUid(), null);
449 ArrayList<AppOpsManager.PackageOps> res = null;
450 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700451 final int uidStateCount = mUidStates.size();
452 for (int i = 0; i < uidStateCount; i++) {
453 UidState uidState = mUidStates.valueAt(i);
454 if (uidState.pkgOps == null || uidState.pkgOps.isEmpty()) {
455 continue;
456 }
457 ArrayMap<String, Ops> packages = uidState.pkgOps;
458 final int packageCount = packages.size();
459 for (int j = 0; j < packageCount; j++) {
460 Ops pkgOps = packages.valueAt(j);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800461 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800462 if (resOps != null) {
463 if (res == null) {
464 res = new ArrayList<AppOpsManager.PackageOps>();
465 }
466 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700467 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800468 res.add(resPackage);
469 }
470 }
471 }
472 }
473 return res;
474 }
475
476 @Override
Dianne Hackborn72e39832013-01-18 18:36:09 -0800477 public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
478 int[] ops) {
479 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
480 Binder.getCallingPid(), Binder.getCallingUid(), null);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000481 String resolvedPackageName = resolvePackageName(uid, packageName);
482 if (resolvedPackageName == null) {
483 return Collections.emptyList();
484 }
Dianne Hackborn72e39832013-01-18 18:36:09 -0800485 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000486 Ops pkgOps = getOpsRawLocked(uid, resolvedPackageName, false);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800487 if (pkgOps == null) {
488 return null;
489 }
490 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
491 if (resOps == null) {
492 return null;
493 }
494 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
495 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700496 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800497 res.add(resPackage);
498 return res;
499 }
500 }
501
Dianne Hackbornc7214a32017-04-11 13:32:47 -0700502 @Override
503 public List<AppOpsManager.PackageOps> getUidOps(int uid, int[] ops) {
504 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
505 Binder.getCallingPid(), Binder.getCallingUid(), null);
506 synchronized (this) {
507 UidState uidState = getUidStateLocked(uid, false);
508 if (uidState == null) {
509 return null;
510 }
511 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(uidState.opModes, ops);
512 if (resOps == null) {
513 return null;
514 }
515 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
516 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
517 null, uidState.uid, resOps);
518 res.add(resPackage);
519 return res;
520 }
521 }
522
Dianne Hackborn607b4142013-08-02 18:10:10 -0700523 private void pruneOp(Op op, int uid, String packageName) {
524 if (op.time == 0 && op.rejectTime == 0) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000525 Ops ops = getOpsRawLocked(uid, packageName, false);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700526 if (ops != null) {
527 ops.remove(op.op);
528 if (ops.size() <= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -0700529 UidState uidState = ops.uidState;
530 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700531 if (pkgOps != null) {
532 pkgOps.remove(ops.packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700533 if (pkgOps.isEmpty()) {
534 uidState.pkgOps = null;
535 }
536 if (uidState.isDefault()) {
537 mUidStates.remove(uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700538 }
539 }
540 }
541 }
542 }
543 }
544
Dianne Hackborn72e39832013-01-18 18:36:09 -0800545 @Override
Svet Ganov2af57082015-07-30 08:44:20 -0700546 public void setUidMode(int code, int uid, int mode) {
547 if (Binder.getCallingPid() != Process.myPid()) {
548 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
549 Binder.getCallingPid(), Binder.getCallingUid(), null);
550 }
551 verifyIncomingOp(code);
552 code = AppOpsManager.opToSwitch(code);
553
554 synchronized (this) {
555 final int defaultMode = AppOpsManager.opToDefaultMode(code);
556
557 UidState uidState = getUidStateLocked(uid, false);
558 if (uidState == null) {
559 if (mode == defaultMode) {
560 return;
561 }
562 uidState = new UidState(uid);
563 uidState.opModes = new SparseIntArray();
564 uidState.opModes.put(code, mode);
565 mUidStates.put(uid, uidState);
566 scheduleWriteLocked();
567 } else if (uidState.opModes == null) {
568 if (mode != defaultMode) {
569 uidState.opModes = new SparseIntArray();
570 uidState.opModes.put(code, mode);
571 scheduleWriteLocked();
572 }
573 } else {
574 if (uidState.opModes.get(code) == mode) {
575 return;
576 }
577 if (mode == defaultMode) {
578 uidState.opModes.delete(code);
579 if (uidState.opModes.size() <= 0) {
580 uidState.opModes = null;
581 }
582 } else {
583 uidState.opModes.put(code, mode);
584 }
585 scheduleWriteLocked();
586 }
587 }
588
Svetoslav215b44a2015-08-04 19:03:40 -0700589 String[] uidPackageNames = getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -0700590 ArrayMap<Callback, ArraySet<String>> callbackSpecs = null;
591
riddle_hsu40b300f2015-11-23 13:22:03 +0800592 synchronized (this) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800593 ArraySet<Callback> callbacks = mOpModeWatchers.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -0700594 if (callbacks != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700595 final int callbackCount = callbacks.size();
596 for (int i = 0; i < callbackCount; i++) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800597 Callback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +0800598 ArraySet<String> changedPackages = new ArraySet<>();
599 Collections.addAll(changedPackages, uidPackageNames);
600 callbackSpecs = new ArrayMap<>();
601 callbackSpecs.put(callback, changedPackages);
602 }
603 }
604
605 for (String uidPackageName : uidPackageNames) {
606 callbacks = mPackageModeWatchers.get(uidPackageName);
607 if (callbacks != null) {
608 if (callbackSpecs == null) {
609 callbackSpecs = new ArrayMap<>();
Svet Ganov2af57082015-07-30 08:44:20 -0700610 }
riddle_hsu40b300f2015-11-23 13:22:03 +0800611 final int callbackCount = callbacks.size();
612 for (int i = 0; i < callbackCount; i++) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800613 Callback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +0800614 ArraySet<String> changedPackages = callbackSpecs.get(callback);
615 if (changedPackages == null) {
616 changedPackages = new ArraySet<>();
617 callbackSpecs.put(callback, changedPackages);
618 }
619 changedPackages.add(uidPackageName);
620 }
Svet Ganov2af57082015-07-30 08:44:20 -0700621 }
622 }
623 }
624
625 if (callbackSpecs == null) {
626 return;
627 }
628
629 // There are components watching for mode changes such as window manager
630 // and location manager which are in our process. The callbacks in these
631 // components may require permissions our remote caller does not have.
632 final long identity = Binder.clearCallingIdentity();
633 try {
634 for (int i = 0; i < callbackSpecs.size(); i++) {
635 Callback callback = callbackSpecs.keyAt(i);
636 ArraySet<String> reportedPackageNames = callbackSpecs.valueAt(i);
637 try {
638 if (reportedPackageNames == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700639 callback.mCallback.opChanged(code, uid, null);
Svet Ganov2af57082015-07-30 08:44:20 -0700640 } else {
641 final int reportedPackageCount = reportedPackageNames.size();
642 for (int j = 0; j < reportedPackageCount; j++) {
643 String reportedPackageName = reportedPackageNames.valueAt(j);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700644 callback.mCallback.opChanged(code, uid, reportedPackageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700645 }
646 }
647 } catch (RemoteException e) {
648 Log.w(TAG, "Error dispatching op op change", e);
649 }
650 }
651 } finally {
652 Binder.restoreCallingIdentity(identity);
653 }
654 }
655
656 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800657 public void setMode(int code, int uid, String packageName, int mode) {
Dianne Hackbornb64afe12014-07-22 16:29:04 -0700658 if (Binder.getCallingPid() != Process.myPid()) {
659 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
660 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborn133b9df2014-07-01 13:06:10 -0700661 }
Dianne Hackborn961321f2013-02-05 17:22:41 -0800662 verifyIncomingOp(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800663 ArrayList<Callback> repCbs = null;
664 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800665 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700666 UidState uidState = getUidStateLocked(uid, false);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800667 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800668 if (op != null) {
669 if (op.mode != mode) {
670 op.mode = mode;
Dianne Hackborn68d76552017-02-27 15:32:03 -0800671 ArraySet<Callback> cbs = mOpModeWatchers.get(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800672 if (cbs != null) {
673 if (repCbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800674 repCbs = new ArrayList<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800675 }
676 repCbs.addAll(cbs);
677 }
678 cbs = mPackageModeWatchers.get(packageName);
679 if (cbs != null) {
680 if (repCbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800681 repCbs = new ArrayList<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800682 }
683 repCbs.addAll(cbs);
684 }
David Braunf5d83192013-09-16 13:43:51 -0700685 if (mode == AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800686 // If going into the default mode, prune this op
687 // if there is nothing else interesting in it.
Dianne Hackborn607b4142013-08-02 18:10:10 -0700688 pruneOp(op, uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800689 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800690 scheduleFastWriteLocked();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800691 }
692 }
693 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800694 if (repCbs != null) {
Svet Ganov38536112015-05-19 12:45:52 -0700695 // There are components watching for mode changes such as window manager
696 // and location manager which are in our process. The callbacks in these
697 // components may require permissions our remote caller does not have.
698 final long identity = Binder.clearCallingIdentity();
699 try {
700 for (int i = 0; i < repCbs.size(); i++) {
701 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700702 repCbs.get(i).mCallback.opChanged(code, uid, packageName);
Svet Ganov38536112015-05-19 12:45:52 -0700703 } catch (RemoteException e) {
704 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800705 }
Svet Ganov38536112015-05-19 12:45:52 -0700706 } finally {
707 Binder.restoreCallingIdentity(identity);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800708 }
709 }
710 }
711
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700712 private static HashMap<Callback, ArrayList<ChangeRec>> addCallbacks(
713 HashMap<Callback, ArrayList<ChangeRec>> callbacks,
Dianne Hackborn68d76552017-02-27 15:32:03 -0800714 int op, int uid, String packageName, ArraySet<Callback> cbs) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700715 if (cbs == null) {
716 return callbacks;
717 }
718 if (callbacks == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700719 callbacks = new HashMap<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700720 }
Svet Ganov2af57082015-07-30 08:44:20 -0700721 boolean duplicate = false;
Dianne Hackborn68d76552017-02-27 15:32:03 -0800722 final int N = cbs.size();
723 for (int i=0; i<N; i++) {
724 Callback cb = cbs.valueAt(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700725 ArrayList<ChangeRec> reports = callbacks.get(cb);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700726 if (reports == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700727 reports = new ArrayList<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700728 callbacks.put(cb, reports);
Svet Ganov2af57082015-07-30 08:44:20 -0700729 } else {
730 final int reportCount = reports.size();
731 for (int j = 0; j < reportCount; j++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700732 ChangeRec report = reports.get(j);
733 if (report.op == op && report.pkg.equals(packageName)) {
Svet Ganov2af57082015-07-30 08:44:20 -0700734 duplicate = true;
735 break;
736 }
737 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700738 }
Svet Ganov2af57082015-07-30 08:44:20 -0700739 if (!duplicate) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700740 reports.add(new ChangeRec(op, uid, packageName));
Svet Ganov2af57082015-07-30 08:44:20 -0700741 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700742 }
743 return callbacks;
744 }
745
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700746 static final class ChangeRec {
747 final int op;
748 final int uid;
749 final String pkg;
750
751 ChangeRec(int _op, int _uid, String _pkg) {
752 op = _op;
753 uid = _uid;
754 pkg = _pkg;
755 }
756 }
757
Dianne Hackborn607b4142013-08-02 18:10:10 -0700758 @Override
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800759 public void resetAllModes(int reqUserId, String reqPackageName) {
760 final int callingPid = Binder.getCallingPid();
761 final int callingUid = Binder.getCallingUid();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700762 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800763 callingPid, callingUid, null);
764 reqUserId = ActivityManager.handleIncomingUser(callingPid, callingUid, reqUserId,
765 true, true, "resetAllModes", null);
Svet Ganov2af57082015-07-30 08:44:20 -0700766
767 int reqUid = -1;
768 if (reqPackageName != null) {
769 try {
770 reqUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -0700771 reqPackageName, PackageManager.MATCH_UNINSTALLED_PACKAGES, reqUserId);
Svet Ganov2af57082015-07-30 08:44:20 -0700772 } catch (RemoteException e) {
773 /* ignore - local call */
774 }
775 }
776
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700777 HashMap<Callback, ArrayList<ChangeRec>> callbacks = null;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700778 synchronized (this) {
779 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700780 for (int i = mUidStates.size() - 1; i >= 0; i--) {
781 UidState uidState = mUidStates.valueAt(i);
782
783 SparseIntArray opModes = uidState.opModes;
784 if (opModes != null && (uidState.uid == reqUid || reqUid == -1)) {
785 final int uidOpCount = opModes.size();
786 for (int j = uidOpCount - 1; j >= 0; j--) {
787 final int code = opModes.keyAt(j);
788 if (AppOpsManager.opAllowsReset(code)) {
789 opModes.removeAt(j);
790 if (opModes.size() <= 0) {
791 uidState.opModes = null;
792 }
793 for (String packageName : getPackagesForUid(uidState.uid)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700794 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700795 mOpModeWatchers.get(code));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700796 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700797 mPackageModeWatchers.get(packageName));
798 }
799 }
800 }
801 }
802
803 if (uidState.pkgOps == null) {
804 continue;
805 }
806
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800807 if (reqUserId != UserHandle.USER_ALL
Svet Ganov2af57082015-07-30 08:44:20 -0700808 && reqUserId != UserHandle.getUserId(uidState.uid)) {
Alexandra Gherghinad6a98972014-08-04 17:05:34 +0100809 // Skip any ops for a different user
810 continue;
811 }
Svet Ganov2af57082015-07-30 08:44:20 -0700812
813 Map<String, Ops> packages = uidState.pkgOps;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700814 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
815 while (it.hasNext()) {
816 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700817 String packageName = ent.getKey();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800818 if (reqPackageName != null && !reqPackageName.equals(packageName)) {
819 // Skip any ops for a different package
820 continue;
821 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700822 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700823 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700824 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -0700825 if (AppOpsManager.opAllowsReset(curOp.op)
826 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -0700827 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700828 changed = true;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700829 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -0700830 mOpModeWatchers.get(curOp.op));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700831 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -0700832 mPackageModeWatchers.get(packageName));
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700833 if (curOp.time == 0 && curOp.rejectTime == 0) {
834 pkgOps.removeAt(j);
835 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700836 }
837 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700838 if (pkgOps.size() == 0) {
839 it.remove();
840 }
841 }
Svet Ganov2af57082015-07-30 08:44:20 -0700842 if (uidState.isDefault()) {
843 mUidStates.remove(uidState.uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700844 }
845 }
Svet Ganov2af57082015-07-30 08:44:20 -0700846
Dianne Hackborn607b4142013-08-02 18:10:10 -0700847 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800848 scheduleFastWriteLocked();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700849 }
850 }
851 if (callbacks != null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700852 for (Map.Entry<Callback, ArrayList<ChangeRec>> ent : callbacks.entrySet()) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700853 Callback cb = ent.getKey();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700854 ArrayList<ChangeRec> reports = ent.getValue();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700855 for (int i=0; i<reports.size(); i++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700856 ChangeRec rep = reports.get(i);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700857 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700858 cb.mCallback.opChanged(rep.op, rep.uid, rep.pkg);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700859 } catch (RemoteException e) {
860 }
861 }
862 }
863 }
864 }
865
Dianne Hackbornc2293022013-02-06 23:14:49 -0800866 @Override
867 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -0800868 if (callback == null) {
869 return;
870 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800871 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700872 op = (op != AppOpsManager.OP_NONE) ? AppOpsManager.opToSwitch(op) : op;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800873 Callback cb = mModeWatchers.get(callback.asBinder());
874 if (cb == null) {
875 cb = new Callback(callback);
876 mModeWatchers.put(callback.asBinder(), cb);
877 }
878 if (op != AppOpsManager.OP_NONE) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800879 ArraySet<Callback> cbs = mOpModeWatchers.get(op);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800880 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800881 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800882 mOpModeWatchers.put(op, cbs);
883 }
884 cbs.add(cb);
885 }
886 if (packageName != null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800887 ArraySet<Callback> cbs = mPackageModeWatchers.get(packageName);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800888 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800889 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800890 mPackageModeWatchers.put(packageName, cbs);
891 }
892 cbs.add(cb);
893 }
894 }
895 }
896
897 @Override
898 public void stopWatchingMode(IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -0800899 if (callback == null) {
900 return;
901 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800902 synchronized (this) {
903 Callback cb = mModeWatchers.remove(callback.asBinder());
904 if (cb != null) {
905 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700906 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800907 ArraySet<Callback> cbs = mOpModeWatchers.valueAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800908 cbs.remove(cb);
909 if (cbs.size() <= 0) {
910 mOpModeWatchers.removeAt(i);
911 }
912 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700913 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800914 ArraySet<Callback> cbs = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700915 cbs.remove(cb);
916 if (cbs.size() <= 0) {
917 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800918 }
919 }
920 }
921 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800922 }
923
924 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700925 public IBinder getToken(IBinder clientToken) {
926 synchronized (this) {
927 ClientState cs = mClients.get(clientToken);
928 if (cs == null) {
929 cs = new ClientState(clientToken);
930 mClients.put(clientToken, cs);
931 }
932 return cs;
933 }
934 }
935
936 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800937 public int checkOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800938 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800939 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000940 String resolvedPackageName = resolvePackageName(uid, packageName);
941 if (resolvedPackageName == null) {
942 return AppOpsManager.MODE_IGNORED;
943 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800944 synchronized (this) {
Svet Ganov442ed572016-08-17 17:29:43 -0700945 if (isOpRestrictedLocked(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -0400946 return AppOpsManager.MODE_IGNORED;
947 }
Svet Ganov2af57082015-07-30 08:44:20 -0700948 code = AppOpsManager.opToSwitch(code);
949 UidState uidState = getUidStateLocked(uid, false);
Svet Ganovee438d42017-01-19 18:04:38 -0800950 if (uidState != null && uidState.opModes != null
951 && uidState.opModes.indexOfKey(code) >= 0) {
952 return uidState.opModes.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -0700953 }
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000954 Op op = getOpLocked(code, uid, resolvedPackageName, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800955 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -0700956 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800957 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800958 return op.mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800959 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800960 }
961
962 @Override
John Spurlock7b414672014-07-18 13:02:39 -0400963 public int checkAudioOperation(int code, int usage, int uid, String packageName) {
Andrei Stingaceanuefc4a342016-03-22 14:43:01 +0000964 boolean suspended;
965 try {
966 suspended = isPackageSuspendedForUser(packageName, uid);
967 } catch (IllegalArgumentException ex) {
968 // Package not found.
969 suspended = false;
970 }
971
972 if (suspended) {
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000973 Log.i(TAG, "Audio disabled for suspended package=" + packageName + " for uid=" + uid);
974 return AppOpsManager.MODE_IGNORED;
975 }
976
John Spurlock1af30c72014-03-10 08:33:35 -0400977 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -0400978 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -0400979 if (mode != AppOpsManager.MODE_ALLOWED) {
980 return mode;
981 }
982 }
983 return checkOperation(code, uid, packageName);
984 }
985
Andrei Stingaceanu355b2322016-02-12 16:43:51 +0000986 private boolean isPackageSuspendedForUser(String pkg, int uid) {
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000987 try {
Andrei Stingaceanu355b2322016-02-12 16:43:51 +0000988 return AppGlobals.getPackageManager().isPackageSuspendedForUser(
989 pkg, UserHandle.getUserId(uid));
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000990 } catch (RemoteException re) {
991 throw new SecurityException("Could not talk to package manager service");
992 }
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000993 }
994
John Spurlock7b414672014-07-18 13:02:39 -0400995 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
996 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
997 if (usageRestrictions != null) {
998 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -0400999 if (r != null && !r.exceptionPackages.contains(packageName)) {
1000 return r.mode;
1001 }
1002 }
1003 return AppOpsManager.MODE_ALLOWED;
1004 }
1005
1006 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001007 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -04001008 String[] exceptionPackages) {
1009 verifyIncomingUid(uid);
1010 verifyIncomingOp(code);
1011 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001012 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1013 if (usageRestrictions == null) {
1014 usageRestrictions = new SparseArray<Restriction>();
1015 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -04001016 }
John Spurlock7b414672014-07-18 13:02:39 -04001017 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001018 if (mode != AppOpsManager.MODE_ALLOWED) {
1019 final Restriction r = new Restriction();
1020 r.mode = mode;
1021 if (exceptionPackages != null) {
1022 final int N = exceptionPackages.length;
1023 r.exceptionPackages = new ArraySet<String>(N);
1024 for (int i = 0; i < N; i++) {
1025 final String pkg = exceptionPackages[i];
1026 if (pkg != null) {
1027 r.exceptionPackages.add(pkg.trim());
1028 }
1029 }
1030 }
John Spurlock7b414672014-07-18 13:02:39 -04001031 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -04001032 }
1033 }
Julia Reynoldsbb21c252016-04-05 16:01:49 -04001034 notifyWatchersOfChange(code);
John Spurlock1af30c72014-03-10 08:33:35 -04001035 }
1036
1037 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001038 public int checkPackage(int uid, String packageName) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001039 Preconditions.checkNotNull(packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001040 synchronized (this) {
Dianne Hackborn0fcef842014-09-12 15:38:33 -07001041 if (getOpsRawLocked(uid, packageName, true) != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001042 return AppOpsManager.MODE_ALLOWED;
1043 } else {
1044 return AppOpsManager.MODE_ERRORED;
1045 }
1046 }
1047 }
1048
1049 @Override
Svet Ganov99b60432015-06-27 13:15:22 -07001050 public int noteProxyOperation(int code, String proxyPackageName,
1051 int proxiedUid, String proxiedPackageName) {
1052 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001053 final int proxyUid = Binder.getCallingUid();
1054 String resolveProxyPackageName = resolvePackageName(proxyUid, proxyPackageName);
1055 if (resolveProxyPackageName == null) {
1056 return AppOpsManager.MODE_IGNORED;
1057 }
1058 final int proxyMode = noteOperationUnchecked(code, proxyUid,
1059 resolveProxyPackageName, -1, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001060 if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
1061 return proxyMode;
1062 }
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001063 String resolveProxiedPackageName = resolvePackageName(proxiedUid, proxiedPackageName);
1064 if (resolveProxiedPackageName == null) {
1065 return AppOpsManager.MODE_IGNORED;
1066 }
1067 return noteOperationUnchecked(code, proxiedUid, resolveProxiedPackageName,
1068 proxyMode, resolveProxyPackageName);
Svet Ganov99b60432015-06-27 13:15:22 -07001069 }
1070
1071 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001072 public int noteOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001073 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001074 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001075 String resolvedPackageName = resolvePackageName(uid, packageName);
1076 if (resolvedPackageName == null) {
1077 return AppOpsManager.MODE_IGNORED;
1078 }
1079 return noteOperationUnchecked(code, uid, resolvedPackageName, 0, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001080 }
1081
1082 private int noteOperationUnchecked(int code, int uid, String packageName,
1083 int proxyUid, String proxyPackageName) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001084 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001085 Ops ops = getOpsRawLocked(uid, packageName, true);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001086 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001087 if (DEBUG) Log.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
1088 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001089 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001090 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001091 Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07001092 if (isOpRestrictedLocked(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001093 return AppOpsManager.MODE_IGNORED;
1094 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001095 if (op.duration == -1) {
1096 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
1097 + " code " + code + " time=" + op.time + " duration=" + op.duration);
1098 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001099 op.duration = 0;
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001100 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001101 UidState uidState = ops.uidState;
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001102 // If there is a non-default per UID policy (we set UID op mode only if
1103 // non-default) it takes over, otherwise use the per package policy.
1104 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -07001105 final int uidMode = uidState.opModes.get(switchCode);
1106 if (uidMode != AppOpsManager.MODE_ALLOWED) {
1107 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1108 + switchCode + " (" + code + ") uid " + uid + " package "
1109 + packageName);
1110 op.rejectTime = System.currentTimeMillis();
1111 return uidMode;
1112 }
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001113 } else {
1114 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
1115 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
1116 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1117 + switchCode + " (" + code + ") uid " + uid + " package "
1118 + packageName);
1119 op.rejectTime = System.currentTimeMillis();
1120 return switchOp.mode;
1121 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001122 }
1123 if (DEBUG) Log.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
1124 + " package " + packageName);
1125 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001126 op.rejectTime = 0;
Svet Ganov99b60432015-06-27 13:15:22 -07001127 op.proxyUid = proxyUid;
1128 op.proxyPackageName = proxyPackageName;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001129 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001130 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001131 }
1132
1133 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001134 public int startOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001135 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001136 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001137 String resolvedPackageName = resolvePackageName(uid, packageName);
1138 if (resolvedPackageName == null) {
1139 return AppOpsManager.MODE_IGNORED;
1140 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001141 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001142 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001143 Ops ops = getOpsRawLocked(uid, resolvedPackageName, true);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001144 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001145 if (DEBUG) Log.d(TAG, "startOperation: no op for code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001146 + " package " + resolvedPackageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001147 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001148 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001149 Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07001150 if (isOpRestrictedLocked(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001151 return AppOpsManager.MODE_IGNORED;
1152 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001153 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001154 UidState uidState = ops.uidState;
1155 if (uidState.opModes != null) {
1156 final int uidMode = uidState.opModes.get(switchCode);
1157 if (uidMode != AppOpsManager.MODE_ALLOWED) {
1158 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1159 + switchCode + " (" + code + ") uid " + uid + " package "
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001160 + resolvedPackageName);
Svet Ganov2af57082015-07-30 08:44:20 -07001161 op.rejectTime = System.currentTimeMillis();
1162 return uidMode;
1163 }
1164 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001165 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
1166 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
1167 if (DEBUG) Log.d(TAG, "startOperation: reject #" + op.mode + " for code "
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001168 + switchCode + " (" + code + ") uid " + uid + " package "
1169 + resolvedPackageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001170 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001171 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001172 }
1173 if (DEBUG) Log.d(TAG, "startOperation: allowing code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001174 + " package " + resolvedPackageName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001175 if (op.nesting == 0) {
1176 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001177 op.rejectTime = 0;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001178 op.duration = -1;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001179 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001180 op.nesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001181 if (client.mStartedOps != null) {
1182 client.mStartedOps.add(op);
1183 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001184 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001185 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001186 }
1187
1188 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001189 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001190 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001191 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001192 String resolvedPackageName = resolvePackageName(uid, packageName);
1193 if (resolvedPackageName == null) {
1194 return;
1195 }
1196 if (!(token instanceof ClientState)) {
1197 return;
1198 }
1199 ClientState client = (ClientState) token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001200 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001201 Op op = getOpLocked(code, uid, resolvedPackageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001202 if (op == null) {
1203 return;
1204 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001205 if (client.mStartedOps != null) {
1206 if (!client.mStartedOps.remove(op)) {
1207 throw new IllegalStateException("Operation not started: uid" + op.uid
1208 + " pkg=" + op.packageName + " op=" + op.op);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001209 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001210 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001211 finishOperationLocked(op);
1212 }
1213 }
1214
Svet Ganovb9d71a62015-04-30 10:38:13 -07001215 @Override
1216 public int permissionToOpCode(String permission) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001217 if (permission == null) {
1218 return AppOpsManager.OP_NONE;
1219 }
Svet Ganovb9d71a62015-04-30 10:38:13 -07001220 return AppOpsManager.permissionToOpCode(permission);
1221 }
1222
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001223 void finishOperationLocked(Op op) {
1224 if (op.nesting <= 1) {
1225 if (op.nesting == 1) {
1226 op.duration = (int)(System.currentTimeMillis() - op.time);
1227 op.time += op.duration;
1228 } else {
1229 Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
1230 + op.packageName + " code " + op.op + " time=" + op.time
1231 + " duration=" + op.duration + " nesting=" + op.nesting);
1232 }
1233 op.nesting = 0;
1234 } else {
1235 op.nesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001236 }
1237 }
1238
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001239 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001240 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001241 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001242 }
1243 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001244 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001245 }
1246 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
1247 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001248 }
1249
Dianne Hackborn961321f2013-02-05 17:22:41 -08001250 private void verifyIncomingOp(int op) {
1251 if (op >= 0 && op < AppOpsManager._NUM_OP) {
1252 return;
1253 }
1254 throw new IllegalArgumentException("Bad operation #" + op);
1255 }
1256
Svet Ganov2af57082015-07-30 08:44:20 -07001257 private UidState getUidStateLocked(int uid, boolean edit) {
1258 UidState uidState = mUidStates.get(uid);
1259 if (uidState == null) {
1260 if (!edit) {
1261 return null;
1262 }
1263 uidState = new UidState(uid);
1264 mUidStates.put(uid, uidState);
1265 }
1266 return uidState;
1267 }
1268
Dianne Hackborn0fcef842014-09-12 15:38:33 -07001269 private Ops getOpsRawLocked(int uid, String packageName, boolean edit) {
Svet Ganov2af57082015-07-30 08:44:20 -07001270 UidState uidState = getUidStateLocked(uid, edit);
1271 if (uidState == null) {
1272 return null;
1273 }
1274
1275 if (uidState.pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001276 if (!edit) {
1277 return null;
1278 }
Svet Ganov2af57082015-07-30 08:44:20 -07001279 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001280 }
Svet Ganov2af57082015-07-30 08:44:20 -07001281
1282 Ops ops = uidState.pkgOps.get(packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001283 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001284 if (!edit) {
1285 return null;
1286 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001287 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001288 // This is the first time we have seen this package name under this uid,
1289 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -08001290 if (uid != 0) {
1291 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001292 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001293 int pkgUid = -1;
1294 try {
Jason Monk1c7c3192014-06-26 12:52:18 -04001295 ApplicationInfo appInfo = ActivityThread.getPackageManager()
Jeff Sharkeycd654482016-01-08 17:42:11 -07001296 .getApplicationInfo(packageName,
1297 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1298 UserHandle.getUserId(uid));
Jason Monk1c7c3192014-06-26 12:52:18 -04001299 if (appInfo != null) {
1300 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001301 isPrivileged = (appInfo.privateFlags
1302 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001303 } else {
1304 if ("media".equals(packageName)) {
1305 pkgUid = Process.MEDIA_UID;
1306 isPrivileged = false;
Andy Hunged0ea402015-10-30 14:11:46 -07001307 } else if ("audioserver".equals(packageName)) {
1308 pkgUid = Process.AUDIOSERVER_UID;
1309 isPrivileged = false;
Chien-Yu Chen75cade02016-01-11 10:56:21 -08001310 } else if ("cameraserver".equals(packageName)) {
1311 pkgUid = Process.CAMERASERVER_UID;
1312 isPrivileged = false;
Jason Monk1c7c3192014-06-26 12:52:18 -04001313 }
Dianne Hackborn713df152013-05-17 11:27:57 -07001314 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001315 } catch (RemoteException e) {
1316 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001317 }
1318 if (pkgUid != uid) {
1319 // Oops! The package name is not valid for the uid they are calling
1320 // under. Abort.
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001321 RuntimeException ex = new RuntimeException("here");
1322 ex.fillInStackTrace();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001323 Slog.w(TAG, "Bad call: specified package " + packageName
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001324 + " under uid " + uid + " but it is really " + pkgUid, ex);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001325 return null;
1326 }
1327 } finally {
1328 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001329 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001330 }
Svet Ganov2af57082015-07-30 08:44:20 -07001331 ops = new Ops(packageName, uidState, isPrivileged);
1332 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001333 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08001334 return ops;
1335 }
1336
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001337 private void scheduleWriteLocked() {
1338 if (!mWriteScheduled) {
1339 mWriteScheduled = true;
1340 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
1341 }
1342 }
1343
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001344 private void scheduleFastWriteLocked() {
1345 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001346 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001347 mFastWriteScheduled = true;
1348 mHandler.removeCallbacks(mWriteRunner);
1349 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001350 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001351 }
1352
Dianne Hackborn72e39832013-01-18 18:36:09 -08001353 private Op getOpLocked(int code, int uid, String packageName, boolean edit) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001354 Ops ops = getOpsRawLocked(uid, packageName, edit);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001355 if (ops == null) {
1356 return null;
1357 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001358 return getOpLocked(ops, code, edit);
1359 }
1360
1361 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001362 Op op = ops.get(code);
1363 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001364 if (!edit) {
1365 return null;
1366 }
Svet Ganov2af57082015-07-30 08:44:20 -07001367 op = new Op(ops.uidState.uid, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001368 ops.put(code, op);
1369 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001370 if (edit) {
1371 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001372 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001373 return op;
1374 }
1375
Svet Ganov442ed572016-08-17 17:29:43 -07001376 private boolean isOpRestrictedLocked(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04001377 int userHandle = UserHandle.getUserId(uid);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001378 final int restrictionSetCount = mOpUserRestrictions.size();
Ruben Brunk29931bc2016-03-11 00:24:26 -08001379
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001380 for (int i = 0; i < restrictionSetCount; i++) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08001381 // For each client, check that the given op is not restricted, or that the given
1382 // package is exempt from the restriction.
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07001383 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07001384 if (restrictionState.hasRestriction(code, packageName, userHandle)) {
1385 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
1386 // If we are the system, bypass user restrictions for certain codes
1387 synchronized (this) {
1388 Ops ops = getOpsRawLocked(uid, packageName, true);
1389 if ((ops != null) && ops.isPrivileged) {
1390 return false;
1391 }
Ruben Brunk32f0fa42016-03-11 19:07:07 -08001392 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08001393 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001394 return true;
Jason Monk1c7c3192014-06-26 12:52:18 -04001395 }
Jason Monk62062992014-05-06 09:55:28 -04001396 }
1397 return false;
1398 }
1399
Dianne Hackborn35654b62013-01-14 17:38:02 -08001400 void readState() {
1401 synchronized (mFile) {
1402 synchronized (this) {
1403 FileInputStream stream;
1404 try {
1405 stream = mFile.openRead();
1406 } catch (FileNotFoundException e) {
1407 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
1408 return;
1409 }
1410 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001411 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001412 try {
1413 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001414 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001415 int type;
1416 while ((type = parser.next()) != XmlPullParser.START_TAG
1417 && type != XmlPullParser.END_DOCUMENT) {
1418 ;
1419 }
1420
1421 if (type != XmlPullParser.START_TAG) {
1422 throw new IllegalStateException("no start tag found");
1423 }
1424
1425 int outerDepth = parser.getDepth();
1426 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1427 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1428 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1429 continue;
1430 }
1431
1432 String tagName = parser.getName();
1433 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001434 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07001435 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07001436 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001437 } else {
1438 Slog.w(TAG, "Unknown element under <app-ops>: "
1439 + parser.getName());
1440 XmlUtils.skipCurrentTag(parser);
1441 }
1442 }
1443 success = true;
1444 } catch (IllegalStateException e) {
1445 Slog.w(TAG, "Failed parsing " + e);
1446 } catch (NullPointerException e) {
1447 Slog.w(TAG, "Failed parsing " + e);
1448 } catch (NumberFormatException e) {
1449 Slog.w(TAG, "Failed parsing " + e);
1450 } catch (XmlPullParserException e) {
1451 Slog.w(TAG, "Failed parsing " + e);
1452 } catch (IOException e) {
1453 Slog.w(TAG, "Failed parsing " + e);
1454 } catch (IndexOutOfBoundsException e) {
1455 Slog.w(TAG, "Failed parsing " + e);
1456 } finally {
1457 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07001458 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001459 }
1460 try {
1461 stream.close();
1462 } catch (IOException e) {
1463 }
1464 }
1465 }
1466 }
1467 }
1468
Svet Ganov2af57082015-07-30 08:44:20 -07001469 void readUidOps(XmlPullParser parser) throws NumberFormatException,
1470 XmlPullParserException, IOException {
1471 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
1472 int outerDepth = parser.getDepth();
1473 int type;
1474 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1475 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1476 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1477 continue;
1478 }
1479
1480 String tagName = parser.getName();
1481 if (tagName.equals("op")) {
1482 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
1483 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
1484 UidState uidState = getUidStateLocked(uid, true);
1485 if (uidState.opModes == null) {
1486 uidState.opModes = new SparseIntArray();
1487 }
1488 uidState.opModes.put(code, mode);
1489 } else {
1490 Slog.w(TAG, "Unknown element under <uid-ops>: "
1491 + parser.getName());
1492 XmlUtils.skipCurrentTag(parser);
1493 }
1494 }
1495 }
1496
Dave Burke0997c5bd2013-08-02 20:25:02 +00001497 void readPackage(XmlPullParser parser) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001498 XmlPullParserException, IOException {
1499 String pkgName = parser.getAttributeValue(null, "n");
1500 int outerDepth = parser.getDepth();
1501 int type;
1502 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1503 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1504 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1505 continue;
1506 }
1507
1508 String tagName = parser.getName();
1509 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001510 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001511 } else {
1512 Slog.w(TAG, "Unknown element under <pkg>: "
1513 + parser.getName());
1514 XmlUtils.skipCurrentTag(parser);
1515 }
1516 }
1517 }
1518
Dave Burke0997c5bd2013-08-02 20:25:02 +00001519 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001520 XmlPullParserException, IOException {
1521 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Jason Monk1c7c3192014-06-26 12:52:18 -04001522 String isPrivilegedString = parser.getAttributeValue(null, "p");
1523 boolean isPrivileged = false;
1524 if (isPrivilegedString == null) {
1525 try {
1526 IPackageManager packageManager = ActivityThread.getPackageManager();
1527 if (packageManager != null) {
1528 ApplicationInfo appInfo = ActivityThread.getPackageManager()
1529 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
1530 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001531 isPrivileged = (appInfo.privateFlags
1532 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001533 }
1534 } else {
1535 // Could not load data, don't add to cache so it will be loaded later.
1536 return;
1537 }
1538 } catch (RemoteException e) {
1539 Slog.w(TAG, "Could not contact PackageManager", e);
1540 }
1541 } else {
1542 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
1543 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001544 int outerDepth = parser.getDepth();
1545 int type;
1546 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1547 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1548 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1549 continue;
1550 }
1551
1552 String tagName = parser.getName();
1553 if (tagName.equals("op")) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001554 Op op = new Op(uid, pkgName, Integer.parseInt(parser.getAttributeValue(null, "n")));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001555 String mode = parser.getAttributeValue(null, "m");
1556 if (mode != null) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001557 op.mode = Integer.parseInt(mode);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001558 }
1559 String time = parser.getAttributeValue(null, "t");
1560 if (time != null) {
1561 op.time = Long.parseLong(time);
1562 }
1563 time = parser.getAttributeValue(null, "r");
1564 if (time != null) {
1565 op.rejectTime = Long.parseLong(time);
1566 }
1567 String dur = parser.getAttributeValue(null, "d");
1568 if (dur != null) {
1569 op.duration = Integer.parseInt(dur);
1570 }
Svet Ganov99b60432015-06-27 13:15:22 -07001571 String proxyUid = parser.getAttributeValue(null, "pu");
1572 if (proxyUid != null) {
1573 op.proxyUid = Integer.parseInt(proxyUid);
1574 }
1575 String proxyPackageName = parser.getAttributeValue(null, "pp");
1576 if (proxyPackageName != null) {
1577 op.proxyPackageName = proxyPackageName;
1578 }
Svet Ganov2af57082015-07-30 08:44:20 -07001579
1580 UidState uidState = getUidStateLocked(uid, true);
1581 if (uidState.pkgOps == null) {
1582 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001583 }
Svet Ganov2af57082015-07-30 08:44:20 -07001584
1585 Ops ops = uidState.pkgOps.get(pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001586 if (ops == null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001587 ops = new Ops(pkgName, uidState, isPrivileged);
1588 uidState.pkgOps.put(pkgName, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001589 }
1590 ops.put(op.op, op);
1591 } else {
1592 Slog.w(TAG, "Unknown element under <pkg>: "
1593 + parser.getName());
1594 XmlUtils.skipCurrentTag(parser);
1595 }
1596 }
1597 }
1598
1599 void writeState() {
1600 synchronized (mFile) {
1601 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
1602
1603 FileOutputStream stream;
1604 try {
1605 stream = mFile.startWrite();
1606 } catch (IOException e) {
1607 Slog.w(TAG, "Failed to write state: " + e);
1608 return;
1609 }
1610
1611 try {
1612 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001613 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001614 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001615 out.startTag(null, "app-ops");
Svet Ganov2af57082015-07-30 08:44:20 -07001616
1617 final int uidStateCount = mUidStates.size();
1618 for (int i = 0; i < uidStateCount; i++) {
1619 UidState uidState = mUidStates.valueAt(i);
1620 if (uidState.opModes != null && uidState.opModes.size() > 0) {
1621 out.startTag(null, "uid");
1622 out.attribute(null, "n", Integer.toString(uidState.uid));
1623 SparseIntArray uidOpModes = uidState.opModes;
1624 final int opCount = uidOpModes.size();
1625 for (int j = 0; j < opCount; j++) {
1626 final int op = uidOpModes.keyAt(j);
1627 final int mode = uidOpModes.valueAt(j);
1628 out.startTag(null, "op");
1629 out.attribute(null, "n", Integer.toString(op));
1630 out.attribute(null, "m", Integer.toString(mode));
1631 out.endTag(null, "op");
1632 }
1633 out.endTag(null, "uid");
1634 }
1635 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001636
1637 if (allOps != null) {
1638 String lastPkg = null;
1639 for (int i=0; i<allOps.size(); i++) {
1640 AppOpsManager.PackageOps pkg = allOps.get(i);
1641 if (!pkg.getPackageName().equals(lastPkg)) {
1642 if (lastPkg != null) {
1643 out.endTag(null, "pkg");
1644 }
1645 lastPkg = pkg.getPackageName();
1646 out.startTag(null, "pkg");
1647 out.attribute(null, "n", lastPkg);
1648 }
1649 out.startTag(null, "uid");
1650 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04001651 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001652 Ops ops = getOpsRawLocked(pkg.getUid(), pkg.getPackageName(), false);
Jason Monk1c7c3192014-06-26 12:52:18 -04001653 // Should always be present as the list of PackageOps is generated
1654 // from Ops.
1655 if (ops != null) {
1656 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
1657 } else {
1658 out.attribute(null, "p", Boolean.toString(false));
1659 }
1660 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001661 List<AppOpsManager.OpEntry> ops = pkg.getOps();
1662 for (int j=0; j<ops.size(); j++) {
1663 AppOpsManager.OpEntry op = ops.get(j);
1664 out.startTag(null, "op");
1665 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07001666 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001667 out.attribute(null, "m", Integer.toString(op.getMode()));
1668 }
1669 long time = op.getTime();
1670 if (time != 0) {
1671 out.attribute(null, "t", Long.toString(time));
1672 }
1673 time = op.getRejectTime();
1674 if (time != 0) {
1675 out.attribute(null, "r", Long.toString(time));
1676 }
1677 int dur = op.getDuration();
1678 if (dur != 0) {
1679 out.attribute(null, "d", Integer.toString(dur));
1680 }
Svet Ganov99b60432015-06-27 13:15:22 -07001681 int proxyUid = op.getProxyUid();
1682 if (proxyUid != -1) {
1683 out.attribute(null, "pu", Integer.toString(proxyUid));
1684 }
1685 String proxyPackageName = op.getProxyPackageName();
1686 if (proxyPackageName != null) {
1687 out.attribute(null, "pp", proxyPackageName);
1688 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001689 out.endTag(null, "op");
1690 }
1691 out.endTag(null, "uid");
1692 }
1693 if (lastPkg != null) {
1694 out.endTag(null, "pkg");
1695 }
1696 }
1697
1698 out.endTag(null, "app-ops");
1699 out.endDocument();
1700 mFile.finishWrite(stream);
1701 } catch (IOException e) {
1702 Slog.w(TAG, "Failed to write state, restoring backup.", e);
1703 mFile.failWrite(stream);
1704 }
1705 }
1706 }
1707
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001708 static class Shell extends ShellCommand {
1709 final IAppOpsService mInterface;
1710 final AppOpsService mInternal;
1711
1712 int userId = UserHandle.USER_SYSTEM;
1713 String packageName;
1714 String opStr;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001715 String modeStr;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001716 int op;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001717 int mode;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001718 int packageUid;
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001719 int nonpackageUid;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001720
1721 Shell(IAppOpsService iface, AppOpsService internal) {
1722 mInterface = iface;
1723 mInternal = internal;
1724 }
1725
1726 @Override
1727 public int onCommand(String cmd) {
1728 return onShellCommand(this, cmd);
1729 }
1730
1731 @Override
1732 public void onHelp() {
1733 PrintWriter pw = getOutPrintWriter();
1734 dumpCommandHelp(pw);
1735 }
1736
1737 private int strOpToOp(String op, PrintWriter err) {
1738 try {
1739 return AppOpsManager.strOpToOp(op);
1740 } catch (IllegalArgumentException e) {
1741 }
1742 try {
1743 return Integer.parseInt(op);
1744 } catch (NumberFormatException e) {
1745 }
1746 try {
1747 return AppOpsManager.strDebugOpToOp(op);
1748 } catch (IllegalArgumentException e) {
1749 err.println("Error: " + e.getMessage());
1750 return -1;
1751 }
1752 }
1753
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001754 int strModeToMode(String modeStr, PrintWriter err) {
1755 switch (modeStr) {
1756 case "allow":
1757 return AppOpsManager.MODE_ALLOWED;
1758 case "deny":
1759 return AppOpsManager.MODE_ERRORED;
1760 case "ignore":
1761 return AppOpsManager.MODE_IGNORED;
1762 case "default":
1763 return AppOpsManager.MODE_DEFAULT;
1764 }
1765 try {
1766 return Integer.parseInt(modeStr);
1767 } catch (NumberFormatException e) {
1768 }
1769 err.println("Error: Mode " + modeStr + " is not valid");
1770 return -1;
1771 }
1772
1773 int parseUserOpMode(int defMode, PrintWriter err) throws RemoteException {
1774 userId = UserHandle.USER_CURRENT;
1775 opStr = null;
1776 modeStr = null;
1777 for (String argument; (argument = getNextArg()) != null;) {
1778 if ("--user".equals(argument)) {
1779 userId = UserHandle.parseUserArg(getNextArgRequired());
1780 } else {
1781 if (opStr == null) {
1782 opStr = argument;
1783 } else if (modeStr == null) {
1784 modeStr = argument;
1785 break;
1786 }
1787 }
1788 }
1789 if (opStr == null) {
1790 err.println("Error: Operation not specified.");
1791 return -1;
1792 }
1793 op = strOpToOp(opStr, err);
1794 if (op < 0) {
1795 return -1;
1796 }
1797 if (modeStr != null) {
1798 if ((mode=strModeToMode(modeStr, err)) < 0) {
1799 return -1;
1800 }
1801 } else {
1802 mode = defMode;
1803 }
1804 return 0;
1805 }
1806
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001807 int parseUserPackageOp(boolean reqOp, PrintWriter err) throws RemoteException {
1808 userId = UserHandle.USER_CURRENT;
1809 packageName = null;
1810 opStr = null;
1811 for (String argument; (argument = getNextArg()) != null;) {
1812 if ("--user".equals(argument)) {
1813 userId = UserHandle.parseUserArg(getNextArgRequired());
1814 } else {
1815 if (packageName == null) {
1816 packageName = argument;
1817 } else if (opStr == null) {
1818 opStr = argument;
1819 break;
1820 }
1821 }
1822 }
1823 if (packageName == null) {
1824 err.println("Error: Package name not specified.");
1825 return -1;
1826 } else if (opStr == null && reqOp) {
1827 err.println("Error: Operation not specified.");
1828 return -1;
1829 }
1830 if (opStr != null) {
1831 op = strOpToOp(opStr, err);
1832 if (op < 0) {
1833 return -1;
1834 }
1835 } else {
1836 op = AppOpsManager.OP_NONE;
1837 }
1838 if (userId == UserHandle.USER_CURRENT) {
1839 userId = ActivityManager.getCurrentUser();
1840 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001841 nonpackageUid = -1;
1842 try {
1843 nonpackageUid = Integer.parseInt(packageName);
1844 } catch (NumberFormatException e) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001845 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001846 if (nonpackageUid == -1 && packageName.length() > 1 && packageName.charAt(0) == 'u'
1847 && packageName.indexOf('.') < 0) {
1848 int i = 1;
1849 while (i < packageName.length() && packageName.charAt(i) >= '0'
1850 && packageName.charAt(i) <= '9') {
1851 i++;
1852 }
1853 if (i > 1 && i < packageName.length()) {
1854 String userStr = packageName.substring(1, i);
1855 try {
1856 int user = Integer.parseInt(userStr);
1857 char type = packageName.charAt(i);
1858 i++;
1859 int startTypeVal = i;
1860 while (i < packageName.length() && packageName.charAt(i) >= '0'
1861 && packageName.charAt(i) <= '9') {
1862 i++;
1863 }
1864 if (i > startTypeVal) {
1865 String typeValStr = packageName.substring(startTypeVal, i);
1866 try {
1867 int typeVal = Integer.parseInt(typeValStr);
1868 if (type == 'a') {
1869 nonpackageUid = UserHandle.getUid(user,
1870 typeVal + Process.FIRST_APPLICATION_UID);
1871 } else if (type == 's') {
1872 nonpackageUid = UserHandle.getUid(user, typeVal);
1873 }
1874 } catch (NumberFormatException e) {
1875 }
1876 }
1877 } catch (NumberFormatException e) {
1878 }
1879 }
1880 }
1881 if (nonpackageUid != -1) {
1882 packageName = null;
1883 } else {
1884 if ("root".equals(packageName)) {
1885 packageUid = 0;
1886 } else {
1887 packageUid = AppGlobals.getPackageManager().getPackageUid(packageName,
1888 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
1889 }
1890 if (packageUid < 0) {
1891 err.println("Error: No UID for " + packageName + " in user " + userId);
1892 return -1;
1893 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001894 }
1895 return 0;
1896 }
1897 }
1898
1899 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07001900 FileDescriptor err, String[] args, ShellCallback callback,
1901 ResultReceiver resultReceiver) {
1902 (new Shell(this, this)).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001903 }
1904
1905 static void dumpCommandHelp(PrintWriter pw) {
1906 pw.println("AppOps service (appops) commands:");
1907 pw.println(" help");
1908 pw.println(" Print this help text.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001909 pw.println(" set [--user <USER_ID>] <PACKAGE | UID> <OP> <MODE>");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001910 pw.println(" Set the mode for a particular application and operation.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001911 pw.println(" get [--user <USER_ID>] <PACKAGE | UID> [<OP>]");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001912 pw.println(" Return the mode for a particular application and optional operation.");
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001913 pw.println(" query-op [--user <USER_ID>] <OP> [<MODE>]");
1914 pw.println(" Print all packages that currently have the given op in the given mode.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001915 pw.println(" reset [--user <USER_ID>] [<PACKAGE>]");
1916 pw.println(" Reset the given application or all applications to default modes.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001917 pw.println(" write-settings");
1918 pw.println(" Immediately write pending changes to storage.");
1919 pw.println(" read-settings");
1920 pw.println(" Read the last written settings, replacing current state in RAM.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001921 pw.println(" options:");
1922 pw.println(" <PACKAGE> an Android package name.");
1923 pw.println(" <OP> an AppOps operation.");
1924 pw.println(" <MODE> one of allow, ignore, deny, or default");
1925 pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
1926 pw.println(" specified, the current user is assumed.");
1927 }
1928
1929 static int onShellCommand(Shell shell, String cmd) {
1930 if (cmd == null) {
1931 return shell.handleDefaultCommands(cmd);
1932 }
1933 PrintWriter pw = shell.getOutPrintWriter();
1934 PrintWriter err = shell.getErrPrintWriter();
1935 try {
1936 switch (cmd) {
1937 case "set": {
1938 int res = shell.parseUserPackageOp(true, err);
1939 if (res < 0) {
1940 return res;
1941 }
1942 String modeStr = shell.getNextArg();
1943 if (modeStr == null) {
1944 err.println("Error: Mode not specified.");
1945 return -1;
1946 }
1947
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001948 final int mode = shell.strModeToMode(modeStr, err);
1949 if (mode < 0) {
1950 return -1;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001951 }
1952
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001953 if (shell.packageName != null) {
1954 shell.mInterface.setMode(shell.op, shell.packageUid, shell.packageName,
1955 mode);
1956 } else {
1957 shell.mInterface.setUidMode(shell.op, shell.nonpackageUid, mode);
1958 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001959 return 0;
1960 }
1961 case "get": {
1962 int res = shell.parseUserPackageOp(false, err);
1963 if (res < 0) {
1964 return res;
1965 }
1966
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001967 List<AppOpsManager.PackageOps> ops;
1968 if (shell.packageName != null) {
1969 ops = shell.mInterface.getOpsForPackage(
1970 shell.packageUid, shell.packageName,
1971 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
1972 } else {
1973 ops = shell.mInterface.getUidOps(
1974 shell.nonpackageUid,
1975 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
1976 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001977 if (ops == null || ops.size() <= 0) {
1978 pw.println("No operations.");
1979 return 0;
1980 }
1981 final long now = System.currentTimeMillis();
1982 for (int i=0; i<ops.size(); i++) {
1983 List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
1984 for (int j=0; j<entries.size(); j++) {
1985 AppOpsManager.OpEntry ent = entries.get(j);
1986 pw.print(AppOpsManager.opToName(ent.getOp()));
1987 pw.print(": ");
1988 switch (ent.getMode()) {
1989 case AppOpsManager.MODE_ALLOWED:
1990 pw.print("allow");
1991 break;
1992 case AppOpsManager.MODE_IGNORED:
1993 pw.print("ignore");
1994 break;
1995 case AppOpsManager.MODE_ERRORED:
1996 pw.print("deny");
1997 break;
1998 case AppOpsManager.MODE_DEFAULT:
1999 pw.print("default");
2000 break;
2001 default:
2002 pw.print("mode=");
2003 pw.print(ent.getMode());
2004 break;
2005 }
2006 if (ent.getTime() != 0) {
2007 pw.print("; time=");
2008 TimeUtils.formatDuration(now - ent.getTime(), pw);
2009 pw.print(" ago");
2010 }
2011 if (ent.getRejectTime() != 0) {
2012 pw.print("; rejectTime=");
2013 TimeUtils.formatDuration(now - ent.getRejectTime(), pw);
2014 pw.print(" ago");
2015 }
2016 if (ent.getDuration() == -1) {
2017 pw.print(" (running)");
2018 } else if (ent.getDuration() != 0) {
2019 pw.print("; duration=");
2020 TimeUtils.formatDuration(ent.getDuration(), pw);
2021 }
2022 pw.println();
2023 }
2024 }
2025 return 0;
2026 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002027 case "query-op": {
2028 int res = shell.parseUserOpMode(AppOpsManager.MODE_IGNORED, err);
2029 if (res < 0) {
2030 return res;
2031 }
2032 List<AppOpsManager.PackageOps> ops = shell.mInterface.getPackagesForOps(
2033 new int[] {shell.op});
2034 if (ops == null || ops.size() <= 0) {
2035 pw.println("No operations.");
2036 return 0;
2037 }
2038 for (int i=0; i<ops.size(); i++) {
2039 final AppOpsManager.PackageOps pkg = ops.get(i);
2040 boolean hasMatch = false;
2041 final List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
2042 for (int j=0; j<entries.size(); j++) {
2043 AppOpsManager.OpEntry ent = entries.get(j);
2044 if (ent.getOp() == shell.op && ent.getMode() == shell.mode) {
2045 hasMatch = true;
2046 break;
2047 }
2048 }
2049 if (hasMatch) {
2050 pw.println(pkg.getPackageName());
2051 }
2052 }
2053 return 0;
2054 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002055 case "reset": {
2056 String packageName = null;
2057 int userId = UserHandle.USER_CURRENT;
2058 for (String argument; (argument = shell.getNextArg()) != null;) {
2059 if ("--user".equals(argument)) {
2060 String userStr = shell.getNextArgRequired();
2061 userId = UserHandle.parseUserArg(userStr);
2062 } else {
2063 if (packageName == null) {
2064 packageName = argument;
2065 } else {
2066 err.println("Error: Unsupported argument: " + argument);
2067 return -1;
2068 }
2069 }
2070 }
2071
2072 if (userId == UserHandle.USER_CURRENT) {
2073 userId = ActivityManager.getCurrentUser();
2074 }
2075
2076 shell.mInterface.resetAllModes(userId, packageName);
2077 pw.print("Reset all modes for: ");
2078 if (userId == UserHandle.USER_ALL) {
2079 pw.print("all users");
2080 } else {
2081 pw.print("user "); pw.print(userId);
2082 }
2083 pw.print(", ");
2084 if (packageName == null) {
2085 pw.println("all packages");
2086 } else {
2087 pw.print("package "); pw.println(packageName);
2088 }
2089 return 0;
2090 }
2091 case "write-settings": {
2092 shell.mInternal.mContext.enforcePermission(
2093 android.Manifest.permission.UPDATE_APP_OPS_STATS,
2094 Binder.getCallingPid(), Binder.getCallingUid(), null);
2095 long token = Binder.clearCallingIdentity();
2096 try {
2097 synchronized (shell.mInternal) {
2098 shell.mInternal.mHandler.removeCallbacks(shell.mInternal.mWriteRunner);
2099 }
2100 shell.mInternal.writeState();
2101 pw.println("Current settings written.");
2102 } finally {
2103 Binder.restoreCallingIdentity(token);
2104 }
2105 return 0;
2106 }
2107 case "read-settings": {
2108 shell.mInternal.mContext.enforcePermission(
2109 android.Manifest.permission.UPDATE_APP_OPS_STATS,
2110 Binder.getCallingPid(), Binder.getCallingUid(), null);
2111 long token = Binder.clearCallingIdentity();
2112 try {
2113 shell.mInternal.readState();
2114 pw.println("Last settings read.");
2115 } finally {
2116 Binder.restoreCallingIdentity(token);
2117 }
2118 return 0;
2119 }
2120 default:
2121 return shell.handleDefaultCommands(cmd);
2122 }
2123 } catch (RemoteException e) {
2124 pw.println("Remote exception: " + e);
2125 }
2126 return -1;
2127 }
2128
2129 private void dumpHelp(PrintWriter pw) {
2130 pw.println("AppOps service (appops) dump options:");
2131 pw.println(" none");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002132 }
2133
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002134 @Override
2135 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002136 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002137
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002138 if (args != null) {
2139 for (int i=0; i<args.length; i++) {
2140 String arg = args[i];
2141 if ("-h".equals(arg)) {
2142 dumpHelp(pw);
2143 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07002144 } else if ("-a".equals(arg)) {
2145 // dump all data
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002146 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
2147 pw.println("Unknown option: " + arg);
2148 return;
2149 } else {
2150 pw.println("Unknown command: " + arg);
2151 return;
2152 }
2153 }
2154 }
2155
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002156 synchronized (this) {
2157 pw.println("Current AppOps Service state:");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002158 final long now = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002159 boolean needSep = false;
2160 if (mOpModeWatchers.size() > 0) {
2161 needSep = true;
2162 pw.println(" Op mode watchers:");
2163 for (int i=0; i<mOpModeWatchers.size(); i++) {
2164 pw.print(" Op "); pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
2165 pw.println(":");
Dianne Hackborn68d76552017-02-27 15:32:03 -08002166 ArraySet<Callback> callbacks = mOpModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002167 for (int j=0; j<callbacks.size(); j++) {
2168 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08002169 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002170 }
2171 }
2172 }
2173 if (mPackageModeWatchers.size() > 0) {
2174 needSep = true;
2175 pw.println(" Package mode watchers:");
2176 for (int i=0; i<mPackageModeWatchers.size(); i++) {
2177 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
2178 pw.println(":");
Dianne Hackborn68d76552017-02-27 15:32:03 -08002179 ArraySet<Callback> callbacks = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002180 for (int j=0; j<callbacks.size(); j++) {
2181 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08002182 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002183 }
2184 }
2185 }
2186 if (mModeWatchers.size() > 0) {
2187 needSep = true;
2188 pw.println(" All mode watchers:");
2189 for (int i=0; i<mModeWatchers.size(); i++) {
2190 pw.print(" "); pw.print(mModeWatchers.keyAt(i));
2191 pw.print(" -> "); pw.println(mModeWatchers.valueAt(i));
2192 }
2193 }
2194 if (mClients.size() > 0) {
2195 needSep = true;
2196 pw.println(" Clients:");
2197 for (int i=0; i<mClients.size(); i++) {
2198 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
2199 ClientState cs = mClients.valueAt(i);
2200 pw.print(" "); pw.println(cs);
2201 if (cs.mStartedOps != null && cs.mStartedOps.size() > 0) {
2202 pw.println(" Started ops:");
2203 for (int j=0; j<cs.mStartedOps.size(); j++) {
2204 Op op = cs.mStartedOps.get(j);
2205 pw.print(" "); pw.print("uid="); pw.print(op.uid);
2206 pw.print(" pkg="); pw.print(op.packageName);
2207 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
2208 }
2209 }
2210 }
2211 }
John Spurlock1af30c72014-03-10 08:33:35 -04002212 if (mAudioRestrictions.size() > 0) {
2213 boolean printedHeader = false;
2214 for (int o=0; o<mAudioRestrictions.size(); o++) {
2215 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
2216 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
2217 for (int i=0; i<restrictions.size(); i++) {
2218 if (!printedHeader){
2219 pw.println(" Audio Restrictions:");
2220 printedHeader = true;
2221 needSep = true;
2222 }
John Spurlock7b414672014-07-18 13:02:39 -04002223 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04002224 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04002225 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04002226 Restriction r = restrictions.valueAt(i);
2227 pw.print(": mode="); pw.println(r.mode);
2228 if (!r.exceptionPackages.isEmpty()) {
2229 pw.println(" Exceptions:");
2230 for (int j=0; j<r.exceptionPackages.size(); j++) {
2231 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
2232 }
2233 }
2234 }
2235 }
2236 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002237 if (needSep) {
2238 pw.println();
2239 }
Svet Ganov2af57082015-07-30 08:44:20 -07002240 for (int i=0; i<mUidStates.size(); i++) {
2241 UidState uidState = mUidStates.valueAt(i);
2242
2243 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
Svet Ganovee438d42017-01-19 18:04:38 -08002244 needSep = true;
Svet Ganov2af57082015-07-30 08:44:20 -07002245
2246 SparseIntArray opModes = uidState.opModes;
2247 if (opModes != null) {
2248 final int opModeCount = opModes.size();
2249 for (int j = 0; j < opModeCount; j++) {
2250 final int code = opModes.keyAt(j);
2251 final int mode = opModes.valueAt(j);
2252 pw.print(" "); pw.print(AppOpsManager.opToName(code));
2253 pw.print(": mode="); pw.println(mode);
2254 }
2255 }
2256
2257 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
2258 if (pkgOps == null) {
2259 continue;
2260 }
2261
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002262 for (Ops ops : pkgOps.values()) {
2263 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
2264 for (int j=0; j<ops.size(); j++) {
2265 Op op = ops.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002266 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
2267 pw.print(": mode="); pw.print(op.mode);
2268 if (op.time != 0) {
2269 pw.print("; time="); TimeUtils.formatDuration(now-op.time, pw);
2270 pw.print(" ago");
2271 }
2272 if (op.rejectTime != 0) {
2273 pw.print("; rejectTime="); TimeUtils.formatDuration(now-op.rejectTime, pw);
2274 pw.print(" ago");
2275 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002276 if (op.duration == -1) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002277 pw.print(" (running)");
2278 } else if (op.duration != 0) {
2279 pw.print("; duration="); TimeUtils.formatDuration(op.duration, pw);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002280 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002281 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002282 }
2283 }
2284 }
Svet Ganovee438d42017-01-19 18:04:38 -08002285 if (needSep) {
2286 pw.println();
2287 }
2288
2289 final int userRestrictionCount = mOpUserRestrictions.size();
2290 for (int i = 0; i < userRestrictionCount; i++) {
2291 IBinder token = mOpUserRestrictions.keyAt(i);
2292 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
2293 pw.println(" User restrictions for token " + token + ":");
2294
2295 final int restrictionCount = restrictionState.perUserRestrictions != null
2296 ? restrictionState.perUserRestrictions.size() : 0;
2297 if (restrictionCount > 0) {
2298 pw.println(" Restricted ops:");
2299 for (int j = 0; j < restrictionCount; j++) {
2300 int userId = restrictionState.perUserRestrictions.keyAt(j);
2301 boolean[] restrictedOps = restrictionState.perUserRestrictions.valueAt(j);
2302 if (restrictedOps == null) {
2303 continue;
2304 }
2305 StringBuilder restrictedOpsValue = new StringBuilder();
2306 restrictedOpsValue.append("[");
2307 final int restrictedOpCount = restrictedOps.length;
2308 for (int k = 0; k < restrictedOpCount; k++) {
2309 if (restrictedOps[k]) {
2310 if (restrictedOpsValue.length() > 1) {
2311 restrictedOpsValue.append(", ");
2312 }
2313 restrictedOpsValue.append(AppOpsManager.opToName(k));
2314 }
2315 }
2316 restrictedOpsValue.append("]");
2317 pw.print(" "); pw.print("user: "); pw.print(userId);
2318 pw.print(" restricted ops: "); pw.println(restrictedOpsValue);
2319 }
2320 }
2321
2322 final int excludedPackageCount = restrictionState.perUserExcludedPackages != null
2323 ? restrictionState.perUserExcludedPackages.size() : 0;
2324 if (excludedPackageCount > 0) {
2325 pw.println(" Excluded packages:");
2326 for (int j = 0; j < excludedPackageCount; j++) {
2327 int userId = restrictionState.perUserExcludedPackages.keyAt(j);
2328 String[] packageNames = restrictionState.perUserExcludedPackages.valueAt(j);
2329 pw.print(" "); pw.print("user: "); pw.print(userId);
2330 pw.print(" packages: "); pw.println(Arrays.toString(packageNames));
2331 }
2332 }
2333 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002334 }
2335 }
John Spurlock1af30c72014-03-10 08:33:35 -04002336
2337 private static final class Restriction {
2338 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
2339 int mode;
2340 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
2341 }
Jason Monk62062992014-05-06 09:55:28 -04002342
2343 @Override
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002344 public void setUserRestrictions(Bundle restrictions, IBinder token, int userHandle) {
Jason Monk62062992014-05-06 09:55:28 -04002345 checkSystemUid("setUserRestrictions");
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002346 Preconditions.checkNotNull(restrictions);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002347 Preconditions.checkNotNull(token);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002348 for (int i = 0; i < AppOpsManager._NUM_OP; i++) {
Jason Monk62062992014-05-06 09:55:28 -04002349 String restriction = AppOpsManager.opToRestriction(i);
Suprabh Shukla64e0dcb2016-05-24 16:23:11 -07002350 if (restriction != null) {
2351 setUserRestrictionNoCheck(i, restrictions.getBoolean(restriction, false), token,
2352 userHandle, null);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002353 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002354 }
2355 }
2356
2357 @Override
Ruben Brunk29931bc2016-03-11 00:24:26 -08002358 public void setUserRestriction(int code, boolean restricted, IBinder token, int userHandle,
2359 String[] exceptionPackages) {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002360 if (Binder.getCallingPid() != Process.myPid()) {
2361 mContext.enforcePermission(Manifest.permission.MANAGE_APP_OPS_RESTRICTIONS,
2362 Binder.getCallingPid(), Binder.getCallingUid(), null);
2363 }
2364 if (userHandle != UserHandle.getCallingUserId()) {
2365 if (mContext.checkCallingOrSelfPermission(Manifest.permission
2366 .INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
2367 && mContext.checkCallingOrSelfPermission(Manifest.permission
2368 .INTERACT_ACROSS_USERS) != PackageManager.PERMISSION_GRANTED) {
2369 throw new SecurityException("Need INTERACT_ACROSS_USERS_FULL or"
2370 + " INTERACT_ACROSS_USERS to interact cross user ");
Jason Monk62062992014-05-06 09:55:28 -04002371 }
2372 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002373 verifyIncomingOp(code);
2374 Preconditions.checkNotNull(token);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002375 setUserRestrictionNoCheck(code, restricted, token, userHandle, exceptionPackages);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002376 }
2377
2378 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
Ruben Brunk29931bc2016-03-11 00:24:26 -08002379 int userHandle, String[] exceptionPackages) {
Svet Ganov442ed572016-08-17 17:29:43 -07002380 boolean notifyChange = false;
Ruben Brunk29931bc2016-03-11 00:24:26 -08002381
Svet Ganov442ed572016-08-17 17:29:43 -07002382 synchronized (AppOpsService.this) {
2383 ClientRestrictionState restrictionState = mOpUserRestrictions.get(token);
2384
2385 if (restrictionState == null) {
2386 try {
2387 restrictionState = new ClientRestrictionState(token);
2388 } catch (RemoteException e) {
2389 return;
2390 }
2391 mOpUserRestrictions.put(token, restrictionState);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002392 }
Svet Ganov442ed572016-08-17 17:29:43 -07002393
2394 if (restrictionState.setRestriction(code, restricted, exceptionPackages, userHandle)) {
2395 notifyChange = true;
2396 }
2397
2398 if (restrictionState.isDefault()) {
2399 mOpUserRestrictions.remove(token);
2400 restrictionState.destroy();
2401 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002402 }
2403
Svet Ganov442ed572016-08-17 17:29:43 -07002404 if (notifyChange) {
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002405 notifyWatchersOfChange(code);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002406 }
Julia Reynoldsbb21c252016-04-05 16:01:49 -04002407 }
2408
2409 private void notifyWatchersOfChange(int code) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08002410 final ArraySet<Callback> clonedCallbacks;
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002411 synchronized (this) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08002412 ArraySet<Callback> callbacks = mOpModeWatchers.get(code);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002413 if (callbacks == null) {
2414 return;
2415 }
Dianne Hackborn68d76552017-02-27 15:32:03 -08002416 clonedCallbacks = new ArraySet<>(callbacks);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002417 }
2418
2419 // There are components watching for mode changes such as window manager
2420 // and location manager which are in our process. The callbacks in these
Dianne Hackborn68d76552017-02-27 15:32:03 -08002421 // components may require permissions our remote caller does not have.
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002422 final long identity = Binder.clearCallingIdentity();
2423 try {
2424 final int callbackCount = clonedCallbacks.size();
2425 for (int i = 0; i < callbackCount; i++) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08002426 Callback callback = clonedCallbacks.valueAt(i);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002427 try {
2428 callback.mCallback.opChanged(code, -1, null);
2429 } catch (RemoteException e) {
2430 Log.w(TAG, "Error dispatching op op change", e);
2431 }
2432 }
2433 } finally {
2434 Binder.restoreCallingIdentity(identity);
2435 }
Jason Monk62062992014-05-06 09:55:28 -04002436 }
2437
2438 @Override
2439 public void removeUser(int userHandle) throws RemoteException {
2440 checkSystemUid("removeUser");
Svet Ganov442ed572016-08-17 17:29:43 -07002441 synchronized (AppOpsService.this) {
2442 final int tokenCount = mOpUserRestrictions.size();
2443 for (int i = tokenCount - 1; i >= 0; i--) {
2444 ClientRestrictionState opRestrictions = mOpUserRestrictions.valueAt(i);
2445 opRestrictions.removeUser(userHandle);
2446 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002447 removeUidsForUserLocked(userHandle);
2448 }
2449 }
2450
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002451 @Override
2452 public boolean isOperationActive(int code, int uid, String packageName) {
2453 verifyIncomingUid(uid);
2454 verifyIncomingOp(code);
2455 String resolvedPackageName = resolvePackageName(uid, packageName);
2456 if (resolvedPackageName == null) {
2457 return false;
2458 }
2459 synchronized (this) {
2460 for (int i = mClients.size() - 1; i >= 0; i--) {
2461 final ClientState client = mClients.valueAt(i);
2462 if (client.mStartedOps == null) continue;
2463
2464 for (int j = client.mStartedOps.size() - 1; j >= 0; j--) {
2465 final Op op = client.mStartedOps.get(j);
2466 if (op.op == code && op.uid == uid) return true;
2467 }
2468 }
2469 }
2470 return false;
2471 }
2472
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002473 private void removeUidsForUserLocked(int userHandle) {
2474 for (int i = mUidStates.size() - 1; i >= 0; --i) {
2475 final int uid = mUidStates.keyAt(i);
2476 if (UserHandle.getUserId(uid) == userHandle) {
2477 mUidStates.removeAt(i);
2478 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002479 }
2480 }
2481
Jason Monk62062992014-05-06 09:55:28 -04002482 private void checkSystemUid(String function) {
2483 int uid = Binder.getCallingUid();
2484 if (uid != Process.SYSTEM_UID) {
2485 throw new SecurityException(function + " must by called by the system");
2486 }
2487 }
2488
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002489 private static String resolvePackageName(int uid, String packageName) {
2490 if (uid == 0) {
2491 return "root";
2492 } else if (uid == Process.SHELL_UID) {
2493 return "com.android.shell";
2494 } else if (uid == Process.SYSTEM_UID && packageName == null) {
2495 return "android";
2496 }
2497 return packageName;
2498 }
2499
Svet Ganov2af57082015-07-30 08:44:20 -07002500 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07002501 String[] packageNames = null;
Svet Ganov2af57082015-07-30 08:44:20 -07002502 try {
riddle_hsu40b300f2015-11-23 13:22:03 +08002503 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -07002504 } catch (RemoteException e) {
2505 /* ignore - local call */
2506 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07002507 if (packageNames == null) {
2508 return EmptyArray.STRING;
2509 }
2510 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07002511 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002512
2513 private final class ClientRestrictionState implements DeathRecipient {
2514 private final IBinder token;
2515 SparseArray<boolean[]> perUserRestrictions;
2516 SparseArray<String[]> perUserExcludedPackages;
2517
2518 public ClientRestrictionState(IBinder token)
2519 throws RemoteException {
2520 token.linkToDeath(this, 0);
2521 this.token = token;
2522 }
2523
2524 public boolean setRestriction(int code, boolean restricted,
2525 String[] excludedPackages, int userId) {
2526 boolean changed = false;
2527
2528 if (perUserRestrictions == null && restricted) {
2529 perUserRestrictions = new SparseArray<>();
2530 }
2531
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002532 int[] users;
2533 if (userId == UserHandle.USER_ALL) {
2534 List<UserInfo> liveUsers = UserManager.get(mContext).getUsers(false);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002535
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002536 users = new int[liveUsers.size()];
2537 for (int i = 0; i < liveUsers.size(); i++) {
2538 users[i] = liveUsers.get(i).id;
2539 }
2540 } else {
2541 users = new int[]{userId};
2542 }
2543
2544 if (perUserRestrictions != null) {
2545 int numUsers = users.length;
2546
2547 for (int i = 0; i < numUsers; i++) {
2548 int thisUserId = users[i];
2549
2550 boolean[] userRestrictions = perUserRestrictions.get(thisUserId);
2551 if (userRestrictions == null && restricted) {
2552 userRestrictions = new boolean[AppOpsManager._NUM_OP];
2553 perUserRestrictions.put(thisUserId, userRestrictions);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002554 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002555 if (userRestrictions != null && userRestrictions[code] != restricted) {
2556 userRestrictions[code] = restricted;
2557 if (!restricted && isDefault(userRestrictions)) {
2558 perUserRestrictions.remove(thisUserId);
2559 userRestrictions = null;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002560 }
2561 changed = true;
2562 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002563
2564 if (userRestrictions != null) {
2565 final boolean noExcludedPackages = ArrayUtils.isEmpty(excludedPackages);
2566 if (perUserExcludedPackages == null && !noExcludedPackages) {
2567 perUserExcludedPackages = new SparseArray<>();
2568 }
2569 if (perUserExcludedPackages != null && !Arrays.equals(excludedPackages,
2570 perUserExcludedPackages.get(thisUserId))) {
2571 if (noExcludedPackages) {
2572 perUserExcludedPackages.remove(thisUserId);
2573 if (perUserExcludedPackages.size() <= 0) {
2574 perUserExcludedPackages = null;
2575 }
2576 } else {
2577 perUserExcludedPackages.put(thisUserId, excludedPackages);
2578 }
2579 changed = true;
2580 }
2581 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002582 }
2583 }
2584
2585 return changed;
2586 }
2587
2588 public boolean hasRestriction(int restriction, String packageName, int userId) {
2589 if (perUserRestrictions == null) {
2590 return false;
2591 }
2592 boolean[] restrictions = perUserRestrictions.get(userId);
2593 if (restrictions == null) {
2594 return false;
2595 }
2596 if (!restrictions[restriction]) {
2597 return false;
2598 }
2599 if (perUserExcludedPackages == null) {
2600 return true;
2601 }
2602 String[] perUserExclusions = perUserExcludedPackages.get(userId);
2603 if (perUserExclusions == null) {
2604 return true;
2605 }
2606 return !ArrayUtils.contains(perUserExclusions, packageName);
2607 }
2608
2609 public void removeUser(int userId) {
2610 if (perUserExcludedPackages != null) {
2611 perUserExcludedPackages.remove(userId);
2612 if (perUserExcludedPackages.size() <= 0) {
2613 perUserExcludedPackages = null;
2614 }
2615 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002616 if (perUserRestrictions != null) {
2617 perUserRestrictions.remove(userId);
2618 if (perUserRestrictions.size() <= 0) {
2619 perUserRestrictions = null;
2620 }
2621 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002622 }
2623
2624 public boolean isDefault() {
2625 return perUserRestrictions == null || perUserRestrictions.size() <= 0;
2626 }
2627
2628 @Override
2629 public void binderDied() {
2630 synchronized (AppOpsService.this) {
2631 mOpUserRestrictions.remove(token);
2632 if (perUserRestrictions == null) {
2633 return;
2634 }
2635 final int userCount = perUserRestrictions.size();
2636 for (int i = 0; i < userCount; i++) {
2637 final boolean[] restrictions = perUserRestrictions.valueAt(i);
2638 final int restrictionCount = restrictions.length;
2639 for (int j = 0; j < restrictionCount; j++) {
2640 if (restrictions[j]) {
2641 final int changedCode = j;
2642 mHandler.post(() -> notifyWatchersOfChange(changedCode));
2643 }
2644 }
2645 }
2646 destroy();
2647 }
2648 }
2649
2650 public void destroy() {
2651 token.unlinkToDeath(this, 0);
2652 }
2653
2654 private boolean isDefault(boolean[] array) {
2655 if (ArrayUtils.isEmpty(array)) {
2656 return true;
2657 }
2658 for (boolean value : array) {
2659 if (value) {
2660 return false;
2661 }
2662 }
2663 return true;
2664 }
2665 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002666}