blob: f4675fd3316df0f9b1556e9fdcb6718ca469c8f2 [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
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070055import com.android.internal.annotations.VisibleForTesting;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070056import com.android.internal.app.IAppOpsCallback;
57import com.android.internal.app.IAppOpsService;
58import com.android.internal.os.Zygote;
59import com.android.internal.util.ArrayUtils;
60import com.android.internal.util.DumpUtils;
61import com.android.internal.util.FastXmlSerializer;
62import com.android.internal.util.Preconditions;
63import com.android.internal.util.XmlUtils;
64
65import libcore.util.EmptyArray;
66
67import org.xmlpull.v1.XmlPullParser;
68import org.xmlpull.v1.XmlPullParserException;
69import org.xmlpull.v1.XmlSerializer;
70
Dianne Hackborna06de0f2012-12-11 16:34:47 -080071import java.io.File;
72import java.io.FileDescriptor;
Dianne Hackborn35654b62013-01-14 17:38:02 -080073import java.io.FileInputStream;
74import java.io.FileNotFoundException;
75import java.io.FileOutputStream;
76import java.io.IOException;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080077import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010078import java.nio.charset.StandardCharsets;
Dianne Hackborn35654b62013-01-14 17:38:02 -080079import java.util.ArrayList;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -070080import java.util.Arrays;
Svetoslav215b44a2015-08-04 19:03:40 -070081import java.util.Collections;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080082import java.util.HashMap;
Dianne Hackbornc2293022013-02-06 23:14:49 -080083import java.util.Iterator;
Dianne Hackborn35654b62013-01-14 17:38:02 -080084import java.util.List;
Dianne Hackborn607b4142013-08-02 18:10:10 -070085import java.util.Map;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080086
Dianne Hackborna06de0f2012-12-11 16:34:47 -080087public class AppOpsService extends IAppOpsService.Stub {
88 static final String TAG = "AppOps";
Dianne Hackborn35654b62013-01-14 17:38:02 -080089 static final boolean DEBUG = false;
90
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070091 private static final int NO_VERSION = -1;
92 /** Increment by one every time and add the corresponding upgrade logic in
93 * {@link #upgradeLocked(int)} below. The first version was 1 */
94 private static final int CURRENT_VERSION = 1;
95
Dianne Hackborn35654b62013-01-14 17:38:02 -080096 // Write at most every 30 minutes.
97 static final long WRITE_DELAY = DEBUG ? 1000 : 30*60*1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080098
99 Context mContext;
100 final AtomicFile mFile;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800101 final Handler mHandler;
102
103 boolean mWriteScheduled;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800104 boolean mFastWriteScheduled;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800105 final Runnable mWriteRunner = new Runnable() {
106 public void run() {
107 synchronized (AppOpsService.this) {
108 mWriteScheduled = false;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800109 mFastWriteScheduled = false;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800110 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
111 @Override protected Void doInBackground(Void... params) {
112 writeState();
113 return null;
114 }
115 };
116 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
117 }
118 }
119 };
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800120
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700121 @VisibleForTesting
122 final SparseArray<UidState> mUidStates = new SparseArray<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800123
Ruben Brunk29931bc2016-03-11 00:24:26 -0800124 /*
125 * These are app op restrictions imposed per user from various parties.
Ruben Brunk29931bc2016-03-11 00:24:26 -0800126 */
Svetoslav Ganova8bbd762016-05-13 17:08:16 -0700127 private final ArrayMap<IBinder, ClientRestrictionState> mOpUserRestrictions = new ArrayMap<>();
Jason Monk62062992014-05-06 09:55:28 -0400128
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700129 @VisibleForTesting
130 static final class UidState {
Svet Ganov2af57082015-07-30 08:44:20 -0700131 public final int uid;
132 public ArrayMap<String, Ops> pkgOps;
133 public SparseIntArray opModes;
134
135 public UidState(int uid) {
136 this.uid = uid;
137 }
138
139 public void clear() {
140 pkgOps = null;
141 opModes = null;
142 }
143
144 public boolean isDefault() {
145 return (pkgOps == null || pkgOps.isEmpty())
146 && (opModes == null || opModes.size() <= 0);
147 }
148 }
149
Dianne Hackbornc2293022013-02-06 23:14:49 -0800150 public final static class Ops extends SparseArray<Op> {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800151 public final String packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700152 public final UidState uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400153 public final boolean isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800154
Svet Ganov2af57082015-07-30 08:44:20 -0700155 public Ops(String _packageName, UidState _uidState, boolean _isPrivileged) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800156 packageName = _packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700157 uidState = _uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400158 isPrivileged = _isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800159 }
160 }
161
Dianne Hackbornc2293022013-02-06 23:14:49 -0800162 public final static class Op {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700163 public final int uid;
164 public final String packageName;
Svet Ganov99b60432015-06-27 13:15:22 -0700165 public int proxyUid = -1;
166 public String proxyPackageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800167 public final int op;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800168 public int mode;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800169 public int duration;
170 public long time;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800171 public long rejectTime;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800172 public int nesting;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800173
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700174 public Op(int _uid, String _packageName, int _op) {
175 uid = _uid;
176 packageName = _packageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800177 op = _op;
David Braunf5d83192013-09-16 13:43:51 -0700178 mode = AppOpsManager.opToDefaultMode(op);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800179 }
180 }
181
Dianne Hackborn68d76552017-02-27 15:32:03 -0800182 final SparseArray<ArraySet<Callback>> mOpModeWatchers = new SparseArray<>();
183 final ArrayMap<String, ArraySet<Callback>> mPackageModeWatchers = new ArrayMap<>();
184 final ArrayMap<IBinder, Callback> mModeWatchers = new ArrayMap<>();
185 final SparseArray<SparseArray<Restriction>> mAudioRestrictions = new SparseArray<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800186
187 public final class Callback implements DeathRecipient {
188 final IAppOpsCallback mCallback;
189
190 public Callback(IAppOpsCallback callback) {
191 mCallback = callback;
192 try {
193 mCallback.asBinder().linkToDeath(this, 0);
194 } catch (RemoteException e) {
195 }
196 }
197
198 public void unlinkToDeath() {
199 mCallback.asBinder().unlinkToDeath(this, 0);
200 }
201
202 @Override
203 public void binderDied() {
204 stopWatchingMode(mCallback);
205 }
206 }
207
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700208 final ArrayMap<IBinder, ClientState> mClients = new ArrayMap<IBinder, ClientState>();
209
210 public final class ClientState extends Binder implements DeathRecipient {
211 final IBinder mAppToken;
212 final int mPid;
213 final ArrayList<Op> mStartedOps;
214
215 public ClientState(IBinder appToken) {
216 mAppToken = appToken;
217 mPid = Binder.getCallingPid();
218 if (appToken instanceof Binder) {
219 // For local clients, there is no reason to track them.
220 mStartedOps = null;
221 } else {
222 mStartedOps = new ArrayList<Op>();
223 try {
224 mAppToken.linkToDeath(this, 0);
225 } catch (RemoteException e) {
226 }
227 }
228 }
229
230 @Override
231 public String toString() {
232 return "ClientState{" +
233 "mAppToken=" + mAppToken +
234 ", " + (mStartedOps != null ? ("pid=" + mPid) : "local") +
235 '}';
236 }
237
238 @Override
239 public void binderDied() {
240 synchronized (AppOpsService.this) {
241 for (int i=mStartedOps.size()-1; i>=0; i--) {
242 finishOperationLocked(mStartedOps.get(i));
243 }
244 mClients.remove(mAppToken);
245 }
246 }
247 }
248
Jeff Brown6f357d32014-01-15 20:40:55 -0800249 public AppOpsService(File storagePath, Handler handler) {
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600250 LockGuard.installLock(this, LockGuard.INDEX_APP_OPS);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800251 mFile = new AtomicFile(storagePath);
Jeff Brown6f357d32014-01-15 20:40:55 -0800252 mHandler = handler;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800253 readState();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800254 }
David Braunf5d83192013-09-16 13:43:51 -0700255
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800256 public void publish(Context context) {
257 mContext = context;
258 ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
259 }
260
Dianne Hackborn514074f2013-02-11 10:52:46 -0800261 public void systemReady() {
262 synchronized (this) {
263 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700264 for (int i = mUidStates.size() - 1; i >= 0; i--) {
265 UidState uidState = mUidStates.valueAt(i);
266
267 String[] packageNames = getPackagesForUid(uidState.uid);
268 if (ArrayUtils.isEmpty(packageNames)) {
269 uidState.clear();
270 mUidStates.removeAt(i);
271 changed = true;
272 continue;
273 }
274
275 ArrayMap<String, Ops> pkgs = uidState.pkgOps;
276 if (pkgs == null) {
277 continue;
278 }
279
Dianne Hackborn514074f2013-02-11 10:52:46 -0800280 Iterator<Ops> it = pkgs.values().iterator();
281 while (it.hasNext()) {
282 Ops ops = it.next();
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700283 int curUid = -1;
Dianne Hackborn514074f2013-02-11 10:52:46 -0800284 try {
Jeff Sharkeycd654482016-01-08 17:42:11 -0700285 curUid = AppGlobals.getPackageManager().getPackageUid(ops.packageName,
286 PackageManager.MATCH_UNINSTALLED_PACKAGES,
Svet Ganov2af57082015-07-30 08:44:20 -0700287 UserHandle.getUserId(ops.uidState.uid));
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700288 } catch (RemoteException ignored) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800289 }
Svet Ganov2af57082015-07-30 08:44:20 -0700290 if (curUid != ops.uidState.uid) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800291 Slog.i(TAG, "Pruning old package " + ops.packageName
Svet Ganov2af57082015-07-30 08:44:20 -0700292 + "/" + ops.uidState + ": new uid=" + curUid);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800293 it.remove();
294 changed = true;
295 }
296 }
Svet Ganov2af57082015-07-30 08:44:20 -0700297
298 if (uidState.isDefault()) {
299 mUidStates.removeAt(i);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800300 }
301 }
302 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800303 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800304 }
305 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700306
Suprabh Shuklaaef25132017-01-23 18:09:03 -0800307 PackageManagerInternal packageManagerInternal = LocalServices.getService(
308 PackageManagerInternal.class);
309 packageManagerInternal.setExternalSourcesPolicy(
310 new PackageManagerInternal.ExternalSourcesPolicy() {
311 @Override
312 public int getPackageTrustedToInstallApps(String packageName, int uid) {
313 int appOpMode = checkOperation(AppOpsManager.OP_REQUEST_INSTALL_PACKAGES,
314 uid, packageName);
315 switch (appOpMode) {
316 case AppOpsManager.MODE_ALLOWED:
317 return PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
318 case AppOpsManager.MODE_ERRORED:
319 return PackageManagerInternal.ExternalSourcesPolicy.USER_BLOCKED;
320 default:
321 return PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT;
322 }
323 }
324 });
325
Sudheer Shanka2250d562016-11-07 15:41:02 -0800326 StorageManagerInternal storageManagerInternal = LocalServices.getService(
327 StorageManagerInternal.class);
328 storageManagerInternal.addExternalStoragePolicy(
329 new StorageManagerInternal.ExternalStorageMountPolicy() {
Svet Ganov6ee871e2015-07-10 14:29:33 -0700330 @Override
331 public int getMountMode(int uid, String packageName) {
332 if (Process.isIsolated(uid)) {
333 return Zygote.MOUNT_EXTERNAL_NONE;
334 }
335 if (noteOperation(AppOpsManager.OP_READ_EXTERNAL_STORAGE, uid,
336 packageName) != AppOpsManager.MODE_ALLOWED) {
337 return Zygote.MOUNT_EXTERNAL_NONE;
338 }
339 if (noteOperation(AppOpsManager.OP_WRITE_EXTERNAL_STORAGE, uid,
340 packageName) != AppOpsManager.MODE_ALLOWED) {
341 return Zygote.MOUNT_EXTERNAL_READ;
342 }
343 return Zygote.MOUNT_EXTERNAL_WRITE;
344 }
345
346 @Override
347 public boolean hasExternalStorage(int uid, String packageName) {
348 final int mountMode = getMountMode(uid, packageName);
349 return mountMode == Zygote.MOUNT_EXTERNAL_READ
350 || mountMode == Zygote.MOUNT_EXTERNAL_WRITE;
351 }
352 });
Dianne Hackborn514074f2013-02-11 10:52:46 -0800353 }
354
355 public void packageRemoved(int uid, String packageName) {
356 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700357 UidState uidState = mUidStates.get(uid);
358 if (uidState == null) {
359 return;
360 }
361
362 boolean changed = false;
363
364 // Remove any package state if such.
365 if (uidState.pkgOps != null && uidState.pkgOps.remove(packageName) != null) {
366 changed = true;
367 }
368
369 // If we just nuked the last package state check if the UID is valid.
370 if (changed && uidState.pkgOps.isEmpty()
371 && getPackagesForUid(uid).length <= 0) {
372 mUidStates.remove(uid);
373 }
374
375 if (changed) {
376 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800377 }
378 }
379 }
380
381 public void uidRemoved(int uid) {
382 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700383 if (mUidStates.indexOfKey(uid) >= 0) {
384 mUidStates.remove(uid);
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800385 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800386 }
387 }
388 }
389
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800390 public void shutdown() {
391 Slog.w(TAG, "Writing app ops before shutdown...");
Dianne Hackborn35654b62013-01-14 17:38:02 -0800392 boolean doWrite = false;
393 synchronized (this) {
394 if (mWriteScheduled) {
395 mWriteScheduled = false;
396 doWrite = true;
397 }
398 }
399 if (doWrite) {
400 writeState();
401 }
402 }
403
Dianne Hackborn72e39832013-01-18 18:36:09 -0800404 private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
405 ArrayList<AppOpsManager.OpEntry> resOps = null;
406 if (ops == null) {
407 resOps = new ArrayList<AppOpsManager.OpEntry>();
408 for (int j=0; j<pkgOps.size(); j++) {
409 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800410 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Svet Ganov99b60432015-06-27 13:15:22 -0700411 curOp.rejectTime, curOp.duration, curOp.proxyUid,
412 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800413 }
414 } else {
415 for (int j=0; j<ops.length; j++) {
416 Op curOp = pkgOps.get(ops[j]);
417 if (curOp != null) {
418 if (resOps == null) {
419 resOps = new ArrayList<AppOpsManager.OpEntry>();
420 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800421 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Svet Ganov99b60432015-06-27 13:15:22 -0700422 curOp.rejectTime, curOp.duration, curOp.proxyUid,
423 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800424 }
425 }
426 }
427 return resOps;
428 }
429
Dianne Hackbornc7214a32017-04-11 13:32:47 -0700430 private ArrayList<AppOpsManager.OpEntry> collectOps(SparseIntArray uidOps, int[] ops) {
431 ArrayList<AppOpsManager.OpEntry> resOps = null;
432 if (ops == null) {
433 resOps = new ArrayList<>();
434 for (int j=0; j<uidOps.size(); j++) {
435 resOps.add(new AppOpsManager.OpEntry(uidOps.keyAt(j), uidOps.valueAt(j),
436 0, 0, 0, -1, null));
437 }
438 } else {
439 for (int j=0; j<ops.length; j++) {
440 int index = uidOps.indexOfKey(ops[j]);
441 if (index >= 0) {
442 if (resOps == null) {
443 resOps = new ArrayList<>();
444 }
445 resOps.add(new AppOpsManager.OpEntry(uidOps.keyAt(index), uidOps.valueAt(index),
446 0, 0, 0, -1, null));
447 }
448 }
449 }
450 return resOps;
451 }
452
Dianne Hackborn35654b62013-01-14 17:38:02 -0800453 @Override
454 public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
455 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
456 Binder.getCallingPid(), Binder.getCallingUid(), null);
457 ArrayList<AppOpsManager.PackageOps> res = null;
458 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700459 final int uidStateCount = mUidStates.size();
460 for (int i = 0; i < uidStateCount; i++) {
461 UidState uidState = mUidStates.valueAt(i);
462 if (uidState.pkgOps == null || uidState.pkgOps.isEmpty()) {
463 continue;
464 }
465 ArrayMap<String, Ops> packages = uidState.pkgOps;
466 final int packageCount = packages.size();
467 for (int j = 0; j < packageCount; j++) {
468 Ops pkgOps = packages.valueAt(j);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800469 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800470 if (resOps != null) {
471 if (res == null) {
472 res = new ArrayList<AppOpsManager.PackageOps>();
473 }
474 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700475 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800476 res.add(resPackage);
477 }
478 }
479 }
480 }
481 return res;
482 }
483
484 @Override
Dianne Hackborn72e39832013-01-18 18:36:09 -0800485 public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
486 int[] ops) {
487 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
488 Binder.getCallingPid(), Binder.getCallingUid(), null);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000489 String resolvedPackageName = resolvePackageName(uid, packageName);
490 if (resolvedPackageName == null) {
491 return Collections.emptyList();
492 }
Dianne Hackborn72e39832013-01-18 18:36:09 -0800493 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -0700494 Ops pkgOps = getOpsRawLocked(uid, resolvedPackageName, false /* edit */,
495 false /* uidMismatchExpected */);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800496 if (pkgOps == null) {
497 return null;
498 }
499 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
500 if (resOps == null) {
501 return null;
502 }
503 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
504 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700505 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800506 res.add(resPackage);
507 return res;
508 }
509 }
510
Dianne Hackbornc7214a32017-04-11 13:32:47 -0700511 @Override
512 public List<AppOpsManager.PackageOps> getUidOps(int uid, int[] ops) {
513 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
514 Binder.getCallingPid(), Binder.getCallingUid(), null);
515 synchronized (this) {
516 UidState uidState = getUidStateLocked(uid, false);
517 if (uidState == null) {
518 return null;
519 }
520 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(uidState.opModes, ops);
521 if (resOps == null) {
522 return null;
523 }
524 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
525 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
526 null, uidState.uid, resOps);
527 res.add(resPackage);
528 return res;
529 }
530 }
531
Dianne Hackborn607b4142013-08-02 18:10:10 -0700532 private void pruneOp(Op op, int uid, String packageName) {
533 if (op.time == 0 && op.rejectTime == 0) {
Yohei Yukawaa965d652017-10-12 15:02:26 -0700534 Ops ops = getOpsRawLocked(uid, packageName, false /* edit */,
535 false /* uidMismatchExpected */);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700536 if (ops != null) {
537 ops.remove(op.op);
538 if (ops.size() <= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -0700539 UidState uidState = ops.uidState;
540 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700541 if (pkgOps != null) {
542 pkgOps.remove(ops.packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700543 if (pkgOps.isEmpty()) {
544 uidState.pkgOps = null;
545 }
546 if (uidState.isDefault()) {
547 mUidStates.remove(uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700548 }
549 }
550 }
551 }
552 }
553 }
554
Dianne Hackborn72e39832013-01-18 18:36:09 -0800555 @Override
Svet Ganov2af57082015-07-30 08:44:20 -0700556 public void setUidMode(int code, int uid, int mode) {
557 if (Binder.getCallingPid() != Process.myPid()) {
558 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
559 Binder.getCallingPid(), Binder.getCallingUid(), null);
560 }
561 verifyIncomingOp(code);
562 code = AppOpsManager.opToSwitch(code);
563
564 synchronized (this) {
565 final int defaultMode = AppOpsManager.opToDefaultMode(code);
566
567 UidState uidState = getUidStateLocked(uid, false);
568 if (uidState == null) {
569 if (mode == defaultMode) {
570 return;
571 }
572 uidState = new UidState(uid);
573 uidState.opModes = new SparseIntArray();
574 uidState.opModes.put(code, mode);
575 mUidStates.put(uid, uidState);
576 scheduleWriteLocked();
577 } else if (uidState.opModes == null) {
578 if (mode != defaultMode) {
579 uidState.opModes = new SparseIntArray();
580 uidState.opModes.put(code, mode);
581 scheduleWriteLocked();
582 }
583 } else {
584 if (uidState.opModes.get(code) == mode) {
585 return;
586 }
587 if (mode == defaultMode) {
588 uidState.opModes.delete(code);
589 if (uidState.opModes.size() <= 0) {
590 uidState.opModes = null;
591 }
592 } else {
593 uidState.opModes.put(code, mode);
594 }
595 scheduleWriteLocked();
596 }
597 }
598
Svetoslav215b44a2015-08-04 19:03:40 -0700599 String[] uidPackageNames = getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -0700600 ArrayMap<Callback, ArraySet<String>> callbackSpecs = null;
601
riddle_hsu40b300f2015-11-23 13:22:03 +0800602 synchronized (this) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800603 ArraySet<Callback> callbacks = mOpModeWatchers.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -0700604 if (callbacks != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700605 final int callbackCount = callbacks.size();
606 for (int i = 0; i < callbackCount; i++) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800607 Callback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +0800608 ArraySet<String> changedPackages = new ArraySet<>();
609 Collections.addAll(changedPackages, uidPackageNames);
610 callbackSpecs = new ArrayMap<>();
611 callbackSpecs.put(callback, changedPackages);
612 }
613 }
614
615 for (String uidPackageName : uidPackageNames) {
616 callbacks = mPackageModeWatchers.get(uidPackageName);
617 if (callbacks != null) {
618 if (callbackSpecs == null) {
619 callbackSpecs = new ArrayMap<>();
Svet Ganov2af57082015-07-30 08:44:20 -0700620 }
riddle_hsu40b300f2015-11-23 13:22:03 +0800621 final int callbackCount = callbacks.size();
622 for (int i = 0; i < callbackCount; i++) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800623 Callback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +0800624 ArraySet<String> changedPackages = callbackSpecs.get(callback);
625 if (changedPackages == null) {
626 changedPackages = new ArraySet<>();
627 callbackSpecs.put(callback, changedPackages);
628 }
629 changedPackages.add(uidPackageName);
630 }
Svet Ganov2af57082015-07-30 08:44:20 -0700631 }
632 }
633 }
634
635 if (callbackSpecs == null) {
636 return;
637 }
638
639 // There are components watching for mode changes such as window manager
640 // and location manager which are in our process. The callbacks in these
641 // components may require permissions our remote caller does not have.
642 final long identity = Binder.clearCallingIdentity();
643 try {
644 for (int i = 0; i < callbackSpecs.size(); i++) {
645 Callback callback = callbackSpecs.keyAt(i);
646 ArraySet<String> reportedPackageNames = callbackSpecs.valueAt(i);
647 try {
648 if (reportedPackageNames == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700649 callback.mCallback.opChanged(code, uid, null);
Svet Ganov2af57082015-07-30 08:44:20 -0700650 } else {
651 final int reportedPackageCount = reportedPackageNames.size();
652 for (int j = 0; j < reportedPackageCount; j++) {
653 String reportedPackageName = reportedPackageNames.valueAt(j);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700654 callback.mCallback.opChanged(code, uid, reportedPackageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700655 }
656 }
657 } catch (RemoteException e) {
658 Log.w(TAG, "Error dispatching op op change", e);
659 }
660 }
661 } finally {
662 Binder.restoreCallingIdentity(identity);
663 }
664 }
665
666 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800667 public void setMode(int code, int uid, String packageName, int mode) {
Dianne Hackbornb64afe12014-07-22 16:29:04 -0700668 if (Binder.getCallingPid() != Process.myPid()) {
669 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
670 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborn133b9df2014-07-01 13:06:10 -0700671 }
Dianne Hackborn961321f2013-02-05 17:22:41 -0800672 verifyIncomingOp(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800673 ArrayList<Callback> repCbs = null;
674 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800675 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700676 UidState uidState = getUidStateLocked(uid, false);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800677 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800678 if (op != null) {
679 if (op.mode != mode) {
680 op.mode = mode;
Dianne Hackborn68d76552017-02-27 15:32:03 -0800681 ArraySet<Callback> cbs = mOpModeWatchers.get(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800682 if (cbs != null) {
683 if (repCbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800684 repCbs = new ArrayList<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800685 }
686 repCbs.addAll(cbs);
687 }
688 cbs = mPackageModeWatchers.get(packageName);
689 if (cbs != null) {
690 if (repCbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800691 repCbs = new ArrayList<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800692 }
693 repCbs.addAll(cbs);
694 }
David Braunf5d83192013-09-16 13:43:51 -0700695 if (mode == AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800696 // If going into the default mode, prune this op
697 // if there is nothing else interesting in it.
Dianne Hackborn607b4142013-08-02 18:10:10 -0700698 pruneOp(op, uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800699 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800700 scheduleFastWriteLocked();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800701 }
702 }
703 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800704 if (repCbs != null) {
Svet Ganov38536112015-05-19 12:45:52 -0700705 // There are components watching for mode changes such as window manager
706 // and location manager which are in our process. The callbacks in these
707 // components may require permissions our remote caller does not have.
708 final long identity = Binder.clearCallingIdentity();
709 try {
710 for (int i = 0; i < repCbs.size(); i++) {
711 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700712 repCbs.get(i).mCallback.opChanged(code, uid, packageName);
Svet Ganov38536112015-05-19 12:45:52 -0700713 } catch (RemoteException e) {
714 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800715 }
Svet Ganov38536112015-05-19 12:45:52 -0700716 } finally {
717 Binder.restoreCallingIdentity(identity);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800718 }
719 }
720 }
721
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700722 private static HashMap<Callback, ArrayList<ChangeRec>> addCallbacks(
723 HashMap<Callback, ArrayList<ChangeRec>> callbacks,
Dianne Hackborn68d76552017-02-27 15:32:03 -0800724 int op, int uid, String packageName, ArraySet<Callback> cbs) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700725 if (cbs == null) {
726 return callbacks;
727 }
728 if (callbacks == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700729 callbacks = new HashMap<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700730 }
Svet Ganov2af57082015-07-30 08:44:20 -0700731 boolean duplicate = false;
Dianne Hackborn68d76552017-02-27 15:32:03 -0800732 final int N = cbs.size();
733 for (int i=0; i<N; i++) {
734 Callback cb = cbs.valueAt(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700735 ArrayList<ChangeRec> reports = callbacks.get(cb);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700736 if (reports == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700737 reports = new ArrayList<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700738 callbacks.put(cb, reports);
Svet Ganov2af57082015-07-30 08:44:20 -0700739 } else {
740 final int reportCount = reports.size();
741 for (int j = 0; j < reportCount; j++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700742 ChangeRec report = reports.get(j);
743 if (report.op == op && report.pkg.equals(packageName)) {
Svet Ganov2af57082015-07-30 08:44:20 -0700744 duplicate = true;
745 break;
746 }
747 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700748 }
Svet Ganov2af57082015-07-30 08:44:20 -0700749 if (!duplicate) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700750 reports.add(new ChangeRec(op, uid, packageName));
Svet Ganov2af57082015-07-30 08:44:20 -0700751 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700752 }
753 return callbacks;
754 }
755
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700756 static final class ChangeRec {
757 final int op;
758 final int uid;
759 final String pkg;
760
761 ChangeRec(int _op, int _uid, String _pkg) {
762 op = _op;
763 uid = _uid;
764 pkg = _pkg;
765 }
766 }
767
Dianne Hackborn607b4142013-08-02 18:10:10 -0700768 @Override
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800769 public void resetAllModes(int reqUserId, String reqPackageName) {
770 final int callingPid = Binder.getCallingPid();
771 final int callingUid = Binder.getCallingUid();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700772 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800773 callingPid, callingUid, null);
774 reqUserId = ActivityManager.handleIncomingUser(callingPid, callingUid, reqUserId,
775 true, true, "resetAllModes", null);
Svet Ganov2af57082015-07-30 08:44:20 -0700776
777 int reqUid = -1;
778 if (reqPackageName != null) {
779 try {
780 reqUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -0700781 reqPackageName, PackageManager.MATCH_UNINSTALLED_PACKAGES, reqUserId);
Svet Ganov2af57082015-07-30 08:44:20 -0700782 } catch (RemoteException e) {
783 /* ignore - local call */
784 }
785 }
786
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700787 HashMap<Callback, ArrayList<ChangeRec>> callbacks = null;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700788 synchronized (this) {
789 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700790 for (int i = mUidStates.size() - 1; i >= 0; i--) {
791 UidState uidState = mUidStates.valueAt(i);
792
793 SparseIntArray opModes = uidState.opModes;
794 if (opModes != null && (uidState.uid == reqUid || reqUid == -1)) {
795 final int uidOpCount = opModes.size();
796 for (int j = uidOpCount - 1; j >= 0; j--) {
797 final int code = opModes.keyAt(j);
798 if (AppOpsManager.opAllowsReset(code)) {
799 opModes.removeAt(j);
800 if (opModes.size() <= 0) {
801 uidState.opModes = null;
802 }
803 for (String packageName : getPackagesForUid(uidState.uid)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700804 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700805 mOpModeWatchers.get(code));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700806 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700807 mPackageModeWatchers.get(packageName));
808 }
809 }
810 }
811 }
812
813 if (uidState.pkgOps == null) {
814 continue;
815 }
816
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800817 if (reqUserId != UserHandle.USER_ALL
Svet Ganov2af57082015-07-30 08:44:20 -0700818 && reqUserId != UserHandle.getUserId(uidState.uid)) {
Alexandra Gherghinad6a98972014-08-04 17:05:34 +0100819 // Skip any ops for a different user
820 continue;
821 }
Svet Ganov2af57082015-07-30 08:44:20 -0700822
823 Map<String, Ops> packages = uidState.pkgOps;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700824 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
825 while (it.hasNext()) {
826 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700827 String packageName = ent.getKey();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800828 if (reqPackageName != null && !reqPackageName.equals(packageName)) {
829 // Skip any ops for a different package
830 continue;
831 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700832 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700833 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700834 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -0700835 if (AppOpsManager.opAllowsReset(curOp.op)
836 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -0700837 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700838 changed = true;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700839 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -0700840 mOpModeWatchers.get(curOp.op));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700841 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -0700842 mPackageModeWatchers.get(packageName));
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700843 if (curOp.time == 0 && curOp.rejectTime == 0) {
844 pkgOps.removeAt(j);
845 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700846 }
847 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700848 if (pkgOps.size() == 0) {
849 it.remove();
850 }
851 }
Svet Ganov2af57082015-07-30 08:44:20 -0700852 if (uidState.isDefault()) {
853 mUidStates.remove(uidState.uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700854 }
855 }
Svet Ganov2af57082015-07-30 08:44:20 -0700856
Dianne Hackborn607b4142013-08-02 18:10:10 -0700857 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800858 scheduleFastWriteLocked();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700859 }
860 }
861 if (callbacks != null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700862 for (Map.Entry<Callback, ArrayList<ChangeRec>> ent : callbacks.entrySet()) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700863 Callback cb = ent.getKey();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700864 ArrayList<ChangeRec> reports = ent.getValue();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700865 for (int i=0; i<reports.size(); i++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700866 ChangeRec rep = reports.get(i);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700867 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700868 cb.mCallback.opChanged(rep.op, rep.uid, rep.pkg);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700869 } catch (RemoteException e) {
870 }
871 }
872 }
873 }
874 }
875
Dianne Hackbornc2293022013-02-06 23:14:49 -0800876 @Override
877 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -0800878 if (callback == null) {
879 return;
880 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800881 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700882 op = (op != AppOpsManager.OP_NONE) ? AppOpsManager.opToSwitch(op) : op;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800883 Callback cb = mModeWatchers.get(callback.asBinder());
884 if (cb == null) {
885 cb = new Callback(callback);
886 mModeWatchers.put(callback.asBinder(), cb);
887 }
888 if (op != AppOpsManager.OP_NONE) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800889 ArraySet<Callback> cbs = mOpModeWatchers.get(op);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800890 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800891 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800892 mOpModeWatchers.put(op, cbs);
893 }
894 cbs.add(cb);
895 }
896 if (packageName != null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800897 ArraySet<Callback> cbs = mPackageModeWatchers.get(packageName);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800898 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800899 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800900 mPackageModeWatchers.put(packageName, cbs);
901 }
902 cbs.add(cb);
903 }
904 }
905 }
906
907 @Override
908 public void stopWatchingMode(IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -0800909 if (callback == null) {
910 return;
911 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800912 synchronized (this) {
913 Callback cb = mModeWatchers.remove(callback.asBinder());
914 if (cb != null) {
915 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700916 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800917 ArraySet<Callback> cbs = mOpModeWatchers.valueAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800918 cbs.remove(cb);
919 if (cbs.size() <= 0) {
920 mOpModeWatchers.removeAt(i);
921 }
922 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700923 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800924 ArraySet<Callback> cbs = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700925 cbs.remove(cb);
926 if (cbs.size() <= 0) {
927 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800928 }
929 }
930 }
931 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800932 }
933
934 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700935 public IBinder getToken(IBinder clientToken) {
936 synchronized (this) {
937 ClientState cs = mClients.get(clientToken);
938 if (cs == null) {
939 cs = new ClientState(clientToken);
940 mClients.put(clientToken, cs);
941 }
942 return cs;
943 }
944 }
945
946 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800947 public int checkOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800948 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800949 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000950 String resolvedPackageName = resolvePackageName(uid, packageName);
951 if (resolvedPackageName == null) {
952 return AppOpsManager.MODE_IGNORED;
953 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800954 synchronized (this) {
Svet Ganov442ed572016-08-17 17:29:43 -0700955 if (isOpRestrictedLocked(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -0400956 return AppOpsManager.MODE_IGNORED;
957 }
Svet Ganov2af57082015-07-30 08:44:20 -0700958 code = AppOpsManager.opToSwitch(code);
959 UidState uidState = getUidStateLocked(uid, false);
Svet Ganovee438d42017-01-19 18:04:38 -0800960 if (uidState != null && uidState.opModes != null
961 && uidState.opModes.indexOfKey(code) >= 0) {
962 return uidState.opModes.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -0700963 }
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000964 Op op = getOpLocked(code, uid, resolvedPackageName, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800965 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -0700966 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800967 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800968 return op.mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800969 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800970 }
971
972 @Override
John Spurlock7b414672014-07-18 13:02:39 -0400973 public int checkAudioOperation(int code, int usage, int uid, String packageName) {
Andrei Stingaceanuefc4a342016-03-22 14:43:01 +0000974 boolean suspended;
975 try {
976 suspended = isPackageSuspendedForUser(packageName, uid);
977 } catch (IllegalArgumentException ex) {
978 // Package not found.
979 suspended = false;
980 }
981
982 if (suspended) {
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000983 Log.i(TAG, "Audio disabled for suspended package=" + packageName + " for uid=" + uid);
984 return AppOpsManager.MODE_IGNORED;
985 }
986
John Spurlock1af30c72014-03-10 08:33:35 -0400987 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -0400988 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -0400989 if (mode != AppOpsManager.MODE_ALLOWED) {
990 return mode;
991 }
992 }
993 return checkOperation(code, uid, packageName);
994 }
995
Andrei Stingaceanu355b2322016-02-12 16:43:51 +0000996 private boolean isPackageSuspendedForUser(String pkg, int uid) {
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000997 try {
Andrei Stingaceanu355b2322016-02-12 16:43:51 +0000998 return AppGlobals.getPackageManager().isPackageSuspendedForUser(
999 pkg, UserHandle.getUserId(uid));
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001000 } catch (RemoteException re) {
1001 throw new SecurityException("Could not talk to package manager service");
1002 }
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001003 }
1004
John Spurlock7b414672014-07-18 13:02:39 -04001005 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
1006 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1007 if (usageRestrictions != null) {
1008 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001009 if (r != null && !r.exceptionPackages.contains(packageName)) {
1010 return r.mode;
1011 }
1012 }
1013 return AppOpsManager.MODE_ALLOWED;
1014 }
1015
1016 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001017 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -04001018 String[] exceptionPackages) {
1019 verifyIncomingUid(uid);
1020 verifyIncomingOp(code);
1021 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001022 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1023 if (usageRestrictions == null) {
1024 usageRestrictions = new SparseArray<Restriction>();
1025 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -04001026 }
John Spurlock7b414672014-07-18 13:02:39 -04001027 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001028 if (mode != AppOpsManager.MODE_ALLOWED) {
1029 final Restriction r = new Restriction();
1030 r.mode = mode;
1031 if (exceptionPackages != null) {
1032 final int N = exceptionPackages.length;
1033 r.exceptionPackages = new ArraySet<String>(N);
1034 for (int i = 0; i < N; i++) {
1035 final String pkg = exceptionPackages[i];
1036 if (pkg != null) {
1037 r.exceptionPackages.add(pkg.trim());
1038 }
1039 }
1040 }
John Spurlock7b414672014-07-18 13:02:39 -04001041 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -04001042 }
1043 }
Julia Reynoldsbb21c252016-04-05 16:01:49 -04001044 notifyWatchersOfChange(code);
John Spurlock1af30c72014-03-10 08:33:35 -04001045 }
1046
1047 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001048 public int checkPackage(int uid, String packageName) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001049 Preconditions.checkNotNull(packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001050 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001051 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1052 true /* uidMismatchExpected */);
1053 if (ops != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001054 return AppOpsManager.MODE_ALLOWED;
1055 } else {
1056 return AppOpsManager.MODE_ERRORED;
1057 }
1058 }
1059 }
1060
1061 @Override
Svet Ganov99b60432015-06-27 13:15:22 -07001062 public int noteProxyOperation(int code, String proxyPackageName,
1063 int proxiedUid, String proxiedPackageName) {
1064 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001065 final int proxyUid = Binder.getCallingUid();
1066 String resolveProxyPackageName = resolvePackageName(proxyUid, proxyPackageName);
1067 if (resolveProxyPackageName == null) {
1068 return AppOpsManager.MODE_IGNORED;
1069 }
1070 final int proxyMode = noteOperationUnchecked(code, proxyUid,
1071 resolveProxyPackageName, -1, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001072 if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
1073 return proxyMode;
1074 }
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001075 String resolveProxiedPackageName = resolvePackageName(proxiedUid, proxiedPackageName);
1076 if (resolveProxiedPackageName == null) {
1077 return AppOpsManager.MODE_IGNORED;
1078 }
1079 return noteOperationUnchecked(code, proxiedUid, resolveProxiedPackageName,
1080 proxyMode, resolveProxyPackageName);
Svet Ganov99b60432015-06-27 13:15:22 -07001081 }
1082
1083 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001084 public int noteOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001085 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001086 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001087 String resolvedPackageName = resolvePackageName(uid, packageName);
1088 if (resolvedPackageName == null) {
1089 return AppOpsManager.MODE_IGNORED;
1090 }
1091 return noteOperationUnchecked(code, uid, resolvedPackageName, 0, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001092 }
1093
1094 private int noteOperationUnchecked(int code, int uid, String packageName,
1095 int proxyUid, String proxyPackageName) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001096 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001097 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1098 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001099 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001100 if (DEBUG) Log.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
1101 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001102 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001103 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001104 Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07001105 if (isOpRestrictedLocked(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001106 return AppOpsManager.MODE_IGNORED;
1107 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001108 if (op.duration == -1) {
1109 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
1110 + " code " + code + " time=" + op.time + " duration=" + op.duration);
1111 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001112 op.duration = 0;
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001113 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001114 UidState uidState = ops.uidState;
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001115 // If there is a non-default per UID policy (we set UID op mode only if
1116 // non-default) it takes over, otherwise use the per package policy.
1117 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -07001118 final int uidMode = uidState.opModes.get(switchCode);
1119 if (uidMode != AppOpsManager.MODE_ALLOWED) {
1120 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1121 + switchCode + " (" + code + ") uid " + uid + " package "
1122 + packageName);
1123 op.rejectTime = System.currentTimeMillis();
1124 return uidMode;
1125 }
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001126 } else {
1127 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
1128 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
1129 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1130 + switchCode + " (" + code + ") uid " + uid + " package "
1131 + packageName);
1132 op.rejectTime = System.currentTimeMillis();
1133 return switchOp.mode;
1134 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001135 }
1136 if (DEBUG) Log.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
1137 + " package " + packageName);
1138 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001139 op.rejectTime = 0;
Svet Ganov99b60432015-06-27 13:15:22 -07001140 op.proxyUid = proxyUid;
1141 op.proxyPackageName = proxyPackageName;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001142 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001143 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001144 }
1145
1146 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001147 public int startOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001148 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001149 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001150 String resolvedPackageName = resolvePackageName(uid, packageName);
1151 if (resolvedPackageName == null) {
1152 return AppOpsManager.MODE_IGNORED;
1153 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001154 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001155 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001156 Ops ops = getOpsRawLocked(uid, resolvedPackageName, true /* edit */,
1157 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001158 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001159 if (DEBUG) Log.d(TAG, "startOperation: no op for code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001160 + " package " + resolvedPackageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001161 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001162 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001163 Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07001164 if (isOpRestrictedLocked(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001165 return AppOpsManager.MODE_IGNORED;
1166 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001167 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001168 UidState uidState = ops.uidState;
1169 if (uidState.opModes != null) {
1170 final int uidMode = uidState.opModes.get(switchCode);
1171 if (uidMode != AppOpsManager.MODE_ALLOWED) {
1172 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1173 + switchCode + " (" + code + ") uid " + uid + " package "
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001174 + resolvedPackageName);
Svet Ganov2af57082015-07-30 08:44:20 -07001175 op.rejectTime = System.currentTimeMillis();
1176 return uidMode;
1177 }
1178 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001179 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
1180 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
1181 if (DEBUG) Log.d(TAG, "startOperation: reject #" + op.mode + " for code "
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001182 + switchCode + " (" + code + ") uid " + uid + " package "
1183 + resolvedPackageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001184 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001185 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001186 }
1187 if (DEBUG) Log.d(TAG, "startOperation: allowing code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001188 + " package " + resolvedPackageName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001189 if (op.nesting == 0) {
1190 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001191 op.rejectTime = 0;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001192 op.duration = -1;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001193 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001194 op.nesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001195 if (client.mStartedOps != null) {
1196 client.mStartedOps.add(op);
1197 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001198 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001199 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001200 }
1201
1202 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001203 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001204 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001205 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001206 String resolvedPackageName = resolvePackageName(uid, packageName);
1207 if (resolvedPackageName == null) {
1208 return;
1209 }
1210 if (!(token instanceof ClientState)) {
1211 return;
1212 }
1213 ClientState client = (ClientState) token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001214 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001215 Op op = getOpLocked(code, uid, resolvedPackageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001216 if (op == null) {
1217 return;
1218 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001219 if (client.mStartedOps != null) {
1220 if (!client.mStartedOps.remove(op)) {
1221 throw new IllegalStateException("Operation not started: uid" + op.uid
1222 + " pkg=" + op.packageName + " op=" + op.op);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001223 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001224 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001225 finishOperationLocked(op);
1226 }
1227 }
1228
Svet Ganovb9d71a62015-04-30 10:38:13 -07001229 @Override
1230 public int permissionToOpCode(String permission) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001231 if (permission == null) {
1232 return AppOpsManager.OP_NONE;
1233 }
Svet Ganovb9d71a62015-04-30 10:38:13 -07001234 return AppOpsManager.permissionToOpCode(permission);
1235 }
1236
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001237 void finishOperationLocked(Op op) {
1238 if (op.nesting <= 1) {
1239 if (op.nesting == 1) {
1240 op.duration = (int)(System.currentTimeMillis() - op.time);
1241 op.time += op.duration;
1242 } else {
1243 Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
1244 + op.packageName + " code " + op.op + " time=" + op.time
1245 + " duration=" + op.duration + " nesting=" + op.nesting);
1246 }
1247 op.nesting = 0;
1248 } else {
1249 op.nesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001250 }
1251 }
1252
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001253 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001254 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001255 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001256 }
1257 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001258 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001259 }
1260 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
1261 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001262 }
1263
Dianne Hackborn961321f2013-02-05 17:22:41 -08001264 private void verifyIncomingOp(int op) {
1265 if (op >= 0 && op < AppOpsManager._NUM_OP) {
1266 return;
1267 }
1268 throw new IllegalArgumentException("Bad operation #" + op);
1269 }
1270
Svet Ganov2af57082015-07-30 08:44:20 -07001271 private UidState getUidStateLocked(int uid, boolean edit) {
1272 UidState uidState = mUidStates.get(uid);
1273 if (uidState == null) {
1274 if (!edit) {
1275 return null;
1276 }
1277 uidState = new UidState(uid);
1278 mUidStates.put(uid, uidState);
1279 }
1280 return uidState;
1281 }
1282
Yohei Yukawaa965d652017-10-12 15:02:26 -07001283 private Ops getOpsRawLocked(int uid, String packageName, boolean edit,
1284 boolean uidMismatchExpected) {
Svet Ganov2af57082015-07-30 08:44:20 -07001285 UidState uidState = getUidStateLocked(uid, edit);
1286 if (uidState == null) {
1287 return null;
1288 }
1289
1290 if (uidState.pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001291 if (!edit) {
1292 return null;
1293 }
Svet Ganov2af57082015-07-30 08:44:20 -07001294 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001295 }
Svet Ganov2af57082015-07-30 08:44:20 -07001296
1297 Ops ops = uidState.pkgOps.get(packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001298 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001299 if (!edit) {
1300 return null;
1301 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001302 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001303 // This is the first time we have seen this package name under this uid,
1304 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -08001305 if (uid != 0) {
1306 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001307 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001308 int pkgUid = -1;
1309 try {
Jason Monk1c7c3192014-06-26 12:52:18 -04001310 ApplicationInfo appInfo = ActivityThread.getPackageManager()
Jeff Sharkeycd654482016-01-08 17:42:11 -07001311 .getApplicationInfo(packageName,
1312 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1313 UserHandle.getUserId(uid));
Jason Monk1c7c3192014-06-26 12:52:18 -04001314 if (appInfo != null) {
1315 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001316 isPrivileged = (appInfo.privateFlags
1317 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001318 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08001319 pkgUid = resolveUid(packageName);
1320 if (pkgUid >= 0) {
Chien-Yu Chen75cade02016-01-11 10:56:21 -08001321 isPrivileged = false;
Jason Monk1c7c3192014-06-26 12:52:18 -04001322 }
Dianne Hackborn713df152013-05-17 11:27:57 -07001323 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001324 } catch (RemoteException e) {
1325 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001326 }
1327 if (pkgUid != uid) {
1328 // Oops! The package name is not valid for the uid they are calling
1329 // under. Abort.
Yohei Yukawaa965d652017-10-12 15:02:26 -07001330 if (!uidMismatchExpected) {
1331 RuntimeException ex = new RuntimeException("here");
1332 ex.fillInStackTrace();
1333 Slog.w(TAG, "Bad call: specified package " + packageName
1334 + " under uid " + uid + " but it is really " + pkgUid, ex);
1335 }
Dianne Hackborn514074f2013-02-11 10:52:46 -08001336 return null;
1337 }
1338 } finally {
1339 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001340 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001341 }
Svet Ganov2af57082015-07-30 08:44:20 -07001342 ops = new Ops(packageName, uidState, isPrivileged);
1343 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001344 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08001345 return ops;
1346 }
1347
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001348 private void scheduleWriteLocked() {
1349 if (!mWriteScheduled) {
1350 mWriteScheduled = true;
1351 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
1352 }
1353 }
1354
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001355 private void scheduleFastWriteLocked() {
1356 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001357 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001358 mFastWriteScheduled = true;
1359 mHandler.removeCallbacks(mWriteRunner);
1360 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001361 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001362 }
1363
Dianne Hackborn72e39832013-01-18 18:36:09 -08001364 private Op getOpLocked(int code, int uid, String packageName, boolean edit) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001365 Ops ops = getOpsRawLocked(uid, packageName, edit,
1366 false /* uidMismatchExpected */);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001367 if (ops == null) {
1368 return null;
1369 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001370 return getOpLocked(ops, code, edit);
1371 }
1372
1373 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001374 Op op = ops.get(code);
1375 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001376 if (!edit) {
1377 return null;
1378 }
Svet Ganov2af57082015-07-30 08:44:20 -07001379 op = new Op(ops.uidState.uid, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001380 ops.put(code, op);
1381 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001382 if (edit) {
1383 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001384 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001385 return op;
1386 }
1387
Svet Ganov442ed572016-08-17 17:29:43 -07001388 private boolean isOpRestrictedLocked(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04001389 int userHandle = UserHandle.getUserId(uid);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001390 final int restrictionSetCount = mOpUserRestrictions.size();
Ruben Brunk29931bc2016-03-11 00:24:26 -08001391
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001392 for (int i = 0; i < restrictionSetCount; i++) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08001393 // For each client, check that the given op is not restricted, or that the given
1394 // package is exempt from the restriction.
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07001395 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07001396 if (restrictionState.hasRestriction(code, packageName, userHandle)) {
1397 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
1398 // If we are the system, bypass user restrictions for certain codes
1399 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001400 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1401 false /* uidMismatchExpected */);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07001402 if ((ops != null) && ops.isPrivileged) {
1403 return false;
1404 }
Ruben Brunk32f0fa42016-03-11 19:07:07 -08001405 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08001406 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001407 return true;
Jason Monk1c7c3192014-06-26 12:52:18 -04001408 }
Jason Monk62062992014-05-06 09:55:28 -04001409 }
1410 return false;
1411 }
1412
Dianne Hackborn35654b62013-01-14 17:38:02 -08001413 void readState() {
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001414 int oldVersion = NO_VERSION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001415 synchronized (mFile) {
1416 synchronized (this) {
1417 FileInputStream stream;
1418 try {
1419 stream = mFile.openRead();
1420 } catch (FileNotFoundException e) {
1421 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
1422 return;
1423 }
1424 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001425 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001426 try {
1427 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001428 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001429 int type;
1430 while ((type = parser.next()) != XmlPullParser.START_TAG
1431 && type != XmlPullParser.END_DOCUMENT) {
1432 ;
1433 }
1434
1435 if (type != XmlPullParser.START_TAG) {
1436 throw new IllegalStateException("no start tag found");
1437 }
1438
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001439 final String versionString = parser.getAttributeValue(null, "v");
1440 if (versionString != null) {
1441 oldVersion = Integer.parseInt(versionString);
1442 }
1443
Dianne Hackborn35654b62013-01-14 17:38:02 -08001444 int outerDepth = parser.getDepth();
1445 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1446 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1447 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1448 continue;
1449 }
1450
1451 String tagName = parser.getName();
1452 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001453 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07001454 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07001455 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001456 } else {
1457 Slog.w(TAG, "Unknown element under <app-ops>: "
1458 + parser.getName());
1459 XmlUtils.skipCurrentTag(parser);
1460 }
1461 }
1462 success = true;
1463 } catch (IllegalStateException e) {
1464 Slog.w(TAG, "Failed parsing " + e);
1465 } catch (NullPointerException e) {
1466 Slog.w(TAG, "Failed parsing " + e);
1467 } catch (NumberFormatException e) {
1468 Slog.w(TAG, "Failed parsing " + e);
1469 } catch (XmlPullParserException e) {
1470 Slog.w(TAG, "Failed parsing " + e);
1471 } catch (IOException e) {
1472 Slog.w(TAG, "Failed parsing " + e);
1473 } catch (IndexOutOfBoundsException e) {
1474 Slog.w(TAG, "Failed parsing " + e);
1475 } finally {
1476 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07001477 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001478 }
1479 try {
1480 stream.close();
1481 } catch (IOException e) {
1482 }
1483 }
1484 }
1485 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001486 synchronized (this) {
1487 upgradeLocked(oldVersion);
1488 }
1489 }
1490
1491 private void upgradeRunAnyInBackgroundLocked() {
1492 for (int i = 0; i < mUidStates.size(); i++) {
1493 final UidState uidState = mUidStates.valueAt(i);
1494 if (uidState == null) {
1495 continue;
1496 }
1497 if (uidState.opModes != null) {
1498 final int idx = uidState.opModes.indexOfKey(AppOpsManager.OP_RUN_IN_BACKGROUND);
1499 if (idx >= 0) {
1500 uidState.opModes.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND,
1501 uidState.opModes.valueAt(idx));
1502 }
1503 }
1504 if (uidState.pkgOps == null) {
1505 continue;
1506 }
1507 for (int j = 0; j < uidState.pkgOps.size(); j++) {
1508 Ops ops = uidState.pkgOps.valueAt(j);
1509 if (ops != null) {
1510 final Op op = ops.get(AppOpsManager.OP_RUN_IN_BACKGROUND);
1511 if (op != null && op.mode != AppOpsManager.opToDefaultMode(op.op)) {
1512 final Op copy = new Op(op.uid, op.packageName,
1513 AppOpsManager.OP_RUN_ANY_IN_BACKGROUND);
1514 copy.mode = op.mode;
1515 ops.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, copy);
1516 }
1517 }
1518 }
1519 }
1520 }
1521
1522 private void upgradeLocked(int oldVersion) {
1523 if (oldVersion >= CURRENT_VERSION) {
1524 return;
1525 }
1526 Slog.d(TAG, "Upgrading app-ops xml from version " + oldVersion + " to " + CURRENT_VERSION);
1527 switch (oldVersion) {
1528 case NO_VERSION:
1529 upgradeRunAnyInBackgroundLocked();
1530 // fall through
1531 case 1:
1532 // for future upgrades
1533 }
1534 scheduleFastWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001535 }
1536
Svet Ganov2af57082015-07-30 08:44:20 -07001537 void readUidOps(XmlPullParser parser) throws NumberFormatException,
1538 XmlPullParserException, IOException {
1539 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
1540 int outerDepth = parser.getDepth();
1541 int type;
1542 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1543 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1544 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1545 continue;
1546 }
1547
1548 String tagName = parser.getName();
1549 if (tagName.equals("op")) {
1550 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
1551 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
1552 UidState uidState = getUidStateLocked(uid, true);
1553 if (uidState.opModes == null) {
1554 uidState.opModes = new SparseIntArray();
1555 }
1556 uidState.opModes.put(code, mode);
1557 } else {
1558 Slog.w(TAG, "Unknown element under <uid-ops>: "
1559 + parser.getName());
1560 XmlUtils.skipCurrentTag(parser);
1561 }
1562 }
1563 }
1564
Dave Burke0997c5bd2013-08-02 20:25:02 +00001565 void readPackage(XmlPullParser parser) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001566 XmlPullParserException, IOException {
1567 String pkgName = parser.getAttributeValue(null, "n");
1568 int outerDepth = parser.getDepth();
1569 int type;
1570 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1571 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1572 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1573 continue;
1574 }
1575
1576 String tagName = parser.getName();
1577 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001578 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001579 } else {
1580 Slog.w(TAG, "Unknown element under <pkg>: "
1581 + parser.getName());
1582 XmlUtils.skipCurrentTag(parser);
1583 }
1584 }
1585 }
1586
Dave Burke0997c5bd2013-08-02 20:25:02 +00001587 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001588 XmlPullParserException, IOException {
1589 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Jason Monk1c7c3192014-06-26 12:52:18 -04001590 String isPrivilegedString = parser.getAttributeValue(null, "p");
1591 boolean isPrivileged = false;
1592 if (isPrivilegedString == null) {
1593 try {
1594 IPackageManager packageManager = ActivityThread.getPackageManager();
1595 if (packageManager != null) {
1596 ApplicationInfo appInfo = ActivityThread.getPackageManager()
1597 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
1598 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001599 isPrivileged = (appInfo.privateFlags
1600 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001601 }
1602 } else {
1603 // Could not load data, don't add to cache so it will be loaded later.
1604 return;
1605 }
1606 } catch (RemoteException e) {
1607 Slog.w(TAG, "Could not contact PackageManager", e);
1608 }
1609 } else {
1610 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
1611 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001612 int outerDepth = parser.getDepth();
1613 int type;
1614 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1615 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1616 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1617 continue;
1618 }
1619
1620 String tagName = parser.getName();
1621 if (tagName.equals("op")) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001622 Op op = new Op(uid, pkgName, Integer.parseInt(parser.getAttributeValue(null, "n")));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001623 String mode = parser.getAttributeValue(null, "m");
1624 if (mode != null) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001625 op.mode = Integer.parseInt(mode);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001626 }
1627 String time = parser.getAttributeValue(null, "t");
1628 if (time != null) {
1629 op.time = Long.parseLong(time);
1630 }
1631 time = parser.getAttributeValue(null, "r");
1632 if (time != null) {
1633 op.rejectTime = Long.parseLong(time);
1634 }
1635 String dur = parser.getAttributeValue(null, "d");
1636 if (dur != null) {
1637 op.duration = Integer.parseInt(dur);
1638 }
Svet Ganov99b60432015-06-27 13:15:22 -07001639 String proxyUid = parser.getAttributeValue(null, "pu");
1640 if (proxyUid != null) {
1641 op.proxyUid = Integer.parseInt(proxyUid);
1642 }
1643 String proxyPackageName = parser.getAttributeValue(null, "pp");
1644 if (proxyPackageName != null) {
1645 op.proxyPackageName = proxyPackageName;
1646 }
Svet Ganov2af57082015-07-30 08:44:20 -07001647
1648 UidState uidState = getUidStateLocked(uid, true);
1649 if (uidState.pkgOps == null) {
1650 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001651 }
Svet Ganov2af57082015-07-30 08:44:20 -07001652
1653 Ops ops = uidState.pkgOps.get(pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001654 if (ops == null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001655 ops = new Ops(pkgName, uidState, isPrivileged);
1656 uidState.pkgOps.put(pkgName, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001657 }
1658 ops.put(op.op, op);
1659 } else {
1660 Slog.w(TAG, "Unknown element under <pkg>: "
1661 + parser.getName());
1662 XmlUtils.skipCurrentTag(parser);
1663 }
1664 }
1665 }
1666
1667 void writeState() {
1668 synchronized (mFile) {
1669 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
1670
1671 FileOutputStream stream;
1672 try {
1673 stream = mFile.startWrite();
1674 } catch (IOException e) {
1675 Slog.w(TAG, "Failed to write state: " + e);
1676 return;
1677 }
1678
1679 try {
1680 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001681 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001682 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001683 out.startTag(null, "app-ops");
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001684 out.attribute(null, "v", String.valueOf(CURRENT_VERSION));
Svet Ganov2af57082015-07-30 08:44:20 -07001685
1686 final int uidStateCount = mUidStates.size();
1687 for (int i = 0; i < uidStateCount; i++) {
1688 UidState uidState = mUidStates.valueAt(i);
1689 if (uidState.opModes != null && uidState.opModes.size() > 0) {
1690 out.startTag(null, "uid");
1691 out.attribute(null, "n", Integer.toString(uidState.uid));
1692 SparseIntArray uidOpModes = uidState.opModes;
1693 final int opCount = uidOpModes.size();
1694 for (int j = 0; j < opCount; j++) {
1695 final int op = uidOpModes.keyAt(j);
1696 final int mode = uidOpModes.valueAt(j);
1697 out.startTag(null, "op");
1698 out.attribute(null, "n", Integer.toString(op));
1699 out.attribute(null, "m", Integer.toString(mode));
1700 out.endTag(null, "op");
1701 }
1702 out.endTag(null, "uid");
1703 }
1704 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001705
1706 if (allOps != null) {
1707 String lastPkg = null;
1708 for (int i=0; i<allOps.size(); i++) {
1709 AppOpsManager.PackageOps pkg = allOps.get(i);
1710 if (!pkg.getPackageName().equals(lastPkg)) {
1711 if (lastPkg != null) {
1712 out.endTag(null, "pkg");
1713 }
1714 lastPkg = pkg.getPackageName();
1715 out.startTag(null, "pkg");
1716 out.attribute(null, "n", lastPkg);
1717 }
1718 out.startTag(null, "uid");
1719 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04001720 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001721 Ops ops = getOpsRawLocked(pkg.getUid(), pkg.getPackageName(),
1722 false /* edit */, false /* uidMismatchExpected */);
Jason Monk1c7c3192014-06-26 12:52:18 -04001723 // Should always be present as the list of PackageOps is generated
1724 // from Ops.
1725 if (ops != null) {
1726 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
1727 } else {
1728 out.attribute(null, "p", Boolean.toString(false));
1729 }
1730 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001731 List<AppOpsManager.OpEntry> ops = pkg.getOps();
1732 for (int j=0; j<ops.size(); j++) {
1733 AppOpsManager.OpEntry op = ops.get(j);
1734 out.startTag(null, "op");
1735 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07001736 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001737 out.attribute(null, "m", Integer.toString(op.getMode()));
1738 }
1739 long time = op.getTime();
1740 if (time != 0) {
1741 out.attribute(null, "t", Long.toString(time));
1742 }
1743 time = op.getRejectTime();
1744 if (time != 0) {
1745 out.attribute(null, "r", Long.toString(time));
1746 }
1747 int dur = op.getDuration();
1748 if (dur != 0) {
1749 out.attribute(null, "d", Integer.toString(dur));
1750 }
Svet Ganov99b60432015-06-27 13:15:22 -07001751 int proxyUid = op.getProxyUid();
1752 if (proxyUid != -1) {
1753 out.attribute(null, "pu", Integer.toString(proxyUid));
1754 }
1755 String proxyPackageName = op.getProxyPackageName();
1756 if (proxyPackageName != null) {
1757 out.attribute(null, "pp", proxyPackageName);
1758 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001759 out.endTag(null, "op");
1760 }
1761 out.endTag(null, "uid");
1762 }
1763 if (lastPkg != null) {
1764 out.endTag(null, "pkg");
1765 }
1766 }
1767
1768 out.endTag(null, "app-ops");
1769 out.endDocument();
1770 mFile.finishWrite(stream);
1771 } catch (IOException e) {
1772 Slog.w(TAG, "Failed to write state, restoring backup.", e);
1773 mFile.failWrite(stream);
1774 }
1775 }
1776 }
1777
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001778 static class Shell extends ShellCommand {
1779 final IAppOpsService mInterface;
1780 final AppOpsService mInternal;
1781
1782 int userId = UserHandle.USER_SYSTEM;
1783 String packageName;
1784 String opStr;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001785 String modeStr;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001786 int op;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001787 int mode;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001788 int packageUid;
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001789 int nonpackageUid;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001790
1791 Shell(IAppOpsService iface, AppOpsService internal) {
1792 mInterface = iface;
1793 mInternal = internal;
1794 }
1795
1796 @Override
1797 public int onCommand(String cmd) {
1798 return onShellCommand(this, cmd);
1799 }
1800
1801 @Override
1802 public void onHelp() {
1803 PrintWriter pw = getOutPrintWriter();
1804 dumpCommandHelp(pw);
1805 }
1806
1807 private int strOpToOp(String op, PrintWriter err) {
1808 try {
1809 return AppOpsManager.strOpToOp(op);
1810 } catch (IllegalArgumentException e) {
1811 }
1812 try {
1813 return Integer.parseInt(op);
1814 } catch (NumberFormatException e) {
1815 }
1816 try {
1817 return AppOpsManager.strDebugOpToOp(op);
1818 } catch (IllegalArgumentException e) {
1819 err.println("Error: " + e.getMessage());
1820 return -1;
1821 }
1822 }
1823
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001824 int strModeToMode(String modeStr, PrintWriter err) {
1825 switch (modeStr) {
1826 case "allow":
1827 return AppOpsManager.MODE_ALLOWED;
1828 case "deny":
1829 return AppOpsManager.MODE_ERRORED;
1830 case "ignore":
1831 return AppOpsManager.MODE_IGNORED;
1832 case "default":
1833 return AppOpsManager.MODE_DEFAULT;
1834 }
1835 try {
1836 return Integer.parseInt(modeStr);
1837 } catch (NumberFormatException e) {
1838 }
1839 err.println("Error: Mode " + modeStr + " is not valid");
1840 return -1;
1841 }
1842
1843 int parseUserOpMode(int defMode, PrintWriter err) throws RemoteException {
1844 userId = UserHandle.USER_CURRENT;
1845 opStr = null;
1846 modeStr = null;
1847 for (String argument; (argument = getNextArg()) != null;) {
1848 if ("--user".equals(argument)) {
1849 userId = UserHandle.parseUserArg(getNextArgRequired());
1850 } else {
1851 if (opStr == null) {
1852 opStr = argument;
1853 } else if (modeStr == null) {
1854 modeStr = argument;
1855 break;
1856 }
1857 }
1858 }
1859 if (opStr == null) {
1860 err.println("Error: Operation not specified.");
1861 return -1;
1862 }
1863 op = strOpToOp(opStr, err);
1864 if (op < 0) {
1865 return -1;
1866 }
1867 if (modeStr != null) {
1868 if ((mode=strModeToMode(modeStr, err)) < 0) {
1869 return -1;
1870 }
1871 } else {
1872 mode = defMode;
1873 }
1874 return 0;
1875 }
1876
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001877 int parseUserPackageOp(boolean reqOp, PrintWriter err) throws RemoteException {
1878 userId = UserHandle.USER_CURRENT;
1879 packageName = null;
1880 opStr = null;
1881 for (String argument; (argument = getNextArg()) != null;) {
1882 if ("--user".equals(argument)) {
1883 userId = UserHandle.parseUserArg(getNextArgRequired());
1884 } else {
1885 if (packageName == null) {
1886 packageName = argument;
1887 } else if (opStr == null) {
1888 opStr = argument;
1889 break;
1890 }
1891 }
1892 }
1893 if (packageName == null) {
1894 err.println("Error: Package name not specified.");
1895 return -1;
1896 } else if (opStr == null && reqOp) {
1897 err.println("Error: Operation not specified.");
1898 return -1;
1899 }
1900 if (opStr != null) {
1901 op = strOpToOp(opStr, err);
1902 if (op < 0) {
1903 return -1;
1904 }
1905 } else {
1906 op = AppOpsManager.OP_NONE;
1907 }
1908 if (userId == UserHandle.USER_CURRENT) {
1909 userId = ActivityManager.getCurrentUser();
1910 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001911 nonpackageUid = -1;
1912 try {
1913 nonpackageUid = Integer.parseInt(packageName);
1914 } catch (NumberFormatException e) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001915 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001916 if (nonpackageUid == -1 && packageName.length() > 1 && packageName.charAt(0) == 'u'
1917 && packageName.indexOf('.') < 0) {
1918 int i = 1;
1919 while (i < packageName.length() && packageName.charAt(i) >= '0'
1920 && packageName.charAt(i) <= '9') {
1921 i++;
1922 }
1923 if (i > 1 && i < packageName.length()) {
1924 String userStr = packageName.substring(1, i);
1925 try {
1926 int user = Integer.parseInt(userStr);
1927 char type = packageName.charAt(i);
1928 i++;
1929 int startTypeVal = i;
1930 while (i < packageName.length() && packageName.charAt(i) >= '0'
1931 && packageName.charAt(i) <= '9') {
1932 i++;
1933 }
1934 if (i > startTypeVal) {
1935 String typeValStr = packageName.substring(startTypeVal, i);
1936 try {
1937 int typeVal = Integer.parseInt(typeValStr);
1938 if (type == 'a') {
1939 nonpackageUid = UserHandle.getUid(user,
1940 typeVal + Process.FIRST_APPLICATION_UID);
1941 } else if (type == 's') {
1942 nonpackageUid = UserHandle.getUid(user, typeVal);
1943 }
1944 } catch (NumberFormatException e) {
1945 }
1946 }
1947 } catch (NumberFormatException e) {
1948 }
1949 }
1950 }
1951 if (nonpackageUid != -1) {
1952 packageName = null;
1953 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08001954 packageUid = resolveUid(packageName);
1955 if (packageUid < 0) {
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001956 packageUid = AppGlobals.getPackageManager().getPackageUid(packageName,
1957 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
1958 }
1959 if (packageUid < 0) {
1960 err.println("Error: No UID for " + packageName + " in user " + userId);
1961 return -1;
1962 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001963 }
1964 return 0;
1965 }
1966 }
1967
1968 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07001969 FileDescriptor err, String[] args, ShellCallback callback,
1970 ResultReceiver resultReceiver) {
1971 (new Shell(this, this)).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001972 }
1973
1974 static void dumpCommandHelp(PrintWriter pw) {
1975 pw.println("AppOps service (appops) commands:");
1976 pw.println(" help");
1977 pw.println(" Print this help text.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001978 pw.println(" set [--user <USER_ID>] <PACKAGE | UID> <OP> <MODE>");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001979 pw.println(" Set the mode for a particular application and operation.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001980 pw.println(" get [--user <USER_ID>] <PACKAGE | UID> [<OP>]");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001981 pw.println(" Return the mode for a particular application and optional operation.");
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001982 pw.println(" query-op [--user <USER_ID>] <OP> [<MODE>]");
1983 pw.println(" Print all packages that currently have the given op in the given mode.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001984 pw.println(" reset [--user <USER_ID>] [<PACKAGE>]");
1985 pw.println(" Reset the given application or all applications to default modes.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001986 pw.println(" write-settings");
1987 pw.println(" Immediately write pending changes to storage.");
1988 pw.println(" read-settings");
1989 pw.println(" Read the last written settings, replacing current state in RAM.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001990 pw.println(" options:");
1991 pw.println(" <PACKAGE> an Android package name.");
1992 pw.println(" <OP> an AppOps operation.");
1993 pw.println(" <MODE> one of allow, ignore, deny, or default");
1994 pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
1995 pw.println(" specified, the current user is assumed.");
1996 }
1997
1998 static int onShellCommand(Shell shell, String cmd) {
1999 if (cmd == null) {
2000 return shell.handleDefaultCommands(cmd);
2001 }
2002 PrintWriter pw = shell.getOutPrintWriter();
2003 PrintWriter err = shell.getErrPrintWriter();
2004 try {
2005 switch (cmd) {
2006 case "set": {
2007 int res = shell.parseUserPackageOp(true, err);
2008 if (res < 0) {
2009 return res;
2010 }
2011 String modeStr = shell.getNextArg();
2012 if (modeStr == null) {
2013 err.println("Error: Mode not specified.");
2014 return -1;
2015 }
2016
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002017 final int mode = shell.strModeToMode(modeStr, err);
2018 if (mode < 0) {
2019 return -1;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002020 }
2021
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002022 if (shell.packageName != null) {
2023 shell.mInterface.setMode(shell.op, shell.packageUid, shell.packageName,
2024 mode);
2025 } else {
2026 shell.mInterface.setUidMode(shell.op, shell.nonpackageUid, mode);
2027 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002028 return 0;
2029 }
2030 case "get": {
2031 int res = shell.parseUserPackageOp(false, err);
2032 if (res < 0) {
2033 return res;
2034 }
2035
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002036 List<AppOpsManager.PackageOps> ops;
2037 if (shell.packageName != null) {
2038 ops = shell.mInterface.getOpsForPackage(
2039 shell.packageUid, shell.packageName,
2040 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
2041 } else {
2042 ops = shell.mInterface.getUidOps(
2043 shell.nonpackageUid,
2044 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
2045 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002046 if (ops == null || ops.size() <= 0) {
2047 pw.println("No operations.");
Svet Ganov82f09bc2018-01-12 22:08:40 -08002048 if (shell.op > AppOpsManager.OP_NONE && shell.op < AppOpsManager._NUM_OP) {
2049 pw.println("Default mode: " + AppOpsManager.modeToString(
2050 AppOpsManager.opToDefaultMode(shell.op)));
2051 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002052 return 0;
2053 }
2054 final long now = System.currentTimeMillis();
2055 for (int i=0; i<ops.size(); i++) {
2056 List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
2057 for (int j=0; j<entries.size(); j++) {
2058 AppOpsManager.OpEntry ent = entries.get(j);
2059 pw.print(AppOpsManager.opToName(ent.getOp()));
2060 pw.print(": ");
Svet Ganov82f09bc2018-01-12 22:08:40 -08002061 pw.print(AppOpsManager.modeToString(ent.getMode()));
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002062 if (ent.getTime() != 0) {
2063 pw.print("; time=");
2064 TimeUtils.formatDuration(now - ent.getTime(), pw);
2065 pw.print(" ago");
2066 }
2067 if (ent.getRejectTime() != 0) {
2068 pw.print("; rejectTime=");
2069 TimeUtils.formatDuration(now - ent.getRejectTime(), pw);
2070 pw.print(" ago");
2071 }
2072 if (ent.getDuration() == -1) {
2073 pw.print(" (running)");
2074 } else if (ent.getDuration() != 0) {
2075 pw.print("; duration=");
2076 TimeUtils.formatDuration(ent.getDuration(), pw);
2077 }
2078 pw.println();
2079 }
2080 }
2081 return 0;
2082 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002083 case "query-op": {
2084 int res = shell.parseUserOpMode(AppOpsManager.MODE_IGNORED, err);
2085 if (res < 0) {
2086 return res;
2087 }
2088 List<AppOpsManager.PackageOps> ops = shell.mInterface.getPackagesForOps(
2089 new int[] {shell.op});
2090 if (ops == null || ops.size() <= 0) {
2091 pw.println("No operations.");
2092 return 0;
2093 }
2094 for (int i=0; i<ops.size(); i++) {
2095 final AppOpsManager.PackageOps pkg = ops.get(i);
2096 boolean hasMatch = false;
2097 final List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
2098 for (int j=0; j<entries.size(); j++) {
2099 AppOpsManager.OpEntry ent = entries.get(j);
2100 if (ent.getOp() == shell.op && ent.getMode() == shell.mode) {
2101 hasMatch = true;
2102 break;
2103 }
2104 }
2105 if (hasMatch) {
2106 pw.println(pkg.getPackageName());
2107 }
2108 }
2109 return 0;
2110 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002111 case "reset": {
2112 String packageName = null;
2113 int userId = UserHandle.USER_CURRENT;
2114 for (String argument; (argument = shell.getNextArg()) != null;) {
2115 if ("--user".equals(argument)) {
2116 String userStr = shell.getNextArgRequired();
2117 userId = UserHandle.parseUserArg(userStr);
2118 } else {
2119 if (packageName == null) {
2120 packageName = argument;
2121 } else {
2122 err.println("Error: Unsupported argument: " + argument);
2123 return -1;
2124 }
2125 }
2126 }
2127
2128 if (userId == UserHandle.USER_CURRENT) {
2129 userId = ActivityManager.getCurrentUser();
2130 }
2131
2132 shell.mInterface.resetAllModes(userId, packageName);
2133 pw.print("Reset all modes for: ");
2134 if (userId == UserHandle.USER_ALL) {
2135 pw.print("all users");
2136 } else {
2137 pw.print("user "); pw.print(userId);
2138 }
2139 pw.print(", ");
2140 if (packageName == null) {
2141 pw.println("all packages");
2142 } else {
2143 pw.print("package "); pw.println(packageName);
2144 }
2145 return 0;
2146 }
2147 case "write-settings": {
2148 shell.mInternal.mContext.enforcePermission(
2149 android.Manifest.permission.UPDATE_APP_OPS_STATS,
2150 Binder.getCallingPid(), Binder.getCallingUid(), null);
2151 long token = Binder.clearCallingIdentity();
2152 try {
2153 synchronized (shell.mInternal) {
2154 shell.mInternal.mHandler.removeCallbacks(shell.mInternal.mWriteRunner);
2155 }
2156 shell.mInternal.writeState();
2157 pw.println("Current settings written.");
2158 } finally {
2159 Binder.restoreCallingIdentity(token);
2160 }
2161 return 0;
2162 }
2163 case "read-settings": {
2164 shell.mInternal.mContext.enforcePermission(
2165 android.Manifest.permission.UPDATE_APP_OPS_STATS,
2166 Binder.getCallingPid(), Binder.getCallingUid(), null);
2167 long token = Binder.clearCallingIdentity();
2168 try {
2169 shell.mInternal.readState();
2170 pw.println("Last settings read.");
2171 } finally {
2172 Binder.restoreCallingIdentity(token);
2173 }
2174 return 0;
2175 }
2176 default:
2177 return shell.handleDefaultCommands(cmd);
2178 }
2179 } catch (RemoteException e) {
2180 pw.println("Remote exception: " + e);
2181 }
2182 return -1;
2183 }
2184
2185 private void dumpHelp(PrintWriter pw) {
2186 pw.println("AppOps service (appops) dump options:");
2187 pw.println(" none");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002188 }
2189
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002190 @Override
2191 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002192 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002193
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002194 if (args != null) {
2195 for (int i=0; i<args.length; i++) {
2196 String arg = args[i];
2197 if ("-h".equals(arg)) {
2198 dumpHelp(pw);
2199 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07002200 } else if ("-a".equals(arg)) {
2201 // dump all data
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002202 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
2203 pw.println("Unknown option: " + arg);
2204 return;
2205 } else {
2206 pw.println("Unknown command: " + arg);
2207 return;
2208 }
2209 }
2210 }
2211
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002212 synchronized (this) {
2213 pw.println("Current AppOps Service state:");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002214 final long now = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002215 boolean needSep = false;
2216 if (mOpModeWatchers.size() > 0) {
2217 needSep = true;
2218 pw.println(" Op mode watchers:");
2219 for (int i=0; i<mOpModeWatchers.size(); i++) {
2220 pw.print(" Op "); pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
2221 pw.println(":");
Dianne Hackborn68d76552017-02-27 15:32:03 -08002222 ArraySet<Callback> callbacks = mOpModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002223 for (int j=0; j<callbacks.size(); j++) {
2224 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08002225 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002226 }
2227 }
2228 }
2229 if (mPackageModeWatchers.size() > 0) {
2230 needSep = true;
2231 pw.println(" Package mode watchers:");
2232 for (int i=0; i<mPackageModeWatchers.size(); i++) {
2233 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
2234 pw.println(":");
Dianne Hackborn68d76552017-02-27 15:32:03 -08002235 ArraySet<Callback> callbacks = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002236 for (int j=0; j<callbacks.size(); j++) {
2237 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08002238 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002239 }
2240 }
2241 }
2242 if (mModeWatchers.size() > 0) {
2243 needSep = true;
2244 pw.println(" All mode watchers:");
2245 for (int i=0; i<mModeWatchers.size(); i++) {
2246 pw.print(" "); pw.print(mModeWatchers.keyAt(i));
2247 pw.print(" -> "); pw.println(mModeWatchers.valueAt(i));
2248 }
2249 }
2250 if (mClients.size() > 0) {
2251 needSep = true;
2252 pw.println(" Clients:");
2253 for (int i=0; i<mClients.size(); i++) {
2254 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
2255 ClientState cs = mClients.valueAt(i);
2256 pw.print(" "); pw.println(cs);
2257 if (cs.mStartedOps != null && cs.mStartedOps.size() > 0) {
2258 pw.println(" Started ops:");
2259 for (int j=0; j<cs.mStartedOps.size(); j++) {
2260 Op op = cs.mStartedOps.get(j);
2261 pw.print(" "); pw.print("uid="); pw.print(op.uid);
2262 pw.print(" pkg="); pw.print(op.packageName);
2263 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
2264 }
2265 }
2266 }
2267 }
John Spurlock1af30c72014-03-10 08:33:35 -04002268 if (mAudioRestrictions.size() > 0) {
2269 boolean printedHeader = false;
2270 for (int o=0; o<mAudioRestrictions.size(); o++) {
2271 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
2272 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
2273 for (int i=0; i<restrictions.size(); i++) {
2274 if (!printedHeader){
2275 pw.println(" Audio Restrictions:");
2276 printedHeader = true;
2277 needSep = true;
2278 }
John Spurlock7b414672014-07-18 13:02:39 -04002279 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04002280 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04002281 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04002282 Restriction r = restrictions.valueAt(i);
2283 pw.print(": mode="); pw.println(r.mode);
2284 if (!r.exceptionPackages.isEmpty()) {
2285 pw.println(" Exceptions:");
2286 for (int j=0; j<r.exceptionPackages.size(); j++) {
2287 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
2288 }
2289 }
2290 }
2291 }
2292 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002293 if (needSep) {
2294 pw.println();
2295 }
Svet Ganov2af57082015-07-30 08:44:20 -07002296 for (int i=0; i<mUidStates.size(); i++) {
2297 UidState uidState = mUidStates.valueAt(i);
2298
2299 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
Svet Ganovee438d42017-01-19 18:04:38 -08002300 needSep = true;
Svet Ganov2af57082015-07-30 08:44:20 -07002301
2302 SparseIntArray opModes = uidState.opModes;
2303 if (opModes != null) {
2304 final int opModeCount = opModes.size();
2305 for (int j = 0; j < opModeCount; j++) {
2306 final int code = opModes.keyAt(j);
2307 final int mode = opModes.valueAt(j);
2308 pw.print(" "); pw.print(AppOpsManager.opToName(code));
2309 pw.print(": mode="); pw.println(mode);
2310 }
2311 }
2312
2313 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
2314 if (pkgOps == null) {
2315 continue;
2316 }
2317
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002318 for (Ops ops : pkgOps.values()) {
2319 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
2320 for (int j=0; j<ops.size(); j++) {
2321 Op op = ops.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002322 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
2323 pw.print(": mode="); pw.print(op.mode);
2324 if (op.time != 0) {
2325 pw.print("; time="); TimeUtils.formatDuration(now-op.time, pw);
2326 pw.print(" ago");
2327 }
2328 if (op.rejectTime != 0) {
2329 pw.print("; rejectTime="); TimeUtils.formatDuration(now-op.rejectTime, pw);
2330 pw.print(" ago");
2331 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002332 if (op.duration == -1) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002333 pw.print(" (running)");
2334 } else if (op.duration != 0) {
2335 pw.print("; duration="); TimeUtils.formatDuration(op.duration, pw);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002336 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002337 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002338 }
2339 }
2340 }
Svet Ganovee438d42017-01-19 18:04:38 -08002341 if (needSep) {
2342 pw.println();
2343 }
2344
2345 final int userRestrictionCount = mOpUserRestrictions.size();
2346 for (int i = 0; i < userRestrictionCount; i++) {
2347 IBinder token = mOpUserRestrictions.keyAt(i);
2348 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
2349 pw.println(" User restrictions for token " + token + ":");
2350
2351 final int restrictionCount = restrictionState.perUserRestrictions != null
2352 ? restrictionState.perUserRestrictions.size() : 0;
2353 if (restrictionCount > 0) {
2354 pw.println(" Restricted ops:");
2355 for (int j = 0; j < restrictionCount; j++) {
2356 int userId = restrictionState.perUserRestrictions.keyAt(j);
2357 boolean[] restrictedOps = restrictionState.perUserRestrictions.valueAt(j);
2358 if (restrictedOps == null) {
2359 continue;
2360 }
2361 StringBuilder restrictedOpsValue = new StringBuilder();
2362 restrictedOpsValue.append("[");
2363 final int restrictedOpCount = restrictedOps.length;
2364 for (int k = 0; k < restrictedOpCount; k++) {
2365 if (restrictedOps[k]) {
2366 if (restrictedOpsValue.length() > 1) {
2367 restrictedOpsValue.append(", ");
2368 }
2369 restrictedOpsValue.append(AppOpsManager.opToName(k));
2370 }
2371 }
2372 restrictedOpsValue.append("]");
2373 pw.print(" "); pw.print("user: "); pw.print(userId);
2374 pw.print(" restricted ops: "); pw.println(restrictedOpsValue);
2375 }
2376 }
2377
2378 final int excludedPackageCount = restrictionState.perUserExcludedPackages != null
2379 ? restrictionState.perUserExcludedPackages.size() : 0;
2380 if (excludedPackageCount > 0) {
2381 pw.println(" Excluded packages:");
2382 for (int j = 0; j < excludedPackageCount; j++) {
2383 int userId = restrictionState.perUserExcludedPackages.keyAt(j);
2384 String[] packageNames = restrictionState.perUserExcludedPackages.valueAt(j);
2385 pw.print(" "); pw.print("user: "); pw.print(userId);
2386 pw.print(" packages: "); pw.println(Arrays.toString(packageNames));
2387 }
2388 }
2389 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002390 }
2391 }
John Spurlock1af30c72014-03-10 08:33:35 -04002392
2393 private static final class Restriction {
2394 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
2395 int mode;
2396 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
2397 }
Jason Monk62062992014-05-06 09:55:28 -04002398
2399 @Override
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002400 public void setUserRestrictions(Bundle restrictions, IBinder token, int userHandle) {
Jason Monk62062992014-05-06 09:55:28 -04002401 checkSystemUid("setUserRestrictions");
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002402 Preconditions.checkNotNull(restrictions);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002403 Preconditions.checkNotNull(token);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002404 for (int i = 0; i < AppOpsManager._NUM_OP; i++) {
Jason Monk62062992014-05-06 09:55:28 -04002405 String restriction = AppOpsManager.opToRestriction(i);
Suprabh Shukla64e0dcb2016-05-24 16:23:11 -07002406 if (restriction != null) {
2407 setUserRestrictionNoCheck(i, restrictions.getBoolean(restriction, false), token,
2408 userHandle, null);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002409 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002410 }
2411 }
2412
2413 @Override
Ruben Brunk29931bc2016-03-11 00:24:26 -08002414 public void setUserRestriction(int code, boolean restricted, IBinder token, int userHandle,
2415 String[] exceptionPackages) {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002416 if (Binder.getCallingPid() != Process.myPid()) {
2417 mContext.enforcePermission(Manifest.permission.MANAGE_APP_OPS_RESTRICTIONS,
2418 Binder.getCallingPid(), Binder.getCallingUid(), null);
2419 }
2420 if (userHandle != UserHandle.getCallingUserId()) {
2421 if (mContext.checkCallingOrSelfPermission(Manifest.permission
2422 .INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
2423 && mContext.checkCallingOrSelfPermission(Manifest.permission
2424 .INTERACT_ACROSS_USERS) != PackageManager.PERMISSION_GRANTED) {
2425 throw new SecurityException("Need INTERACT_ACROSS_USERS_FULL or"
2426 + " INTERACT_ACROSS_USERS to interact cross user ");
Jason Monk62062992014-05-06 09:55:28 -04002427 }
2428 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002429 verifyIncomingOp(code);
2430 Preconditions.checkNotNull(token);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002431 setUserRestrictionNoCheck(code, restricted, token, userHandle, exceptionPackages);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002432 }
2433
2434 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
Ruben Brunk29931bc2016-03-11 00:24:26 -08002435 int userHandle, String[] exceptionPackages) {
Svet Ganov442ed572016-08-17 17:29:43 -07002436 boolean notifyChange = false;
Ruben Brunk29931bc2016-03-11 00:24:26 -08002437
Svet Ganov442ed572016-08-17 17:29:43 -07002438 synchronized (AppOpsService.this) {
2439 ClientRestrictionState restrictionState = mOpUserRestrictions.get(token);
2440
2441 if (restrictionState == null) {
2442 try {
2443 restrictionState = new ClientRestrictionState(token);
2444 } catch (RemoteException e) {
2445 return;
2446 }
2447 mOpUserRestrictions.put(token, restrictionState);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002448 }
Svet Ganov442ed572016-08-17 17:29:43 -07002449
2450 if (restrictionState.setRestriction(code, restricted, exceptionPackages, userHandle)) {
2451 notifyChange = true;
2452 }
2453
2454 if (restrictionState.isDefault()) {
2455 mOpUserRestrictions.remove(token);
2456 restrictionState.destroy();
2457 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002458 }
2459
Svet Ganov442ed572016-08-17 17:29:43 -07002460 if (notifyChange) {
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002461 notifyWatchersOfChange(code);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002462 }
Julia Reynoldsbb21c252016-04-05 16:01:49 -04002463 }
2464
2465 private void notifyWatchersOfChange(int code) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08002466 final ArraySet<Callback> clonedCallbacks;
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002467 synchronized (this) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08002468 ArraySet<Callback> callbacks = mOpModeWatchers.get(code);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002469 if (callbacks == null) {
2470 return;
2471 }
Dianne Hackborn68d76552017-02-27 15:32:03 -08002472 clonedCallbacks = new ArraySet<>(callbacks);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002473 }
2474
2475 // There are components watching for mode changes such as window manager
2476 // and location manager which are in our process. The callbacks in these
Dianne Hackborn68d76552017-02-27 15:32:03 -08002477 // components may require permissions our remote caller does not have.
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002478 final long identity = Binder.clearCallingIdentity();
2479 try {
2480 final int callbackCount = clonedCallbacks.size();
2481 for (int i = 0; i < callbackCount; i++) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08002482 Callback callback = clonedCallbacks.valueAt(i);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002483 try {
2484 callback.mCallback.opChanged(code, -1, null);
2485 } catch (RemoteException e) {
2486 Log.w(TAG, "Error dispatching op op change", e);
2487 }
2488 }
2489 } finally {
2490 Binder.restoreCallingIdentity(identity);
2491 }
Jason Monk62062992014-05-06 09:55:28 -04002492 }
2493
2494 @Override
2495 public void removeUser(int userHandle) throws RemoteException {
2496 checkSystemUid("removeUser");
Svet Ganov442ed572016-08-17 17:29:43 -07002497 synchronized (AppOpsService.this) {
2498 final int tokenCount = mOpUserRestrictions.size();
2499 for (int i = tokenCount - 1; i >= 0; i--) {
2500 ClientRestrictionState opRestrictions = mOpUserRestrictions.valueAt(i);
2501 opRestrictions.removeUser(userHandle);
2502 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002503 removeUidsForUserLocked(userHandle);
2504 }
2505 }
2506
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002507 @Override
2508 public boolean isOperationActive(int code, int uid, String packageName) {
2509 verifyIncomingUid(uid);
2510 verifyIncomingOp(code);
2511 String resolvedPackageName = resolvePackageName(uid, packageName);
2512 if (resolvedPackageName == null) {
2513 return false;
2514 }
2515 synchronized (this) {
2516 for (int i = mClients.size() - 1; i >= 0; i--) {
2517 final ClientState client = mClients.valueAt(i);
2518 if (client.mStartedOps == null) continue;
2519
2520 for (int j = client.mStartedOps.size() - 1; j >= 0; j--) {
2521 final Op op = client.mStartedOps.get(j);
2522 if (op.op == code && op.uid == uid) return true;
2523 }
2524 }
2525 }
2526 return false;
2527 }
2528
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002529 private void removeUidsForUserLocked(int userHandle) {
2530 for (int i = mUidStates.size() - 1; i >= 0; --i) {
2531 final int uid = mUidStates.keyAt(i);
2532 if (UserHandle.getUserId(uid) == userHandle) {
2533 mUidStates.removeAt(i);
2534 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002535 }
2536 }
2537
Jason Monk62062992014-05-06 09:55:28 -04002538 private void checkSystemUid(String function) {
2539 int uid = Binder.getCallingUid();
2540 if (uid != Process.SYSTEM_UID) {
2541 throw new SecurityException(function + " must by called by the system");
2542 }
2543 }
2544
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002545 private static String resolvePackageName(int uid, String packageName) {
Svet Ganov82f09bc2018-01-12 22:08:40 -08002546 if (uid == Process.ROOT_UID) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002547 return "root";
2548 } else if (uid == Process.SHELL_UID) {
2549 return "com.android.shell";
Svet Ganov82f09bc2018-01-12 22:08:40 -08002550 } else if (uid == Process.MEDIA_UID) {
2551 return "media";
2552 } else if (uid == Process.AUDIOSERVER_UID) {
2553 return "audioserver";
2554 } else if (uid == Process.CAMERASERVER_UID) {
2555 return "cameraserver";
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002556 } else if (uid == Process.SYSTEM_UID && packageName == null) {
2557 return "android";
2558 }
2559 return packageName;
2560 }
2561
Svet Ganov82f09bc2018-01-12 22:08:40 -08002562 private static int resolveUid(String packageName) {
2563 if (packageName == null) {
2564 return -1;
2565 }
2566 switch (packageName) {
2567 case "root":
2568 return Process.ROOT_UID;
2569 case "shell":
2570 return Process.SHELL_UID;
2571 case "media":
2572 return Process.MEDIA_UID;
2573 case "audioserver":
2574 return Process.AUDIOSERVER_UID;
2575 case "cameraserver":
2576 return Process.CAMERASERVER_UID;
2577 }
2578 return -1;
2579 }
2580
Svet Ganov2af57082015-07-30 08:44:20 -07002581 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07002582 String[] packageNames = null;
Svet Ganov2af57082015-07-30 08:44:20 -07002583 try {
riddle_hsu40b300f2015-11-23 13:22:03 +08002584 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -07002585 } catch (RemoteException e) {
2586 /* ignore - local call */
2587 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07002588 if (packageNames == null) {
2589 return EmptyArray.STRING;
2590 }
2591 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07002592 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002593
2594 private final class ClientRestrictionState implements DeathRecipient {
2595 private final IBinder token;
2596 SparseArray<boolean[]> perUserRestrictions;
2597 SparseArray<String[]> perUserExcludedPackages;
2598
2599 public ClientRestrictionState(IBinder token)
2600 throws RemoteException {
2601 token.linkToDeath(this, 0);
2602 this.token = token;
2603 }
2604
2605 public boolean setRestriction(int code, boolean restricted,
2606 String[] excludedPackages, int userId) {
2607 boolean changed = false;
2608
2609 if (perUserRestrictions == null && restricted) {
2610 perUserRestrictions = new SparseArray<>();
2611 }
2612
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002613 int[] users;
2614 if (userId == UserHandle.USER_ALL) {
2615 List<UserInfo> liveUsers = UserManager.get(mContext).getUsers(false);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002616
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002617 users = new int[liveUsers.size()];
2618 for (int i = 0; i < liveUsers.size(); i++) {
2619 users[i] = liveUsers.get(i).id;
2620 }
2621 } else {
2622 users = new int[]{userId};
2623 }
2624
2625 if (perUserRestrictions != null) {
2626 int numUsers = users.length;
2627
2628 for (int i = 0; i < numUsers; i++) {
2629 int thisUserId = users[i];
2630
2631 boolean[] userRestrictions = perUserRestrictions.get(thisUserId);
2632 if (userRestrictions == null && restricted) {
2633 userRestrictions = new boolean[AppOpsManager._NUM_OP];
2634 perUserRestrictions.put(thisUserId, userRestrictions);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002635 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002636 if (userRestrictions != null && userRestrictions[code] != restricted) {
2637 userRestrictions[code] = restricted;
2638 if (!restricted && isDefault(userRestrictions)) {
2639 perUserRestrictions.remove(thisUserId);
2640 userRestrictions = null;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002641 }
2642 changed = true;
2643 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002644
2645 if (userRestrictions != null) {
2646 final boolean noExcludedPackages = ArrayUtils.isEmpty(excludedPackages);
2647 if (perUserExcludedPackages == null && !noExcludedPackages) {
2648 perUserExcludedPackages = new SparseArray<>();
2649 }
2650 if (perUserExcludedPackages != null && !Arrays.equals(excludedPackages,
2651 perUserExcludedPackages.get(thisUserId))) {
2652 if (noExcludedPackages) {
2653 perUserExcludedPackages.remove(thisUserId);
2654 if (perUserExcludedPackages.size() <= 0) {
2655 perUserExcludedPackages = null;
2656 }
2657 } else {
2658 perUserExcludedPackages.put(thisUserId, excludedPackages);
2659 }
2660 changed = true;
2661 }
2662 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002663 }
2664 }
2665
2666 return changed;
2667 }
2668
2669 public boolean hasRestriction(int restriction, String packageName, int userId) {
2670 if (perUserRestrictions == null) {
2671 return false;
2672 }
2673 boolean[] restrictions = perUserRestrictions.get(userId);
2674 if (restrictions == null) {
2675 return false;
2676 }
2677 if (!restrictions[restriction]) {
2678 return false;
2679 }
2680 if (perUserExcludedPackages == null) {
2681 return true;
2682 }
2683 String[] perUserExclusions = perUserExcludedPackages.get(userId);
2684 if (perUserExclusions == null) {
2685 return true;
2686 }
2687 return !ArrayUtils.contains(perUserExclusions, packageName);
2688 }
2689
2690 public void removeUser(int userId) {
2691 if (perUserExcludedPackages != null) {
2692 perUserExcludedPackages.remove(userId);
2693 if (perUserExcludedPackages.size() <= 0) {
2694 perUserExcludedPackages = null;
2695 }
2696 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002697 if (perUserRestrictions != null) {
2698 perUserRestrictions.remove(userId);
2699 if (perUserRestrictions.size() <= 0) {
2700 perUserRestrictions = null;
2701 }
2702 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002703 }
2704
2705 public boolean isDefault() {
2706 return perUserRestrictions == null || perUserRestrictions.size() <= 0;
2707 }
2708
2709 @Override
2710 public void binderDied() {
2711 synchronized (AppOpsService.this) {
2712 mOpUserRestrictions.remove(token);
2713 if (perUserRestrictions == null) {
2714 return;
2715 }
2716 final int userCount = perUserRestrictions.size();
2717 for (int i = 0; i < userCount; i++) {
2718 final boolean[] restrictions = perUserRestrictions.valueAt(i);
2719 final int restrictionCount = restrictions.length;
2720 for (int j = 0; j < restrictionCount; j++) {
2721 if (restrictions[j]) {
2722 final int changedCode = j;
2723 mHandler.post(() -> notifyWatchersOfChange(changedCode));
2724 }
2725 }
2726 }
2727 destroy();
2728 }
2729 }
2730
2731 public void destroy() {
2732 token.unlinkToDeath(this, 0);
2733 }
2734
2735 private boolean isDefault(boolean[] array) {
2736 if (ArrayUtils.isEmpty(array)) {
2737 return true;
2738 }
2739 for (boolean value : array) {
2740 if (value) {
2741 return false;
2742 }
2743 }
2744 return true;
2745 }
2746 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002747}