blob: 4ffa5f1f38f9bd45d1d9495e5ff057415835c293 [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 {
1319 if ("media".equals(packageName)) {
1320 pkgUid = Process.MEDIA_UID;
1321 isPrivileged = false;
Andy Hunged0ea402015-10-30 14:11:46 -07001322 } else if ("audioserver".equals(packageName)) {
1323 pkgUid = Process.AUDIOSERVER_UID;
1324 isPrivileged = false;
Chien-Yu Chen75cade02016-01-11 10:56:21 -08001325 } else if ("cameraserver".equals(packageName)) {
1326 pkgUid = Process.CAMERASERVER_UID;
1327 isPrivileged = false;
Jason Monk1c7c3192014-06-26 12:52:18 -04001328 }
Dianne Hackborn713df152013-05-17 11:27:57 -07001329 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001330 } catch (RemoteException e) {
1331 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001332 }
1333 if (pkgUid != uid) {
1334 // Oops! The package name is not valid for the uid they are calling
1335 // under. Abort.
Yohei Yukawaa965d652017-10-12 15:02:26 -07001336 if (!uidMismatchExpected) {
1337 RuntimeException ex = new RuntimeException("here");
1338 ex.fillInStackTrace();
1339 Slog.w(TAG, "Bad call: specified package " + packageName
1340 + " under uid " + uid + " but it is really " + pkgUid, ex);
1341 }
Dianne Hackborn514074f2013-02-11 10:52:46 -08001342 return null;
1343 }
1344 } finally {
1345 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001346 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001347 }
Svet Ganov2af57082015-07-30 08:44:20 -07001348 ops = new Ops(packageName, uidState, isPrivileged);
1349 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001350 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08001351 return ops;
1352 }
1353
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001354 private void scheduleWriteLocked() {
1355 if (!mWriteScheduled) {
1356 mWriteScheduled = true;
1357 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
1358 }
1359 }
1360
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001361 private void scheduleFastWriteLocked() {
1362 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001363 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001364 mFastWriteScheduled = true;
1365 mHandler.removeCallbacks(mWriteRunner);
1366 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001367 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001368 }
1369
Dianne Hackborn72e39832013-01-18 18:36:09 -08001370 private Op getOpLocked(int code, int uid, String packageName, boolean edit) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001371 Ops ops = getOpsRawLocked(uid, packageName, edit,
1372 false /* uidMismatchExpected */);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001373 if (ops == null) {
1374 return null;
1375 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001376 return getOpLocked(ops, code, edit);
1377 }
1378
1379 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001380 Op op = ops.get(code);
1381 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001382 if (!edit) {
1383 return null;
1384 }
Svet Ganov2af57082015-07-30 08:44:20 -07001385 op = new Op(ops.uidState.uid, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001386 ops.put(code, op);
1387 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001388 if (edit) {
1389 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001390 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001391 return op;
1392 }
1393
Svet Ganov442ed572016-08-17 17:29:43 -07001394 private boolean isOpRestrictedLocked(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04001395 int userHandle = UserHandle.getUserId(uid);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001396 final int restrictionSetCount = mOpUserRestrictions.size();
Ruben Brunk29931bc2016-03-11 00:24:26 -08001397
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001398 for (int i = 0; i < restrictionSetCount; i++) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08001399 // For each client, check that the given op is not restricted, or that the given
1400 // package is exempt from the restriction.
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07001401 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07001402 if (restrictionState.hasRestriction(code, packageName, userHandle)) {
1403 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
1404 // If we are the system, bypass user restrictions for certain codes
1405 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001406 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1407 false /* uidMismatchExpected */);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07001408 if ((ops != null) && ops.isPrivileged) {
1409 return false;
1410 }
Ruben Brunk32f0fa42016-03-11 19:07:07 -08001411 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08001412 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001413 return true;
Jason Monk1c7c3192014-06-26 12:52:18 -04001414 }
Jason Monk62062992014-05-06 09:55:28 -04001415 }
1416 return false;
1417 }
1418
Dianne Hackborn35654b62013-01-14 17:38:02 -08001419 void readState() {
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001420 int oldVersion = NO_VERSION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001421 synchronized (mFile) {
1422 synchronized (this) {
1423 FileInputStream stream;
1424 try {
1425 stream = mFile.openRead();
1426 } catch (FileNotFoundException e) {
1427 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
1428 return;
1429 }
1430 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001431 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001432 try {
1433 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001434 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001435 int type;
1436 while ((type = parser.next()) != XmlPullParser.START_TAG
1437 && type != XmlPullParser.END_DOCUMENT) {
1438 ;
1439 }
1440
1441 if (type != XmlPullParser.START_TAG) {
1442 throw new IllegalStateException("no start tag found");
1443 }
1444
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001445 final String versionString = parser.getAttributeValue(null, "v");
1446 if (versionString != null) {
1447 oldVersion = Integer.parseInt(versionString);
1448 }
1449
Dianne Hackborn35654b62013-01-14 17:38:02 -08001450 int outerDepth = parser.getDepth();
1451 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1452 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1453 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1454 continue;
1455 }
1456
1457 String tagName = parser.getName();
1458 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001459 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07001460 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07001461 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001462 } else {
1463 Slog.w(TAG, "Unknown element under <app-ops>: "
1464 + parser.getName());
1465 XmlUtils.skipCurrentTag(parser);
1466 }
1467 }
1468 success = true;
1469 } catch (IllegalStateException e) {
1470 Slog.w(TAG, "Failed parsing " + e);
1471 } catch (NullPointerException e) {
1472 Slog.w(TAG, "Failed parsing " + e);
1473 } catch (NumberFormatException e) {
1474 Slog.w(TAG, "Failed parsing " + e);
1475 } catch (XmlPullParserException e) {
1476 Slog.w(TAG, "Failed parsing " + e);
1477 } catch (IOException e) {
1478 Slog.w(TAG, "Failed parsing " + e);
1479 } catch (IndexOutOfBoundsException e) {
1480 Slog.w(TAG, "Failed parsing " + e);
1481 } finally {
1482 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07001483 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001484 }
1485 try {
1486 stream.close();
1487 } catch (IOException e) {
1488 }
1489 }
1490 }
1491 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001492 synchronized (this) {
1493 upgradeLocked(oldVersion);
1494 }
1495 }
1496
1497 private void upgradeRunAnyInBackgroundLocked() {
1498 for (int i = 0; i < mUidStates.size(); i++) {
1499 final UidState uidState = mUidStates.valueAt(i);
1500 if (uidState == null) {
1501 continue;
1502 }
1503 if (uidState.opModes != null) {
1504 final int idx = uidState.opModes.indexOfKey(AppOpsManager.OP_RUN_IN_BACKGROUND);
1505 if (idx >= 0) {
1506 uidState.opModes.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND,
1507 uidState.opModes.valueAt(idx));
1508 }
1509 }
1510 if (uidState.pkgOps == null) {
1511 continue;
1512 }
1513 for (int j = 0; j < uidState.pkgOps.size(); j++) {
1514 Ops ops = uidState.pkgOps.valueAt(j);
1515 if (ops != null) {
1516 final Op op = ops.get(AppOpsManager.OP_RUN_IN_BACKGROUND);
1517 if (op != null && op.mode != AppOpsManager.opToDefaultMode(op.op)) {
1518 final Op copy = new Op(op.uid, op.packageName,
1519 AppOpsManager.OP_RUN_ANY_IN_BACKGROUND);
1520 copy.mode = op.mode;
1521 ops.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, copy);
1522 }
1523 }
1524 }
1525 }
1526 }
1527
1528 private void upgradeLocked(int oldVersion) {
1529 if (oldVersion >= CURRENT_VERSION) {
1530 return;
1531 }
1532 Slog.d(TAG, "Upgrading app-ops xml from version " + oldVersion + " to " + CURRENT_VERSION);
1533 switch (oldVersion) {
1534 case NO_VERSION:
1535 upgradeRunAnyInBackgroundLocked();
1536 // fall through
1537 case 1:
1538 // for future upgrades
1539 }
1540 scheduleFastWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001541 }
1542
Svet Ganov2af57082015-07-30 08:44:20 -07001543 void readUidOps(XmlPullParser parser) throws NumberFormatException,
1544 XmlPullParserException, IOException {
1545 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
1546 int outerDepth = parser.getDepth();
1547 int type;
1548 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1549 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1550 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1551 continue;
1552 }
1553
1554 String tagName = parser.getName();
1555 if (tagName.equals("op")) {
1556 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
1557 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
1558 UidState uidState = getUidStateLocked(uid, true);
1559 if (uidState.opModes == null) {
1560 uidState.opModes = new SparseIntArray();
1561 }
1562 uidState.opModes.put(code, mode);
1563 } else {
1564 Slog.w(TAG, "Unknown element under <uid-ops>: "
1565 + parser.getName());
1566 XmlUtils.skipCurrentTag(parser);
1567 }
1568 }
1569 }
1570
Dave Burke0997c5bd2013-08-02 20:25:02 +00001571 void readPackage(XmlPullParser parser) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001572 XmlPullParserException, IOException {
1573 String pkgName = parser.getAttributeValue(null, "n");
1574 int outerDepth = parser.getDepth();
1575 int type;
1576 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1577 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1578 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1579 continue;
1580 }
1581
1582 String tagName = parser.getName();
1583 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001584 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001585 } else {
1586 Slog.w(TAG, "Unknown element under <pkg>: "
1587 + parser.getName());
1588 XmlUtils.skipCurrentTag(parser);
1589 }
1590 }
1591 }
1592
Dave Burke0997c5bd2013-08-02 20:25:02 +00001593 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001594 XmlPullParserException, IOException {
1595 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Jason Monk1c7c3192014-06-26 12:52:18 -04001596 String isPrivilegedString = parser.getAttributeValue(null, "p");
1597 boolean isPrivileged = false;
1598 if (isPrivilegedString == null) {
1599 try {
1600 IPackageManager packageManager = ActivityThread.getPackageManager();
1601 if (packageManager != null) {
1602 ApplicationInfo appInfo = ActivityThread.getPackageManager()
1603 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
1604 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001605 isPrivileged = (appInfo.privateFlags
1606 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001607 }
1608 } else {
1609 // Could not load data, don't add to cache so it will be loaded later.
1610 return;
1611 }
1612 } catch (RemoteException e) {
1613 Slog.w(TAG, "Could not contact PackageManager", e);
1614 }
1615 } else {
1616 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
1617 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001618 int outerDepth = parser.getDepth();
1619 int type;
1620 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1621 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1622 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1623 continue;
1624 }
1625
1626 String tagName = parser.getName();
1627 if (tagName.equals("op")) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001628 Op op = new Op(uid, pkgName, Integer.parseInt(parser.getAttributeValue(null, "n")));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001629 String mode = parser.getAttributeValue(null, "m");
1630 if (mode != null) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001631 op.mode = Integer.parseInt(mode);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001632 }
1633 String time = parser.getAttributeValue(null, "t");
1634 if (time != null) {
1635 op.time = Long.parseLong(time);
1636 }
1637 time = parser.getAttributeValue(null, "r");
1638 if (time != null) {
1639 op.rejectTime = Long.parseLong(time);
1640 }
1641 String dur = parser.getAttributeValue(null, "d");
1642 if (dur != null) {
1643 op.duration = Integer.parseInt(dur);
1644 }
Svet Ganov99b60432015-06-27 13:15:22 -07001645 String proxyUid = parser.getAttributeValue(null, "pu");
1646 if (proxyUid != null) {
1647 op.proxyUid = Integer.parseInt(proxyUid);
1648 }
1649 String proxyPackageName = parser.getAttributeValue(null, "pp");
1650 if (proxyPackageName != null) {
1651 op.proxyPackageName = proxyPackageName;
1652 }
Svet Ganov2af57082015-07-30 08:44:20 -07001653
1654 UidState uidState = getUidStateLocked(uid, true);
1655 if (uidState.pkgOps == null) {
1656 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001657 }
Svet Ganov2af57082015-07-30 08:44:20 -07001658
1659 Ops ops = uidState.pkgOps.get(pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001660 if (ops == null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001661 ops = new Ops(pkgName, uidState, isPrivileged);
1662 uidState.pkgOps.put(pkgName, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001663 }
1664 ops.put(op.op, op);
1665 } else {
1666 Slog.w(TAG, "Unknown element under <pkg>: "
1667 + parser.getName());
1668 XmlUtils.skipCurrentTag(parser);
1669 }
1670 }
1671 }
1672
1673 void writeState() {
1674 synchronized (mFile) {
1675 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
1676
1677 FileOutputStream stream;
1678 try {
1679 stream = mFile.startWrite();
1680 } catch (IOException e) {
1681 Slog.w(TAG, "Failed to write state: " + e);
1682 return;
1683 }
1684
1685 try {
1686 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001687 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001688 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001689 out.startTag(null, "app-ops");
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001690 out.attribute(null, "v", String.valueOf(CURRENT_VERSION));
Svet Ganov2af57082015-07-30 08:44:20 -07001691
1692 final int uidStateCount = mUidStates.size();
1693 for (int i = 0; i < uidStateCount; i++) {
1694 UidState uidState = mUidStates.valueAt(i);
1695 if (uidState.opModes != null && uidState.opModes.size() > 0) {
1696 out.startTag(null, "uid");
1697 out.attribute(null, "n", Integer.toString(uidState.uid));
1698 SparseIntArray uidOpModes = uidState.opModes;
1699 final int opCount = uidOpModes.size();
1700 for (int j = 0; j < opCount; j++) {
1701 final int op = uidOpModes.keyAt(j);
1702 final int mode = uidOpModes.valueAt(j);
1703 out.startTag(null, "op");
1704 out.attribute(null, "n", Integer.toString(op));
1705 out.attribute(null, "m", Integer.toString(mode));
1706 out.endTag(null, "op");
1707 }
1708 out.endTag(null, "uid");
1709 }
1710 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001711
1712 if (allOps != null) {
1713 String lastPkg = null;
1714 for (int i=0; i<allOps.size(); i++) {
1715 AppOpsManager.PackageOps pkg = allOps.get(i);
1716 if (!pkg.getPackageName().equals(lastPkg)) {
1717 if (lastPkg != null) {
1718 out.endTag(null, "pkg");
1719 }
1720 lastPkg = pkg.getPackageName();
1721 out.startTag(null, "pkg");
1722 out.attribute(null, "n", lastPkg);
1723 }
1724 out.startTag(null, "uid");
1725 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04001726 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001727 Ops ops = getOpsRawLocked(pkg.getUid(), pkg.getPackageName(),
1728 false /* edit */, false /* uidMismatchExpected */);
Jason Monk1c7c3192014-06-26 12:52:18 -04001729 // Should always be present as the list of PackageOps is generated
1730 // from Ops.
1731 if (ops != null) {
1732 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
1733 } else {
1734 out.attribute(null, "p", Boolean.toString(false));
1735 }
1736 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001737 List<AppOpsManager.OpEntry> ops = pkg.getOps();
1738 for (int j=0; j<ops.size(); j++) {
1739 AppOpsManager.OpEntry op = ops.get(j);
1740 out.startTag(null, "op");
1741 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07001742 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001743 out.attribute(null, "m", Integer.toString(op.getMode()));
1744 }
1745 long time = op.getTime();
1746 if (time != 0) {
1747 out.attribute(null, "t", Long.toString(time));
1748 }
1749 time = op.getRejectTime();
1750 if (time != 0) {
1751 out.attribute(null, "r", Long.toString(time));
1752 }
1753 int dur = op.getDuration();
1754 if (dur != 0) {
1755 out.attribute(null, "d", Integer.toString(dur));
1756 }
Svet Ganov99b60432015-06-27 13:15:22 -07001757 int proxyUid = op.getProxyUid();
1758 if (proxyUid != -1) {
1759 out.attribute(null, "pu", Integer.toString(proxyUid));
1760 }
1761 String proxyPackageName = op.getProxyPackageName();
1762 if (proxyPackageName != null) {
1763 out.attribute(null, "pp", proxyPackageName);
1764 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001765 out.endTag(null, "op");
1766 }
1767 out.endTag(null, "uid");
1768 }
1769 if (lastPkg != null) {
1770 out.endTag(null, "pkg");
1771 }
1772 }
1773
1774 out.endTag(null, "app-ops");
1775 out.endDocument();
1776 mFile.finishWrite(stream);
1777 } catch (IOException e) {
1778 Slog.w(TAG, "Failed to write state, restoring backup.", e);
1779 mFile.failWrite(stream);
1780 }
1781 }
1782 }
1783
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001784 static class Shell extends ShellCommand {
1785 final IAppOpsService mInterface;
1786 final AppOpsService mInternal;
1787
1788 int userId = UserHandle.USER_SYSTEM;
1789 String packageName;
1790 String opStr;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001791 String modeStr;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001792 int op;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001793 int mode;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001794 int packageUid;
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001795 int nonpackageUid;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001796
1797 Shell(IAppOpsService iface, AppOpsService internal) {
1798 mInterface = iface;
1799 mInternal = internal;
1800 }
1801
1802 @Override
1803 public int onCommand(String cmd) {
1804 return onShellCommand(this, cmd);
1805 }
1806
1807 @Override
1808 public void onHelp() {
1809 PrintWriter pw = getOutPrintWriter();
1810 dumpCommandHelp(pw);
1811 }
1812
1813 private int strOpToOp(String op, PrintWriter err) {
1814 try {
1815 return AppOpsManager.strOpToOp(op);
1816 } catch (IllegalArgumentException e) {
1817 }
1818 try {
1819 return Integer.parseInt(op);
1820 } catch (NumberFormatException e) {
1821 }
1822 try {
1823 return AppOpsManager.strDebugOpToOp(op);
1824 } catch (IllegalArgumentException e) {
1825 err.println("Error: " + e.getMessage());
1826 return -1;
1827 }
1828 }
1829
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001830 int strModeToMode(String modeStr, PrintWriter err) {
1831 switch (modeStr) {
1832 case "allow":
1833 return AppOpsManager.MODE_ALLOWED;
1834 case "deny":
1835 return AppOpsManager.MODE_ERRORED;
1836 case "ignore":
1837 return AppOpsManager.MODE_IGNORED;
1838 case "default":
1839 return AppOpsManager.MODE_DEFAULT;
1840 }
1841 try {
1842 return Integer.parseInt(modeStr);
1843 } catch (NumberFormatException e) {
1844 }
1845 err.println("Error: Mode " + modeStr + " is not valid");
1846 return -1;
1847 }
1848
1849 int parseUserOpMode(int defMode, PrintWriter err) throws RemoteException {
1850 userId = UserHandle.USER_CURRENT;
1851 opStr = null;
1852 modeStr = null;
1853 for (String argument; (argument = getNextArg()) != null;) {
1854 if ("--user".equals(argument)) {
1855 userId = UserHandle.parseUserArg(getNextArgRequired());
1856 } else {
1857 if (opStr == null) {
1858 opStr = argument;
1859 } else if (modeStr == null) {
1860 modeStr = argument;
1861 break;
1862 }
1863 }
1864 }
1865 if (opStr == null) {
1866 err.println("Error: Operation not specified.");
1867 return -1;
1868 }
1869 op = strOpToOp(opStr, err);
1870 if (op < 0) {
1871 return -1;
1872 }
1873 if (modeStr != null) {
1874 if ((mode=strModeToMode(modeStr, err)) < 0) {
1875 return -1;
1876 }
1877 } else {
1878 mode = defMode;
1879 }
1880 return 0;
1881 }
1882
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001883 int parseUserPackageOp(boolean reqOp, PrintWriter err) throws RemoteException {
1884 userId = UserHandle.USER_CURRENT;
1885 packageName = null;
1886 opStr = null;
1887 for (String argument; (argument = getNextArg()) != null;) {
1888 if ("--user".equals(argument)) {
1889 userId = UserHandle.parseUserArg(getNextArgRequired());
1890 } else {
1891 if (packageName == null) {
1892 packageName = argument;
1893 } else if (opStr == null) {
1894 opStr = argument;
1895 break;
1896 }
1897 }
1898 }
1899 if (packageName == null) {
1900 err.println("Error: Package name not specified.");
1901 return -1;
1902 } else if (opStr == null && reqOp) {
1903 err.println("Error: Operation not specified.");
1904 return -1;
1905 }
1906 if (opStr != null) {
1907 op = strOpToOp(opStr, err);
1908 if (op < 0) {
1909 return -1;
1910 }
1911 } else {
1912 op = AppOpsManager.OP_NONE;
1913 }
1914 if (userId == UserHandle.USER_CURRENT) {
1915 userId = ActivityManager.getCurrentUser();
1916 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001917 nonpackageUid = -1;
1918 try {
1919 nonpackageUid = Integer.parseInt(packageName);
1920 } catch (NumberFormatException e) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001921 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001922 if (nonpackageUid == -1 && packageName.length() > 1 && packageName.charAt(0) == 'u'
1923 && packageName.indexOf('.') < 0) {
1924 int i = 1;
1925 while (i < packageName.length() && packageName.charAt(i) >= '0'
1926 && packageName.charAt(i) <= '9') {
1927 i++;
1928 }
1929 if (i > 1 && i < packageName.length()) {
1930 String userStr = packageName.substring(1, i);
1931 try {
1932 int user = Integer.parseInt(userStr);
1933 char type = packageName.charAt(i);
1934 i++;
1935 int startTypeVal = i;
1936 while (i < packageName.length() && packageName.charAt(i) >= '0'
1937 && packageName.charAt(i) <= '9') {
1938 i++;
1939 }
1940 if (i > startTypeVal) {
1941 String typeValStr = packageName.substring(startTypeVal, i);
1942 try {
1943 int typeVal = Integer.parseInt(typeValStr);
1944 if (type == 'a') {
1945 nonpackageUid = UserHandle.getUid(user,
1946 typeVal + Process.FIRST_APPLICATION_UID);
1947 } else if (type == 's') {
1948 nonpackageUid = UserHandle.getUid(user, typeVal);
1949 }
1950 } catch (NumberFormatException e) {
1951 }
1952 }
1953 } catch (NumberFormatException e) {
1954 }
1955 }
1956 }
1957 if (nonpackageUid != -1) {
1958 packageName = null;
1959 } else {
1960 if ("root".equals(packageName)) {
1961 packageUid = 0;
1962 } else {
1963 packageUid = AppGlobals.getPackageManager().getPackageUid(packageName,
1964 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
1965 }
1966 if (packageUid < 0) {
1967 err.println("Error: No UID for " + packageName + " in user " + userId);
1968 return -1;
1969 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001970 }
1971 return 0;
1972 }
1973 }
1974
1975 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07001976 FileDescriptor err, String[] args, ShellCallback callback,
1977 ResultReceiver resultReceiver) {
1978 (new Shell(this, this)).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001979 }
1980
1981 static void dumpCommandHelp(PrintWriter pw) {
1982 pw.println("AppOps service (appops) commands:");
1983 pw.println(" help");
1984 pw.println(" Print this help text.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001985 pw.println(" set [--user <USER_ID>] <PACKAGE | UID> <OP> <MODE>");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001986 pw.println(" Set the mode for a particular application and operation.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001987 pw.println(" get [--user <USER_ID>] <PACKAGE | UID> [<OP>]");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001988 pw.println(" Return the mode for a particular application and optional operation.");
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001989 pw.println(" query-op [--user <USER_ID>] <OP> [<MODE>]");
1990 pw.println(" Print all packages that currently have the given op in the given mode.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001991 pw.println(" reset [--user <USER_ID>] [<PACKAGE>]");
1992 pw.println(" Reset the given application or all applications to default modes.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001993 pw.println(" write-settings");
1994 pw.println(" Immediately write pending changes to storage.");
1995 pw.println(" read-settings");
1996 pw.println(" Read the last written settings, replacing current state in RAM.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001997 pw.println(" options:");
1998 pw.println(" <PACKAGE> an Android package name.");
1999 pw.println(" <OP> an AppOps operation.");
2000 pw.println(" <MODE> one of allow, ignore, deny, or default");
2001 pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
2002 pw.println(" specified, the current user is assumed.");
2003 }
2004
2005 static int onShellCommand(Shell shell, String cmd) {
2006 if (cmd == null) {
2007 return shell.handleDefaultCommands(cmd);
2008 }
2009 PrintWriter pw = shell.getOutPrintWriter();
2010 PrintWriter err = shell.getErrPrintWriter();
2011 try {
2012 switch (cmd) {
2013 case "set": {
2014 int res = shell.parseUserPackageOp(true, err);
2015 if (res < 0) {
2016 return res;
2017 }
2018 String modeStr = shell.getNextArg();
2019 if (modeStr == null) {
2020 err.println("Error: Mode not specified.");
2021 return -1;
2022 }
2023
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002024 final int mode = shell.strModeToMode(modeStr, err);
2025 if (mode < 0) {
2026 return -1;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002027 }
2028
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002029 if (shell.packageName != null) {
2030 shell.mInterface.setMode(shell.op, shell.packageUid, shell.packageName,
2031 mode);
2032 } else {
2033 shell.mInterface.setUidMode(shell.op, shell.nonpackageUid, mode);
2034 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002035 return 0;
2036 }
2037 case "get": {
2038 int res = shell.parseUserPackageOp(false, err);
2039 if (res < 0) {
2040 return res;
2041 }
2042
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002043 List<AppOpsManager.PackageOps> ops;
2044 if (shell.packageName != null) {
2045 ops = shell.mInterface.getOpsForPackage(
2046 shell.packageUid, shell.packageName,
2047 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
2048 } else {
2049 ops = shell.mInterface.getUidOps(
2050 shell.nonpackageUid,
2051 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
2052 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002053 if (ops == null || ops.size() <= 0) {
2054 pw.println("No operations.");
2055 return 0;
2056 }
2057 final long now = System.currentTimeMillis();
2058 for (int i=0; i<ops.size(); i++) {
2059 List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
2060 for (int j=0; j<entries.size(); j++) {
2061 AppOpsManager.OpEntry ent = entries.get(j);
2062 pw.print(AppOpsManager.opToName(ent.getOp()));
2063 pw.print(": ");
2064 switch (ent.getMode()) {
2065 case AppOpsManager.MODE_ALLOWED:
2066 pw.print("allow");
2067 break;
2068 case AppOpsManager.MODE_IGNORED:
2069 pw.print("ignore");
2070 break;
2071 case AppOpsManager.MODE_ERRORED:
2072 pw.print("deny");
2073 break;
2074 case AppOpsManager.MODE_DEFAULT:
2075 pw.print("default");
2076 break;
2077 default:
2078 pw.print("mode=");
2079 pw.print(ent.getMode());
2080 break;
2081 }
2082 if (ent.getTime() != 0) {
2083 pw.print("; time=");
2084 TimeUtils.formatDuration(now - ent.getTime(), pw);
2085 pw.print(" ago");
2086 }
2087 if (ent.getRejectTime() != 0) {
2088 pw.print("; rejectTime=");
2089 TimeUtils.formatDuration(now - ent.getRejectTime(), pw);
2090 pw.print(" ago");
2091 }
2092 if (ent.getDuration() == -1) {
2093 pw.print(" (running)");
2094 } else if (ent.getDuration() != 0) {
2095 pw.print("; duration=");
2096 TimeUtils.formatDuration(ent.getDuration(), pw);
2097 }
2098 pw.println();
2099 }
2100 }
2101 return 0;
2102 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002103 case "query-op": {
2104 int res = shell.parseUserOpMode(AppOpsManager.MODE_IGNORED, err);
2105 if (res < 0) {
2106 return res;
2107 }
2108 List<AppOpsManager.PackageOps> ops = shell.mInterface.getPackagesForOps(
2109 new int[] {shell.op});
2110 if (ops == null || ops.size() <= 0) {
2111 pw.println("No operations.");
2112 return 0;
2113 }
2114 for (int i=0; i<ops.size(); i++) {
2115 final AppOpsManager.PackageOps pkg = ops.get(i);
2116 boolean hasMatch = false;
2117 final List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
2118 for (int j=0; j<entries.size(); j++) {
2119 AppOpsManager.OpEntry ent = entries.get(j);
2120 if (ent.getOp() == shell.op && ent.getMode() == shell.mode) {
2121 hasMatch = true;
2122 break;
2123 }
2124 }
2125 if (hasMatch) {
2126 pw.println(pkg.getPackageName());
2127 }
2128 }
2129 return 0;
2130 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002131 case "reset": {
2132 String packageName = null;
2133 int userId = UserHandle.USER_CURRENT;
2134 for (String argument; (argument = shell.getNextArg()) != null;) {
2135 if ("--user".equals(argument)) {
2136 String userStr = shell.getNextArgRequired();
2137 userId = UserHandle.parseUserArg(userStr);
2138 } else {
2139 if (packageName == null) {
2140 packageName = argument;
2141 } else {
2142 err.println("Error: Unsupported argument: " + argument);
2143 return -1;
2144 }
2145 }
2146 }
2147
2148 if (userId == UserHandle.USER_CURRENT) {
2149 userId = ActivityManager.getCurrentUser();
2150 }
2151
2152 shell.mInterface.resetAllModes(userId, packageName);
2153 pw.print("Reset all modes for: ");
2154 if (userId == UserHandle.USER_ALL) {
2155 pw.print("all users");
2156 } else {
2157 pw.print("user "); pw.print(userId);
2158 }
2159 pw.print(", ");
2160 if (packageName == null) {
2161 pw.println("all packages");
2162 } else {
2163 pw.print("package "); pw.println(packageName);
2164 }
2165 return 0;
2166 }
2167 case "write-settings": {
2168 shell.mInternal.mContext.enforcePermission(
2169 android.Manifest.permission.UPDATE_APP_OPS_STATS,
2170 Binder.getCallingPid(), Binder.getCallingUid(), null);
2171 long token = Binder.clearCallingIdentity();
2172 try {
2173 synchronized (shell.mInternal) {
2174 shell.mInternal.mHandler.removeCallbacks(shell.mInternal.mWriteRunner);
2175 }
2176 shell.mInternal.writeState();
2177 pw.println("Current settings written.");
2178 } finally {
2179 Binder.restoreCallingIdentity(token);
2180 }
2181 return 0;
2182 }
2183 case "read-settings": {
2184 shell.mInternal.mContext.enforcePermission(
2185 android.Manifest.permission.UPDATE_APP_OPS_STATS,
2186 Binder.getCallingPid(), Binder.getCallingUid(), null);
2187 long token = Binder.clearCallingIdentity();
2188 try {
2189 shell.mInternal.readState();
2190 pw.println("Last settings read.");
2191 } finally {
2192 Binder.restoreCallingIdentity(token);
2193 }
2194 return 0;
2195 }
2196 default:
2197 return shell.handleDefaultCommands(cmd);
2198 }
2199 } catch (RemoteException e) {
2200 pw.println("Remote exception: " + e);
2201 }
2202 return -1;
2203 }
2204
2205 private void dumpHelp(PrintWriter pw) {
2206 pw.println("AppOps service (appops) dump options:");
2207 pw.println(" none");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002208 }
2209
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002210 @Override
2211 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002212 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002213
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002214 if (args != null) {
2215 for (int i=0; i<args.length; i++) {
2216 String arg = args[i];
2217 if ("-h".equals(arg)) {
2218 dumpHelp(pw);
2219 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07002220 } else if ("-a".equals(arg)) {
2221 // dump all data
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002222 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
2223 pw.println("Unknown option: " + arg);
2224 return;
2225 } else {
2226 pw.println("Unknown command: " + arg);
2227 return;
2228 }
2229 }
2230 }
2231
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002232 synchronized (this) {
2233 pw.println("Current AppOps Service state:");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002234 final long now = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002235 boolean needSep = false;
2236 if (mOpModeWatchers.size() > 0) {
2237 needSep = true;
2238 pw.println(" Op mode watchers:");
2239 for (int i=0; i<mOpModeWatchers.size(); i++) {
2240 pw.print(" Op "); pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
2241 pw.println(":");
Dianne Hackborn68d76552017-02-27 15:32:03 -08002242 ArraySet<Callback> callbacks = mOpModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002243 for (int j=0; j<callbacks.size(); j++) {
2244 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08002245 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002246 }
2247 }
2248 }
2249 if (mPackageModeWatchers.size() > 0) {
2250 needSep = true;
2251 pw.println(" Package mode watchers:");
2252 for (int i=0; i<mPackageModeWatchers.size(); i++) {
2253 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
2254 pw.println(":");
Dianne Hackborn68d76552017-02-27 15:32:03 -08002255 ArraySet<Callback> callbacks = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002256 for (int j=0; j<callbacks.size(); j++) {
2257 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08002258 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002259 }
2260 }
2261 }
2262 if (mModeWatchers.size() > 0) {
2263 needSep = true;
2264 pw.println(" All mode watchers:");
2265 for (int i=0; i<mModeWatchers.size(); i++) {
2266 pw.print(" "); pw.print(mModeWatchers.keyAt(i));
2267 pw.print(" -> "); pw.println(mModeWatchers.valueAt(i));
2268 }
2269 }
2270 if (mClients.size() > 0) {
2271 needSep = true;
2272 pw.println(" Clients:");
2273 for (int i=0; i<mClients.size(); i++) {
2274 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
2275 ClientState cs = mClients.valueAt(i);
2276 pw.print(" "); pw.println(cs);
2277 if (cs.mStartedOps != null && cs.mStartedOps.size() > 0) {
2278 pw.println(" Started ops:");
2279 for (int j=0; j<cs.mStartedOps.size(); j++) {
2280 Op op = cs.mStartedOps.get(j);
2281 pw.print(" "); pw.print("uid="); pw.print(op.uid);
2282 pw.print(" pkg="); pw.print(op.packageName);
2283 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
2284 }
2285 }
2286 }
2287 }
John Spurlock1af30c72014-03-10 08:33:35 -04002288 if (mAudioRestrictions.size() > 0) {
2289 boolean printedHeader = false;
2290 for (int o=0; o<mAudioRestrictions.size(); o++) {
2291 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
2292 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
2293 for (int i=0; i<restrictions.size(); i++) {
2294 if (!printedHeader){
2295 pw.println(" Audio Restrictions:");
2296 printedHeader = true;
2297 needSep = true;
2298 }
John Spurlock7b414672014-07-18 13:02:39 -04002299 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04002300 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04002301 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04002302 Restriction r = restrictions.valueAt(i);
2303 pw.print(": mode="); pw.println(r.mode);
2304 if (!r.exceptionPackages.isEmpty()) {
2305 pw.println(" Exceptions:");
2306 for (int j=0; j<r.exceptionPackages.size(); j++) {
2307 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
2308 }
2309 }
2310 }
2311 }
2312 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002313 if (needSep) {
2314 pw.println();
2315 }
Svet Ganov2af57082015-07-30 08:44:20 -07002316 for (int i=0; i<mUidStates.size(); i++) {
2317 UidState uidState = mUidStates.valueAt(i);
2318
2319 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
Svet Ganovee438d42017-01-19 18:04:38 -08002320 needSep = true;
Svet Ganov2af57082015-07-30 08:44:20 -07002321
2322 SparseIntArray opModes = uidState.opModes;
2323 if (opModes != null) {
2324 final int opModeCount = opModes.size();
2325 for (int j = 0; j < opModeCount; j++) {
2326 final int code = opModes.keyAt(j);
2327 final int mode = opModes.valueAt(j);
2328 pw.print(" "); pw.print(AppOpsManager.opToName(code));
2329 pw.print(": mode="); pw.println(mode);
2330 }
2331 }
2332
2333 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
2334 if (pkgOps == null) {
2335 continue;
2336 }
2337
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002338 for (Ops ops : pkgOps.values()) {
2339 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
2340 for (int j=0; j<ops.size(); j++) {
2341 Op op = ops.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002342 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
2343 pw.print(": mode="); pw.print(op.mode);
2344 if (op.time != 0) {
2345 pw.print("; time="); TimeUtils.formatDuration(now-op.time, pw);
2346 pw.print(" ago");
2347 }
2348 if (op.rejectTime != 0) {
2349 pw.print("; rejectTime="); TimeUtils.formatDuration(now-op.rejectTime, pw);
2350 pw.print(" ago");
2351 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002352 if (op.duration == -1) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002353 pw.print(" (running)");
2354 } else if (op.duration != 0) {
2355 pw.print("; duration="); TimeUtils.formatDuration(op.duration, pw);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002356 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002357 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002358 }
2359 }
2360 }
Svet Ganovee438d42017-01-19 18:04:38 -08002361 if (needSep) {
2362 pw.println();
2363 }
2364
2365 final int userRestrictionCount = mOpUserRestrictions.size();
2366 for (int i = 0; i < userRestrictionCount; i++) {
2367 IBinder token = mOpUserRestrictions.keyAt(i);
2368 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
2369 pw.println(" User restrictions for token " + token + ":");
2370
2371 final int restrictionCount = restrictionState.perUserRestrictions != null
2372 ? restrictionState.perUserRestrictions.size() : 0;
2373 if (restrictionCount > 0) {
2374 pw.println(" Restricted ops:");
2375 for (int j = 0; j < restrictionCount; j++) {
2376 int userId = restrictionState.perUserRestrictions.keyAt(j);
2377 boolean[] restrictedOps = restrictionState.perUserRestrictions.valueAt(j);
2378 if (restrictedOps == null) {
2379 continue;
2380 }
2381 StringBuilder restrictedOpsValue = new StringBuilder();
2382 restrictedOpsValue.append("[");
2383 final int restrictedOpCount = restrictedOps.length;
2384 for (int k = 0; k < restrictedOpCount; k++) {
2385 if (restrictedOps[k]) {
2386 if (restrictedOpsValue.length() > 1) {
2387 restrictedOpsValue.append(", ");
2388 }
2389 restrictedOpsValue.append(AppOpsManager.opToName(k));
2390 }
2391 }
2392 restrictedOpsValue.append("]");
2393 pw.print(" "); pw.print("user: "); pw.print(userId);
2394 pw.print(" restricted ops: "); pw.println(restrictedOpsValue);
2395 }
2396 }
2397
2398 final int excludedPackageCount = restrictionState.perUserExcludedPackages != null
2399 ? restrictionState.perUserExcludedPackages.size() : 0;
2400 if (excludedPackageCount > 0) {
2401 pw.println(" Excluded packages:");
2402 for (int j = 0; j < excludedPackageCount; j++) {
2403 int userId = restrictionState.perUserExcludedPackages.keyAt(j);
2404 String[] packageNames = restrictionState.perUserExcludedPackages.valueAt(j);
2405 pw.print(" "); pw.print("user: "); pw.print(userId);
2406 pw.print(" packages: "); pw.println(Arrays.toString(packageNames));
2407 }
2408 }
2409 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002410 }
2411 }
John Spurlock1af30c72014-03-10 08:33:35 -04002412
2413 private static final class Restriction {
2414 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
2415 int mode;
2416 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
2417 }
Jason Monk62062992014-05-06 09:55:28 -04002418
2419 @Override
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002420 public void setUserRestrictions(Bundle restrictions, IBinder token, int userHandle) {
Jason Monk62062992014-05-06 09:55:28 -04002421 checkSystemUid("setUserRestrictions");
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002422 Preconditions.checkNotNull(restrictions);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002423 Preconditions.checkNotNull(token);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002424 for (int i = 0; i < AppOpsManager._NUM_OP; i++) {
Jason Monk62062992014-05-06 09:55:28 -04002425 String restriction = AppOpsManager.opToRestriction(i);
Suprabh Shukla64e0dcb2016-05-24 16:23:11 -07002426 if (restriction != null) {
2427 setUserRestrictionNoCheck(i, restrictions.getBoolean(restriction, false), token,
2428 userHandle, null);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002429 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002430 }
2431 }
2432
2433 @Override
Ruben Brunk29931bc2016-03-11 00:24:26 -08002434 public void setUserRestriction(int code, boolean restricted, IBinder token, int userHandle,
2435 String[] exceptionPackages) {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002436 if (Binder.getCallingPid() != Process.myPid()) {
2437 mContext.enforcePermission(Manifest.permission.MANAGE_APP_OPS_RESTRICTIONS,
2438 Binder.getCallingPid(), Binder.getCallingUid(), null);
2439 }
2440 if (userHandle != UserHandle.getCallingUserId()) {
2441 if (mContext.checkCallingOrSelfPermission(Manifest.permission
2442 .INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
2443 && mContext.checkCallingOrSelfPermission(Manifest.permission
2444 .INTERACT_ACROSS_USERS) != PackageManager.PERMISSION_GRANTED) {
2445 throw new SecurityException("Need INTERACT_ACROSS_USERS_FULL or"
2446 + " INTERACT_ACROSS_USERS to interact cross user ");
Jason Monk62062992014-05-06 09:55:28 -04002447 }
2448 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002449 verifyIncomingOp(code);
2450 Preconditions.checkNotNull(token);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002451 setUserRestrictionNoCheck(code, restricted, token, userHandle, exceptionPackages);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002452 }
2453
2454 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
Ruben Brunk29931bc2016-03-11 00:24:26 -08002455 int userHandle, String[] exceptionPackages) {
Svet Ganov442ed572016-08-17 17:29:43 -07002456 boolean notifyChange = false;
Ruben Brunk29931bc2016-03-11 00:24:26 -08002457
Svet Ganov442ed572016-08-17 17:29:43 -07002458 synchronized (AppOpsService.this) {
2459 ClientRestrictionState restrictionState = mOpUserRestrictions.get(token);
2460
2461 if (restrictionState == null) {
2462 try {
2463 restrictionState = new ClientRestrictionState(token);
2464 } catch (RemoteException e) {
2465 return;
2466 }
2467 mOpUserRestrictions.put(token, restrictionState);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002468 }
Svet Ganov442ed572016-08-17 17:29:43 -07002469
2470 if (restrictionState.setRestriction(code, restricted, exceptionPackages, userHandle)) {
2471 notifyChange = true;
2472 }
2473
2474 if (restrictionState.isDefault()) {
2475 mOpUserRestrictions.remove(token);
2476 restrictionState.destroy();
2477 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002478 }
2479
Svet Ganov442ed572016-08-17 17:29:43 -07002480 if (notifyChange) {
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002481 notifyWatchersOfChange(code);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002482 }
Julia Reynoldsbb21c252016-04-05 16:01:49 -04002483 }
2484
2485 private void notifyWatchersOfChange(int code) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08002486 final ArraySet<Callback> clonedCallbacks;
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002487 synchronized (this) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08002488 ArraySet<Callback> callbacks = mOpModeWatchers.get(code);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002489 if (callbacks == null) {
2490 return;
2491 }
Dianne Hackborn68d76552017-02-27 15:32:03 -08002492 clonedCallbacks = new ArraySet<>(callbacks);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002493 }
2494
2495 // There are components watching for mode changes such as window manager
2496 // and location manager which are in our process. The callbacks in these
Dianne Hackborn68d76552017-02-27 15:32:03 -08002497 // components may require permissions our remote caller does not have.
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002498 final long identity = Binder.clearCallingIdentity();
2499 try {
2500 final int callbackCount = clonedCallbacks.size();
2501 for (int i = 0; i < callbackCount; i++) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08002502 Callback callback = clonedCallbacks.valueAt(i);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002503 try {
2504 callback.mCallback.opChanged(code, -1, null);
2505 } catch (RemoteException e) {
2506 Log.w(TAG, "Error dispatching op op change", e);
2507 }
2508 }
2509 } finally {
2510 Binder.restoreCallingIdentity(identity);
2511 }
Jason Monk62062992014-05-06 09:55:28 -04002512 }
2513
2514 @Override
2515 public void removeUser(int userHandle) throws RemoteException {
2516 checkSystemUid("removeUser");
Svet Ganov442ed572016-08-17 17:29:43 -07002517 synchronized (AppOpsService.this) {
2518 final int tokenCount = mOpUserRestrictions.size();
2519 for (int i = tokenCount - 1; i >= 0; i--) {
2520 ClientRestrictionState opRestrictions = mOpUserRestrictions.valueAt(i);
2521 opRestrictions.removeUser(userHandle);
2522 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002523 removeUidsForUserLocked(userHandle);
2524 }
2525 }
2526
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002527 @Override
2528 public boolean isOperationActive(int code, int uid, String packageName) {
2529 verifyIncomingUid(uid);
2530 verifyIncomingOp(code);
2531 String resolvedPackageName = resolvePackageName(uid, packageName);
2532 if (resolvedPackageName == null) {
2533 return false;
2534 }
2535 synchronized (this) {
2536 for (int i = mClients.size() - 1; i >= 0; i--) {
2537 final ClientState client = mClients.valueAt(i);
2538 if (client.mStartedOps == null) continue;
2539
2540 for (int j = client.mStartedOps.size() - 1; j >= 0; j--) {
2541 final Op op = client.mStartedOps.get(j);
2542 if (op.op == code && op.uid == uid) return true;
2543 }
2544 }
2545 }
2546 return false;
2547 }
2548
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002549 private void removeUidsForUserLocked(int userHandle) {
2550 for (int i = mUidStates.size() - 1; i >= 0; --i) {
2551 final int uid = mUidStates.keyAt(i);
2552 if (UserHandle.getUserId(uid) == userHandle) {
2553 mUidStates.removeAt(i);
2554 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002555 }
2556 }
2557
Jason Monk62062992014-05-06 09:55:28 -04002558 private void checkSystemUid(String function) {
2559 int uid = Binder.getCallingUid();
2560 if (uid != Process.SYSTEM_UID) {
2561 throw new SecurityException(function + " must by called by the system");
2562 }
2563 }
2564
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002565 private static String resolvePackageName(int uid, String packageName) {
2566 if (uid == 0) {
2567 return "root";
2568 } else if (uid == Process.SHELL_UID) {
2569 return "com.android.shell";
2570 } else if (uid == Process.SYSTEM_UID && packageName == null) {
2571 return "android";
2572 }
2573 return packageName;
2574 }
2575
Svet Ganov2af57082015-07-30 08:44:20 -07002576 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07002577 String[] packageNames = null;
Svet Ganov2af57082015-07-30 08:44:20 -07002578 try {
riddle_hsu40b300f2015-11-23 13:22:03 +08002579 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -07002580 } catch (RemoteException e) {
2581 /* ignore - local call */
2582 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07002583 if (packageNames == null) {
2584 return EmptyArray.STRING;
2585 }
2586 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07002587 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002588
2589 private final class ClientRestrictionState implements DeathRecipient {
2590 private final IBinder token;
2591 SparseArray<boolean[]> perUserRestrictions;
2592 SparseArray<String[]> perUserExcludedPackages;
2593
2594 public ClientRestrictionState(IBinder token)
2595 throws RemoteException {
2596 token.linkToDeath(this, 0);
2597 this.token = token;
2598 }
2599
2600 public boolean setRestriction(int code, boolean restricted,
2601 String[] excludedPackages, int userId) {
2602 boolean changed = false;
2603
2604 if (perUserRestrictions == null && restricted) {
2605 perUserRestrictions = new SparseArray<>();
2606 }
2607
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002608 int[] users;
2609 if (userId == UserHandle.USER_ALL) {
2610 List<UserInfo> liveUsers = UserManager.get(mContext).getUsers(false);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002611
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002612 users = new int[liveUsers.size()];
2613 for (int i = 0; i < liveUsers.size(); i++) {
2614 users[i] = liveUsers.get(i).id;
2615 }
2616 } else {
2617 users = new int[]{userId};
2618 }
2619
2620 if (perUserRestrictions != null) {
2621 int numUsers = users.length;
2622
2623 for (int i = 0; i < numUsers; i++) {
2624 int thisUserId = users[i];
2625
2626 boolean[] userRestrictions = perUserRestrictions.get(thisUserId);
2627 if (userRestrictions == null && restricted) {
2628 userRestrictions = new boolean[AppOpsManager._NUM_OP];
2629 perUserRestrictions.put(thisUserId, userRestrictions);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002630 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002631 if (userRestrictions != null && userRestrictions[code] != restricted) {
2632 userRestrictions[code] = restricted;
2633 if (!restricted && isDefault(userRestrictions)) {
2634 perUserRestrictions.remove(thisUserId);
2635 userRestrictions = null;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002636 }
2637 changed = true;
2638 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002639
2640 if (userRestrictions != null) {
2641 final boolean noExcludedPackages = ArrayUtils.isEmpty(excludedPackages);
2642 if (perUserExcludedPackages == null && !noExcludedPackages) {
2643 perUserExcludedPackages = new SparseArray<>();
2644 }
2645 if (perUserExcludedPackages != null && !Arrays.equals(excludedPackages,
2646 perUserExcludedPackages.get(thisUserId))) {
2647 if (noExcludedPackages) {
2648 perUserExcludedPackages.remove(thisUserId);
2649 if (perUserExcludedPackages.size() <= 0) {
2650 perUserExcludedPackages = null;
2651 }
2652 } else {
2653 perUserExcludedPackages.put(thisUserId, excludedPackages);
2654 }
2655 changed = true;
2656 }
2657 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002658 }
2659 }
2660
2661 return changed;
2662 }
2663
2664 public boolean hasRestriction(int restriction, String packageName, int userId) {
2665 if (perUserRestrictions == null) {
2666 return false;
2667 }
2668 boolean[] restrictions = perUserRestrictions.get(userId);
2669 if (restrictions == null) {
2670 return false;
2671 }
2672 if (!restrictions[restriction]) {
2673 return false;
2674 }
2675 if (perUserExcludedPackages == null) {
2676 return true;
2677 }
2678 String[] perUserExclusions = perUserExcludedPackages.get(userId);
2679 if (perUserExclusions == null) {
2680 return true;
2681 }
2682 return !ArrayUtils.contains(perUserExclusions, packageName);
2683 }
2684
2685 public void removeUser(int userId) {
2686 if (perUserExcludedPackages != null) {
2687 perUserExcludedPackages.remove(userId);
2688 if (perUserExcludedPackages.size() <= 0) {
2689 perUserExcludedPackages = null;
2690 }
2691 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002692 if (perUserRestrictions != null) {
2693 perUserRestrictions.remove(userId);
2694 if (perUserRestrictions.size() <= 0) {
2695 perUserRestrictions = null;
2696 }
2697 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002698 }
2699
2700 public boolean isDefault() {
2701 return perUserRestrictions == null || perUserRestrictions.size() <= 0;
2702 }
2703
2704 @Override
2705 public void binderDied() {
2706 synchronized (AppOpsService.this) {
2707 mOpUserRestrictions.remove(token);
2708 if (perUserRestrictions == null) {
2709 return;
2710 }
2711 final int userCount = perUserRestrictions.size();
2712 for (int i = 0; i < userCount; i++) {
2713 final boolean[] restrictions = perUserRestrictions.valueAt(i);
2714 final int restrictionCount = restrictions.length;
2715 for (int j = 0; j < restrictionCount; j++) {
2716 if (restrictions[j]) {
2717 final int changedCode = j;
2718 mHandler.post(() -> notifyWatchersOfChange(changedCode));
2719 }
2720 }
2721 }
2722 destroy();
2723 }
2724 }
2725
2726 public void destroy() {
2727 token.unlinkToDeath(this, 0);
2728 }
2729
2730 private boolean isDefault(boolean[] array) {
2731 if (ArrayUtils.isEmpty(array)) {
2732 return true;
2733 }
2734 for (boolean value : array) {
2735 if (value) {
2736 return false;
2737 }
2738 }
2739 return true;
2740 }
2741 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002742}