blob: a2f676b8953d80022a9a4a4f7afc6682a962a0d7 [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;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070048import android.util.Slog;
49import android.util.SparseArray;
50import android.util.SparseIntArray;
51import android.util.TimeUtils;
52import android.util.Xml;
53
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070054import com.android.internal.annotations.VisibleForTesting;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -080055import com.android.internal.app.IAppOpsActiveCallback;
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;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -080064import com.android.internal.util.function.pooled.PooledLambda;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -050065
Philip P. Moltmanne683f192017-06-23 14:05:04 -070066import libcore.util.EmptyArray;
67
68import org.xmlpull.v1.XmlPullParser;
69import org.xmlpull.v1.XmlPullParserException;
70import org.xmlpull.v1.XmlSerializer;
71
Dianne Hackborna06de0f2012-12-11 16:34:47 -080072import java.io.File;
73import java.io.FileDescriptor;
Dianne Hackborn35654b62013-01-14 17:38:02 -080074import java.io.FileInputStream;
75import java.io.FileNotFoundException;
76import java.io.FileOutputStream;
77import java.io.IOException;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080078import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010079import java.nio.charset.StandardCharsets;
Dianne Hackborn35654b62013-01-14 17:38:02 -080080import java.util.ArrayList;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -070081import java.util.Arrays;
Svetoslav215b44a2015-08-04 19:03:40 -070082import java.util.Collections;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080083import java.util.HashMap;
Dianne Hackbornc2293022013-02-06 23:14:49 -080084import java.util.Iterator;
Dianne Hackborn35654b62013-01-14 17:38:02 -080085import java.util.List;
Dianne Hackborn607b4142013-08-02 18:10:10 -070086import java.util.Map;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080087
Dianne Hackborna06de0f2012-12-11 16:34:47 -080088public class AppOpsService extends IAppOpsService.Stub {
89 static final String TAG = "AppOps";
Dianne Hackborn35654b62013-01-14 17:38:02 -080090 static final boolean DEBUG = false;
91
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070092 private static final int NO_VERSION = -1;
93 /** Increment by one every time and add the corresponding upgrade logic in
94 * {@link #upgradeLocked(int)} below. The first version was 1 */
95 private static final int CURRENT_VERSION = 1;
96
Dianne Hackborn35654b62013-01-14 17:38:02 -080097 // Write at most every 30 minutes.
98 static final long WRITE_DELAY = DEBUG ? 1000 : 30*60*1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080099
100 Context mContext;
101 final AtomicFile mFile;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800102 final Handler mHandler;
103
104 boolean mWriteScheduled;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800105 boolean mFastWriteScheduled;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800106 final Runnable mWriteRunner = new Runnable() {
107 public void run() {
108 synchronized (AppOpsService.this) {
109 mWriteScheduled = false;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800110 mFastWriteScheduled = false;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800111 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
112 @Override protected Void doInBackground(Void... params) {
113 writeState();
114 return null;
115 }
116 };
117 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
118 }
119 }
120 };
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800121
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700122 @VisibleForTesting
123 final SparseArray<UidState> mUidStates = new SparseArray<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800124
Ruben Brunk29931bc2016-03-11 00:24:26 -0800125 /*
126 * These are app op restrictions imposed per user from various parties.
Ruben Brunk29931bc2016-03-11 00:24:26 -0800127 */
Svetoslav Ganova8bbd762016-05-13 17:08:16 -0700128 private final ArrayMap<IBinder, ClientRestrictionState> mOpUserRestrictions = new ArrayMap<>();
Jason Monk62062992014-05-06 09:55:28 -0400129
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700130 @VisibleForTesting
131 static final class UidState {
Svet Ganov2af57082015-07-30 08:44:20 -0700132 public final int uid;
133 public ArrayMap<String, Ops> pkgOps;
134 public SparseIntArray opModes;
135
136 public UidState(int uid) {
137 this.uid = uid;
138 }
139
140 public void clear() {
141 pkgOps = null;
142 opModes = null;
143 }
144
145 public boolean isDefault() {
146 return (pkgOps == null || pkgOps.isEmpty())
147 && (opModes == null || opModes.size() <= 0);
148 }
149 }
150
Dianne Hackbornc2293022013-02-06 23:14:49 -0800151 public final static class Ops extends SparseArray<Op> {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800152 public final String packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700153 public final UidState uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400154 public final boolean isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800155
Svet Ganov2af57082015-07-30 08:44:20 -0700156 public Ops(String _packageName, UidState _uidState, boolean _isPrivileged) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800157 packageName = _packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700158 uidState = _uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400159 isPrivileged = _isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800160 }
161 }
162
Dianne Hackbornc2293022013-02-06 23:14:49 -0800163 public final static class Op {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700164 public final int uid;
165 public final String packageName;
Svet Ganov99b60432015-06-27 13:15:22 -0700166 public int proxyUid = -1;
167 public String proxyPackageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800168 public final int op;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800169 public int mode;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800170 public int duration;
171 public long time;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800172 public long rejectTime;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800173 public int nesting;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800174
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700175 public Op(int _uid, String _packageName, int _op) {
176 uid = _uid;
177 packageName = _packageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800178 op = _op;
David Braunf5d83192013-09-16 13:43:51 -0700179 mode = AppOpsManager.opToDefaultMode(op);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800180 }
181 }
182
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800183 final SparseArray<ArraySet<ModeCallback>> mOpModeWatchers = new SparseArray<>();
184 final ArrayMap<String, ArraySet<ModeCallback>> mPackageModeWatchers = new ArrayMap<>();
185 final ArrayMap<IBinder, ModeCallback> mModeWatchers = new ArrayMap<>();
186 final ArrayMap<IBinder, SparseArray<ActiveCallback>> mActiveWatchers = new ArrayMap<>();
Dianne Hackborn68d76552017-02-27 15:32:03 -0800187 final SparseArray<SparseArray<Restriction>> mAudioRestrictions = new SparseArray<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800188
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800189 public final class ModeCallback implements DeathRecipient {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800190 final IAppOpsCallback mCallback;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800191 final int mUid;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800192
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800193 public ModeCallback(IAppOpsCallback callback, int uid) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800194 mCallback = callback;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800195 mUid = uid;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800196 try {
197 mCallback.asBinder().linkToDeath(this, 0);
198 } catch (RemoteException e) {
199 }
200 }
201
202 public void unlinkToDeath() {
203 mCallback.asBinder().unlinkToDeath(this, 0);
204 }
205
206 @Override
207 public void binderDied() {
208 stopWatchingMode(mCallback);
209 }
210 }
211
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800212 public final class ActiveCallback implements DeathRecipient {
213 final IAppOpsActiveCallback mCallback;
Svet Ganovf7b47252018-02-26 11:11:27 -0800214 final int mUid;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800215
Svet Ganovf7b47252018-02-26 11:11:27 -0800216 public ActiveCallback(IAppOpsActiveCallback callback, int uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800217 mCallback = callback;
Svet Ganovf7b47252018-02-26 11:11:27 -0800218 mUid = uid;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800219 try {
220 mCallback.asBinder().linkToDeath(this, 0);
221 } catch (RemoteException e) {
222 }
223 }
224
225 public void destroy() {
226 mCallback.asBinder().unlinkToDeath(this, 0);
227 }
228
229 @Override
230 public void binderDied() {
231 stopWatchingActive(mCallback);
232 }
233 }
234
Svet Ganova7a0db62018-02-27 20:08:01 -0800235 final ArrayMap<IBinder, ClientState> mClients = new ArrayMap<>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700236
237 public final class ClientState extends Binder implements DeathRecipient {
Svet Ganovf7b47252018-02-26 11:11:27 -0800238 final ArrayList<Op> mStartedOps = new ArrayList<>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700239 final IBinder mAppToken;
240 final int mPid;
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700241
242 public ClientState(IBinder appToken) {
243 mAppToken = appToken;
244 mPid = Binder.getCallingPid();
Svet Ganovf7b47252018-02-26 11:11:27 -0800245 // Watch only for remote processes dying
246 if (!(appToken instanceof Binder)) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700247 try {
248 mAppToken.linkToDeath(this, 0);
249 } catch (RemoteException e) {
Svet Ganovf7b47252018-02-26 11:11:27 -0800250 /* do nothing */
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700251 }
252 }
253 }
254
255 @Override
256 public String toString() {
257 return "ClientState{" +
258 "mAppToken=" + mAppToken +
Svet Ganovf7b47252018-02-26 11:11:27 -0800259 ", " + "pid=" + mPid +
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700260 '}';
261 }
262
263 @Override
264 public void binderDied() {
265 synchronized (AppOpsService.this) {
266 for (int i=mStartedOps.size()-1; i>=0; i--) {
Svet Ganova7a0db62018-02-27 20:08:01 -0800267 finishOperationLocked(mStartedOps.get(i), /*finishNested*/ true);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700268 }
269 mClients.remove(mAppToken);
270 }
271 }
272 }
273
Jeff Brown6f357d32014-01-15 20:40:55 -0800274 public AppOpsService(File storagePath, Handler handler) {
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600275 LockGuard.installLock(this, LockGuard.INDEX_APP_OPS);
Dianne Hackborne17b4452018-01-10 13:15:40 -0800276 mFile = new AtomicFile(storagePath, "appops");
Jeff Brown6f357d32014-01-15 20:40:55 -0800277 mHandler = handler;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800278 readState();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800279 }
David Braunf5d83192013-09-16 13:43:51 -0700280
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800281 public void publish(Context context) {
282 mContext = context;
283 ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
284 }
285
Dianne Hackborn514074f2013-02-11 10:52:46 -0800286 public void systemReady() {
287 synchronized (this) {
288 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700289 for (int i = mUidStates.size() - 1; i >= 0; i--) {
290 UidState uidState = mUidStates.valueAt(i);
291
292 String[] packageNames = getPackagesForUid(uidState.uid);
293 if (ArrayUtils.isEmpty(packageNames)) {
294 uidState.clear();
295 mUidStates.removeAt(i);
296 changed = true;
297 continue;
298 }
299
300 ArrayMap<String, Ops> pkgs = uidState.pkgOps;
301 if (pkgs == null) {
302 continue;
303 }
304
Dianne Hackborn514074f2013-02-11 10:52:46 -0800305 Iterator<Ops> it = pkgs.values().iterator();
306 while (it.hasNext()) {
307 Ops ops = it.next();
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700308 int curUid = -1;
Dianne Hackborn514074f2013-02-11 10:52:46 -0800309 try {
Jeff Sharkeycd654482016-01-08 17:42:11 -0700310 curUid = AppGlobals.getPackageManager().getPackageUid(ops.packageName,
311 PackageManager.MATCH_UNINSTALLED_PACKAGES,
Svet Ganov2af57082015-07-30 08:44:20 -0700312 UserHandle.getUserId(ops.uidState.uid));
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700313 } catch (RemoteException ignored) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800314 }
Svet Ganov2af57082015-07-30 08:44:20 -0700315 if (curUid != ops.uidState.uid) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800316 Slog.i(TAG, "Pruning old package " + ops.packageName
Svet Ganov2af57082015-07-30 08:44:20 -0700317 + "/" + ops.uidState + ": new uid=" + curUid);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800318 it.remove();
319 changed = true;
320 }
321 }
Svet Ganov2af57082015-07-30 08:44:20 -0700322
323 if (uidState.isDefault()) {
324 mUidStates.removeAt(i);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800325 }
326 }
327 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800328 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800329 }
330 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700331
Suprabh Shuklaaef25132017-01-23 18:09:03 -0800332 PackageManagerInternal packageManagerInternal = LocalServices.getService(
333 PackageManagerInternal.class);
334 packageManagerInternal.setExternalSourcesPolicy(
335 new PackageManagerInternal.ExternalSourcesPolicy() {
336 @Override
337 public int getPackageTrustedToInstallApps(String packageName, int uid) {
338 int appOpMode = checkOperation(AppOpsManager.OP_REQUEST_INSTALL_PACKAGES,
339 uid, packageName);
340 switch (appOpMode) {
341 case AppOpsManager.MODE_ALLOWED:
342 return PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
343 case AppOpsManager.MODE_ERRORED:
344 return PackageManagerInternal.ExternalSourcesPolicy.USER_BLOCKED;
345 default:
346 return PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT;
347 }
348 }
349 });
350
Sudheer Shanka2250d562016-11-07 15:41:02 -0800351 StorageManagerInternal storageManagerInternal = LocalServices.getService(
352 StorageManagerInternal.class);
353 storageManagerInternal.addExternalStoragePolicy(
354 new StorageManagerInternal.ExternalStorageMountPolicy() {
Svet Ganov6ee871e2015-07-10 14:29:33 -0700355 @Override
356 public int getMountMode(int uid, String packageName) {
357 if (Process.isIsolated(uid)) {
358 return Zygote.MOUNT_EXTERNAL_NONE;
359 }
360 if (noteOperation(AppOpsManager.OP_READ_EXTERNAL_STORAGE, uid,
361 packageName) != AppOpsManager.MODE_ALLOWED) {
362 return Zygote.MOUNT_EXTERNAL_NONE;
363 }
364 if (noteOperation(AppOpsManager.OP_WRITE_EXTERNAL_STORAGE, uid,
365 packageName) != AppOpsManager.MODE_ALLOWED) {
366 return Zygote.MOUNT_EXTERNAL_READ;
367 }
368 return Zygote.MOUNT_EXTERNAL_WRITE;
369 }
370
371 @Override
372 public boolean hasExternalStorage(int uid, String packageName) {
373 final int mountMode = getMountMode(uid, packageName);
374 return mountMode == Zygote.MOUNT_EXTERNAL_READ
375 || mountMode == Zygote.MOUNT_EXTERNAL_WRITE;
376 }
377 });
Dianne Hackborn514074f2013-02-11 10:52:46 -0800378 }
379
380 public void packageRemoved(int uid, String packageName) {
381 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700382 UidState uidState = mUidStates.get(uid);
383 if (uidState == null) {
384 return;
385 }
386
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800387 Ops ops = null;
Svet Ganov2af57082015-07-30 08:44:20 -0700388
389 // Remove any package state if such.
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800390 if (uidState.pkgOps != null) {
391 ops = uidState.pkgOps.remove(packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700392 }
393
394 // If we just nuked the last package state check if the UID is valid.
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800395 if (ops != null && uidState.pkgOps.isEmpty()
Svet Ganov2af57082015-07-30 08:44:20 -0700396 && getPackagesForUid(uid).length <= 0) {
397 mUidStates.remove(uid);
398 }
399
Svet Ganova7a0db62018-02-27 20:08:01 -0800400 // Finish ops other packages started on behalf of the package.
401 final int clientCount = mClients.size();
402 for (int i = 0; i < clientCount; i++) {
403 final ClientState client = mClients.valueAt(i);
404 if (client.mStartedOps == null) {
405 continue;
406 }
407 final int opCount = client.mStartedOps.size();
408 for (int j = opCount - 1; j >= 0; j--) {
409 final Op op = client.mStartedOps.get(j);
410 if (uid == op.uid && packageName.equals(op.packageName)) {
411 finishOperationLocked(op, /*finishNested*/ true);
412 client.mStartedOps.remove(j);
413 if (op.nesting <= 0) {
414 scheduleOpActiveChangedIfNeededLocked(op.op,
415 uid, packageName, false);
416 }
417 }
418 }
419 }
420
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800421 if (ops != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700422 scheduleFastWriteLocked();
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800423
424 final int opCount = ops.size();
425 for (int i = 0; i < opCount; i++) {
426 final Op op = ops.valueAt(i);
427 if (op.duration == -1) {
428 scheduleOpActiveChangedIfNeededLocked(
429 op.op, op.uid, op.packageName, false);
430 }
431 }
Dianne Hackborn514074f2013-02-11 10:52:46 -0800432 }
433 }
434 }
435
436 public void uidRemoved(int uid) {
437 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700438 if (mUidStates.indexOfKey(uid) >= 0) {
439 mUidStates.remove(uid);
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800440 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800441 }
442 }
443 }
444
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800445 public void shutdown() {
446 Slog.w(TAG, "Writing app ops before shutdown...");
Dianne Hackborn35654b62013-01-14 17:38:02 -0800447 boolean doWrite = false;
448 synchronized (this) {
449 if (mWriteScheduled) {
450 mWriteScheduled = false;
451 doWrite = true;
452 }
453 }
454 if (doWrite) {
455 writeState();
456 }
457 }
458
Dianne Hackborn72e39832013-01-18 18:36:09 -0800459 private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
460 ArrayList<AppOpsManager.OpEntry> resOps = null;
461 if (ops == null) {
462 resOps = new ArrayList<AppOpsManager.OpEntry>();
463 for (int j=0; j<pkgOps.size(); j++) {
464 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800465 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Svet Ganov99b60432015-06-27 13:15:22 -0700466 curOp.rejectTime, curOp.duration, curOp.proxyUid,
467 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800468 }
469 } else {
470 for (int j=0; j<ops.length; j++) {
471 Op curOp = pkgOps.get(ops[j]);
472 if (curOp != null) {
473 if (resOps == null) {
474 resOps = new ArrayList<AppOpsManager.OpEntry>();
475 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800476 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Svet Ganov99b60432015-06-27 13:15:22 -0700477 curOp.rejectTime, curOp.duration, curOp.proxyUid,
478 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800479 }
480 }
481 }
482 return resOps;
483 }
484
Dianne Hackbornc7214a32017-04-11 13:32:47 -0700485 private ArrayList<AppOpsManager.OpEntry> collectOps(SparseIntArray uidOps, int[] ops) {
486 ArrayList<AppOpsManager.OpEntry> resOps = null;
487 if (ops == null) {
488 resOps = new ArrayList<>();
489 for (int j=0; j<uidOps.size(); j++) {
490 resOps.add(new AppOpsManager.OpEntry(uidOps.keyAt(j), uidOps.valueAt(j),
491 0, 0, 0, -1, null));
492 }
493 } else {
494 for (int j=0; j<ops.length; j++) {
495 int index = uidOps.indexOfKey(ops[j]);
496 if (index >= 0) {
497 if (resOps == null) {
498 resOps = new ArrayList<>();
499 }
500 resOps.add(new AppOpsManager.OpEntry(uidOps.keyAt(index), uidOps.valueAt(index),
501 0, 0, 0, -1, null));
502 }
503 }
504 }
505 return resOps;
506 }
507
Dianne Hackborn35654b62013-01-14 17:38:02 -0800508 @Override
509 public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
510 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
511 Binder.getCallingPid(), Binder.getCallingUid(), null);
512 ArrayList<AppOpsManager.PackageOps> res = null;
513 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700514 final int uidStateCount = mUidStates.size();
515 for (int i = 0; i < uidStateCount; i++) {
516 UidState uidState = mUidStates.valueAt(i);
517 if (uidState.pkgOps == null || uidState.pkgOps.isEmpty()) {
518 continue;
519 }
520 ArrayMap<String, Ops> packages = uidState.pkgOps;
521 final int packageCount = packages.size();
522 for (int j = 0; j < packageCount; j++) {
523 Ops pkgOps = packages.valueAt(j);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800524 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800525 if (resOps != null) {
526 if (res == null) {
527 res = new ArrayList<AppOpsManager.PackageOps>();
528 }
529 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700530 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800531 res.add(resPackage);
532 }
533 }
534 }
535 }
536 return res;
537 }
538
539 @Override
Dianne Hackborn72e39832013-01-18 18:36:09 -0800540 public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
541 int[] ops) {
542 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
543 Binder.getCallingPid(), Binder.getCallingUid(), null);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000544 String resolvedPackageName = resolvePackageName(uid, packageName);
545 if (resolvedPackageName == null) {
546 return Collections.emptyList();
547 }
Dianne Hackborn72e39832013-01-18 18:36:09 -0800548 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -0700549 Ops pkgOps = getOpsRawLocked(uid, resolvedPackageName, false /* edit */,
550 false /* uidMismatchExpected */);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800551 if (pkgOps == null) {
552 return null;
553 }
554 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
555 if (resOps == null) {
556 return null;
557 }
558 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
559 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700560 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800561 res.add(resPackage);
562 return res;
563 }
564 }
565
Dianne Hackbornc7214a32017-04-11 13:32:47 -0700566 @Override
567 public List<AppOpsManager.PackageOps> getUidOps(int uid, int[] ops) {
568 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
569 Binder.getCallingPid(), Binder.getCallingUid(), null);
570 synchronized (this) {
571 UidState uidState = getUidStateLocked(uid, false);
572 if (uidState == null) {
573 return null;
574 }
575 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(uidState.opModes, ops);
576 if (resOps == null) {
577 return null;
578 }
579 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
580 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
581 null, uidState.uid, resOps);
582 res.add(resPackage);
583 return res;
584 }
585 }
586
Dianne Hackborn607b4142013-08-02 18:10:10 -0700587 private void pruneOp(Op op, int uid, String packageName) {
588 if (op.time == 0 && op.rejectTime == 0) {
Yohei Yukawaa965d652017-10-12 15:02:26 -0700589 Ops ops = getOpsRawLocked(uid, packageName, false /* edit */,
590 false /* uidMismatchExpected */);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700591 if (ops != null) {
592 ops.remove(op.op);
593 if (ops.size() <= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -0700594 UidState uidState = ops.uidState;
595 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700596 if (pkgOps != null) {
597 pkgOps.remove(ops.packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700598 if (pkgOps.isEmpty()) {
599 uidState.pkgOps = null;
600 }
601 if (uidState.isDefault()) {
602 mUidStates.remove(uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700603 }
604 }
605 }
606 }
607 }
608 }
609
Dianne Hackborn72e39832013-01-18 18:36:09 -0800610 @Override
Svet Ganov2af57082015-07-30 08:44:20 -0700611 public void setUidMode(int code, int uid, int mode) {
612 if (Binder.getCallingPid() != Process.myPid()) {
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -0800613 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
Svet Ganov2af57082015-07-30 08:44:20 -0700614 Binder.getCallingPid(), Binder.getCallingUid(), null);
615 }
616 verifyIncomingOp(code);
617 code = AppOpsManager.opToSwitch(code);
618
619 synchronized (this) {
620 final int defaultMode = AppOpsManager.opToDefaultMode(code);
621
622 UidState uidState = getUidStateLocked(uid, false);
623 if (uidState == null) {
624 if (mode == defaultMode) {
625 return;
626 }
627 uidState = new UidState(uid);
628 uidState.opModes = new SparseIntArray();
629 uidState.opModes.put(code, mode);
630 mUidStates.put(uid, uidState);
631 scheduleWriteLocked();
632 } else if (uidState.opModes == null) {
633 if (mode != defaultMode) {
634 uidState.opModes = new SparseIntArray();
635 uidState.opModes.put(code, mode);
636 scheduleWriteLocked();
637 }
638 } else {
639 if (uidState.opModes.get(code) == mode) {
640 return;
641 }
642 if (mode == defaultMode) {
643 uidState.opModes.delete(code);
644 if (uidState.opModes.size() <= 0) {
645 uidState.opModes = null;
646 }
647 } else {
648 uidState.opModes.put(code, mode);
649 }
650 scheduleWriteLocked();
651 }
652 }
653
Svetoslav215b44a2015-08-04 19:03:40 -0700654 String[] uidPackageNames = getPackagesForUid(uid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800655 ArrayMap<ModeCallback, ArraySet<String>> callbackSpecs = null;
Svet Ganov2af57082015-07-30 08:44:20 -0700656
riddle_hsu40b300f2015-11-23 13:22:03 +0800657 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800658 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -0700659 if (callbacks != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700660 final int callbackCount = callbacks.size();
661 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800662 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +0800663 ArraySet<String> changedPackages = new ArraySet<>();
664 Collections.addAll(changedPackages, uidPackageNames);
665 callbackSpecs = new ArrayMap<>();
666 callbackSpecs.put(callback, changedPackages);
667 }
668 }
669
670 for (String uidPackageName : uidPackageNames) {
671 callbacks = mPackageModeWatchers.get(uidPackageName);
672 if (callbacks != null) {
673 if (callbackSpecs == null) {
674 callbackSpecs = new ArrayMap<>();
Svet Ganov2af57082015-07-30 08:44:20 -0700675 }
riddle_hsu40b300f2015-11-23 13:22:03 +0800676 final int callbackCount = callbacks.size();
677 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800678 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +0800679 ArraySet<String> changedPackages = callbackSpecs.get(callback);
680 if (changedPackages == null) {
681 changedPackages = new ArraySet<>();
682 callbackSpecs.put(callback, changedPackages);
683 }
684 changedPackages.add(uidPackageName);
685 }
Svet Ganov2af57082015-07-30 08:44:20 -0700686 }
687 }
688 }
689
690 if (callbackSpecs == null) {
691 return;
692 }
693
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800694 for (int i = 0; i < callbackSpecs.size(); i++) {
695 final ModeCallback callback = callbackSpecs.keyAt(i);
696 final ArraySet<String> reportedPackageNames = callbackSpecs.valueAt(i);
697 if (reportedPackageNames == null) {
698 mHandler.sendMessage(PooledLambda.obtainMessage(
699 AppOpsService::notifyOpChanged,
700 this, callback, code, uid, (String) null));
701
702 } else {
703 final int reportedPackageCount = reportedPackageNames.size();
704 for (int j = 0; j < reportedPackageCount; j++) {
705 final String reportedPackageName = reportedPackageNames.valueAt(j);
706 mHandler.sendMessage(PooledLambda.obtainMessage(
707 AppOpsService::notifyOpChanged,
708 this, callback, code, uid, reportedPackageName));
Svet Ganov2af57082015-07-30 08:44:20 -0700709 }
710 }
Svet Ganov2af57082015-07-30 08:44:20 -0700711 }
712 }
713
714 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800715 public void setMode(int code, int uid, String packageName, int mode) {
Dianne Hackbornb64afe12014-07-22 16:29:04 -0700716 if (Binder.getCallingPid() != Process.myPid()) {
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -0800717 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
Dianne Hackbornb64afe12014-07-22 16:29:04 -0700718 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborn133b9df2014-07-01 13:06:10 -0700719 }
Dianne Hackborn961321f2013-02-05 17:22:41 -0800720 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800721 ArraySet<ModeCallback> repCbs = null;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800722 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800723 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700724 UidState uidState = getUidStateLocked(uid, false);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800725 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800726 if (op != null) {
727 if (op.mode != mode) {
728 op.mode = mode;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800729 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800730 if (cbs != null) {
731 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800732 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800733 }
734 repCbs.addAll(cbs);
735 }
736 cbs = mPackageModeWatchers.get(packageName);
737 if (cbs != null) {
738 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800739 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800740 }
741 repCbs.addAll(cbs);
742 }
David Braunf5d83192013-09-16 13:43:51 -0700743 if (mode == AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800744 // If going into the default mode, prune this op
745 // if there is nothing else interesting in it.
Dianne Hackborn607b4142013-08-02 18:10:10 -0700746 pruneOp(op, uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800747 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800748 scheduleFastWriteLocked();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800749 }
750 }
751 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800752 if (repCbs != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800753 mHandler.sendMessage(PooledLambda.obtainMessage(
754 AppOpsService::notifyOpChanged,
755 this, repCbs, code, uid, packageName));
Dianne Hackbornc2293022013-02-06 23:14:49 -0800756 }
757 }
758
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800759 private void notifyOpChanged(ArraySet<ModeCallback> callbacks, int code,
760 int uid, String packageName) {
761 for (int i = 0; i < callbacks.size(); i++) {
762 final ModeCallback callback = callbacks.valueAt(i);
763 notifyOpChanged(callback, code, uid, packageName);
764 }
765 }
766
767 private void notifyOpChanged(ModeCallback callback, int code,
768 int uid, String packageName) {
769 if (callback.mUid >= 0 && callback.mUid != uid) {
770 return;
771 }
772 // There are components watching for mode changes such as window manager
773 // and location manager which are in our process. The callbacks in these
774 // components may require permissions our remote caller does not have.
775 final long identity = Binder.clearCallingIdentity();
776 try {
777 callback.mCallback.opChanged(code, uid, packageName);
778 } catch (RemoteException e) {
779 /* ignore */
780 } finally {
781 Binder.restoreCallingIdentity(identity);
782 }
783 }
784
785 private static HashMap<ModeCallback, ArrayList<ChangeRec>> addCallbacks(
786 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks,
787 int op, int uid, String packageName, ArraySet<ModeCallback> cbs) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700788 if (cbs == null) {
789 return callbacks;
790 }
791 if (callbacks == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700792 callbacks = new HashMap<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700793 }
Svet Ganov2af57082015-07-30 08:44:20 -0700794 boolean duplicate = false;
Dianne Hackborn68d76552017-02-27 15:32:03 -0800795 final int N = cbs.size();
796 for (int i=0; i<N; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800797 ModeCallback cb = cbs.valueAt(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700798 ArrayList<ChangeRec> reports = callbacks.get(cb);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700799 if (reports == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700800 reports = new ArrayList<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700801 callbacks.put(cb, reports);
Svet Ganov2af57082015-07-30 08:44:20 -0700802 } else {
803 final int reportCount = reports.size();
804 for (int j = 0; j < reportCount; j++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700805 ChangeRec report = reports.get(j);
806 if (report.op == op && report.pkg.equals(packageName)) {
Svet Ganov2af57082015-07-30 08:44:20 -0700807 duplicate = true;
808 break;
809 }
810 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700811 }
Svet Ganov2af57082015-07-30 08:44:20 -0700812 if (!duplicate) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700813 reports.add(new ChangeRec(op, uid, packageName));
Svet Ganov2af57082015-07-30 08:44:20 -0700814 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700815 }
816 return callbacks;
817 }
818
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700819 static final class ChangeRec {
820 final int op;
821 final int uid;
822 final String pkg;
823
824 ChangeRec(int _op, int _uid, String _pkg) {
825 op = _op;
826 uid = _uid;
827 pkg = _pkg;
828 }
829 }
830
Dianne Hackborn607b4142013-08-02 18:10:10 -0700831 @Override
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800832 public void resetAllModes(int reqUserId, String reqPackageName) {
833 final int callingPid = Binder.getCallingPid();
834 final int callingUid = Binder.getCallingUid();
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -0800835 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800836 callingPid, callingUid, null);
837 reqUserId = ActivityManager.handleIncomingUser(callingPid, callingUid, reqUserId,
838 true, true, "resetAllModes", null);
Svet Ganov2af57082015-07-30 08:44:20 -0700839
840 int reqUid = -1;
841 if (reqPackageName != null) {
842 try {
843 reqUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -0700844 reqPackageName, PackageManager.MATCH_UNINSTALLED_PACKAGES, reqUserId);
Svet Ganov2af57082015-07-30 08:44:20 -0700845 } catch (RemoteException e) {
846 /* ignore - local call */
847 }
848 }
849
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800850 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks = null;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700851 synchronized (this) {
852 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700853 for (int i = mUidStates.size() - 1; i >= 0; i--) {
854 UidState uidState = mUidStates.valueAt(i);
855
856 SparseIntArray opModes = uidState.opModes;
857 if (opModes != null && (uidState.uid == reqUid || reqUid == -1)) {
858 final int uidOpCount = opModes.size();
859 for (int j = uidOpCount - 1; j >= 0; j--) {
860 final int code = opModes.keyAt(j);
861 if (AppOpsManager.opAllowsReset(code)) {
862 opModes.removeAt(j);
863 if (opModes.size() <= 0) {
864 uidState.opModes = null;
865 }
866 for (String packageName : getPackagesForUid(uidState.uid)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700867 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700868 mOpModeWatchers.get(code));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700869 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700870 mPackageModeWatchers.get(packageName));
871 }
872 }
873 }
874 }
875
876 if (uidState.pkgOps == null) {
877 continue;
878 }
879
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800880 if (reqUserId != UserHandle.USER_ALL
Svet Ganov2af57082015-07-30 08:44:20 -0700881 && reqUserId != UserHandle.getUserId(uidState.uid)) {
Alexandra Gherghinad6a98972014-08-04 17:05:34 +0100882 // Skip any ops for a different user
883 continue;
884 }
Svet Ganov2af57082015-07-30 08:44:20 -0700885
886 Map<String, Ops> packages = uidState.pkgOps;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700887 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
888 while (it.hasNext()) {
889 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700890 String packageName = ent.getKey();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800891 if (reqPackageName != null && !reqPackageName.equals(packageName)) {
892 // Skip any ops for a different package
893 continue;
894 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700895 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700896 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700897 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -0700898 if (AppOpsManager.opAllowsReset(curOp.op)
899 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -0700900 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700901 changed = true;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700902 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -0700903 mOpModeWatchers.get(curOp.op));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700904 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -0700905 mPackageModeWatchers.get(packageName));
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700906 if (curOp.time == 0 && curOp.rejectTime == 0) {
907 pkgOps.removeAt(j);
908 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700909 }
910 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700911 if (pkgOps.size() == 0) {
912 it.remove();
913 }
914 }
Svet Ganov2af57082015-07-30 08:44:20 -0700915 if (uidState.isDefault()) {
916 mUidStates.remove(uidState.uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700917 }
918 }
Svet Ganov2af57082015-07-30 08:44:20 -0700919
Dianne Hackborn607b4142013-08-02 18:10:10 -0700920 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800921 scheduleFastWriteLocked();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700922 }
923 }
924 if (callbacks != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800925 for (Map.Entry<ModeCallback, ArrayList<ChangeRec>> ent : callbacks.entrySet()) {
926 ModeCallback cb = ent.getKey();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700927 ArrayList<ChangeRec> reports = ent.getValue();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700928 for (int i=0; i<reports.size(); i++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700929 ChangeRec rep = reports.get(i);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800930 mHandler.sendMessage(PooledLambda.obtainMessage(
931 AppOpsService::notifyOpChanged,
932 this, cb, rep.op, rep.uid, rep.pkg));
Dianne Hackborn607b4142013-08-02 18:10:10 -0700933 }
934 }
935 }
936 }
937
Dianne Hackbornc2293022013-02-06 23:14:49 -0800938 @Override
939 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800940 int watchedUid = -1;
941 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
942 != PackageManager.PERMISSION_GRANTED) {
943 watchedUid = Binder.getCallingUid();
944 }
945 Preconditions.checkArgumentInRange(op, AppOpsManager.OP_NONE,
946 AppOpsManager._NUM_OP - 1, "Invalid op code: " + op);
Svetoslav Ganov8de59712015-12-09 18:25:13 -0800947 if (callback == null) {
948 return;
949 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800950 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700951 op = (op != AppOpsManager.OP_NONE) ? AppOpsManager.opToSwitch(op) : op;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800952 ModeCallback cb = mModeWatchers.get(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -0800953 if (cb == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800954 cb = new ModeCallback(callback, watchedUid);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800955 mModeWatchers.put(callback.asBinder(), cb);
956 }
957 if (op != AppOpsManager.OP_NONE) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800958 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(op);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800959 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800960 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800961 mOpModeWatchers.put(op, cbs);
962 }
963 cbs.add(cb);
964 }
965 if (packageName != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800966 ArraySet<ModeCallback> cbs = mPackageModeWatchers.get(packageName);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800967 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800968 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800969 mPackageModeWatchers.put(packageName, cbs);
970 }
971 cbs.add(cb);
972 }
973 }
974 }
975
976 @Override
977 public void stopWatchingMode(IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -0800978 if (callback == null) {
979 return;
980 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800981 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800982 ModeCallback cb = mModeWatchers.remove(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -0800983 if (cb != null) {
984 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700985 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800986 ArraySet<ModeCallback> cbs = mOpModeWatchers.valueAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800987 cbs.remove(cb);
988 if (cbs.size() <= 0) {
989 mOpModeWatchers.removeAt(i);
990 }
991 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700992 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800993 ArraySet<ModeCallback> cbs = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700994 cbs.remove(cb);
995 if (cbs.size() <= 0) {
996 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800997 }
998 }
999 }
1000 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001001 }
1002
1003 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001004 public IBinder getToken(IBinder clientToken) {
1005 synchronized (this) {
1006 ClientState cs = mClients.get(clientToken);
1007 if (cs == null) {
1008 cs = new ClientState(clientToken);
1009 mClients.put(clientToken, cs);
1010 }
1011 return cs;
1012 }
1013 }
1014
1015 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -08001016 public int checkOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001017 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001018 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001019 String resolvedPackageName = resolvePackageName(uid, packageName);
1020 if (resolvedPackageName == null) {
1021 return AppOpsManager.MODE_IGNORED;
1022 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001023 synchronized (this) {
Svet Ganov442ed572016-08-17 17:29:43 -07001024 if (isOpRestrictedLocked(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001025 return AppOpsManager.MODE_IGNORED;
1026 }
Svet Ganov2af57082015-07-30 08:44:20 -07001027 code = AppOpsManager.opToSwitch(code);
1028 UidState uidState = getUidStateLocked(uid, false);
Svet Ganovee438d42017-01-19 18:04:38 -08001029 if (uidState != null && uidState.opModes != null
1030 && uidState.opModes.indexOfKey(code) >= 0) {
1031 return uidState.opModes.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001032 }
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001033 Op op = getOpLocked(code, uid, resolvedPackageName, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001034 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -07001035 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001036 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001037 return op.mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001038 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001039 }
1040
1041 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001042 public int checkAudioOperation(int code, int usage, int uid, String packageName) {
Andrei Stingaceanuefc4a342016-03-22 14:43:01 +00001043 boolean suspended;
1044 try {
1045 suspended = isPackageSuspendedForUser(packageName, uid);
1046 } catch (IllegalArgumentException ex) {
1047 // Package not found.
1048 suspended = false;
1049 }
1050
1051 if (suspended) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001052 Slog.i(TAG, "Audio disabled for suspended package=" + packageName + " for uid=" + uid);
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001053 return AppOpsManager.MODE_IGNORED;
1054 }
1055
John Spurlock1af30c72014-03-10 08:33:35 -04001056 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001057 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -04001058 if (mode != AppOpsManager.MODE_ALLOWED) {
1059 return mode;
1060 }
1061 }
1062 return checkOperation(code, uid, packageName);
1063 }
1064
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001065 private boolean isPackageSuspendedForUser(String pkg, int uid) {
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001066 try {
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001067 return AppGlobals.getPackageManager().isPackageSuspendedForUser(
1068 pkg, UserHandle.getUserId(uid));
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001069 } catch (RemoteException re) {
1070 throw new SecurityException("Could not talk to package manager service");
1071 }
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001072 }
1073
John Spurlock7b414672014-07-18 13:02:39 -04001074 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
1075 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1076 if (usageRestrictions != null) {
1077 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001078 if (r != null && !r.exceptionPackages.contains(packageName)) {
1079 return r.mode;
1080 }
1081 }
1082 return AppOpsManager.MODE_ALLOWED;
1083 }
1084
1085 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001086 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -04001087 String[] exceptionPackages) {
1088 verifyIncomingUid(uid);
1089 verifyIncomingOp(code);
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -08001090 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
1091 Binder.getCallingPid(), Binder.getCallingUid(), null);
John Spurlock1af30c72014-03-10 08:33:35 -04001092 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001093 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1094 if (usageRestrictions == null) {
1095 usageRestrictions = new SparseArray<Restriction>();
1096 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -04001097 }
John Spurlock7b414672014-07-18 13:02:39 -04001098 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001099 if (mode != AppOpsManager.MODE_ALLOWED) {
1100 final Restriction r = new Restriction();
1101 r.mode = mode;
1102 if (exceptionPackages != null) {
1103 final int N = exceptionPackages.length;
1104 r.exceptionPackages = new ArraySet<String>(N);
1105 for (int i = 0; i < N; i++) {
1106 final String pkg = exceptionPackages[i];
1107 if (pkg != null) {
1108 r.exceptionPackages.add(pkg.trim());
1109 }
1110 }
1111 }
John Spurlock7b414672014-07-18 13:02:39 -04001112 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -04001113 }
1114 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001115
1116 mHandler.sendMessage(PooledLambda.obtainMessage(
1117 AppOpsService::notifyWatchersOfChange, this, code));
John Spurlock1af30c72014-03-10 08:33:35 -04001118 }
1119
1120 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001121 public int checkPackage(int uid, String packageName) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001122 Preconditions.checkNotNull(packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001123 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001124 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1125 true /* uidMismatchExpected */);
1126 if (ops != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001127 return AppOpsManager.MODE_ALLOWED;
1128 } else {
1129 return AppOpsManager.MODE_ERRORED;
1130 }
1131 }
1132 }
1133
1134 @Override
Svet Ganov99b60432015-06-27 13:15:22 -07001135 public int noteProxyOperation(int code, String proxyPackageName,
1136 int proxiedUid, String proxiedPackageName) {
1137 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001138 final int proxyUid = Binder.getCallingUid();
1139 String resolveProxyPackageName = resolvePackageName(proxyUid, proxyPackageName);
1140 if (resolveProxyPackageName == null) {
1141 return AppOpsManager.MODE_IGNORED;
1142 }
1143 final int proxyMode = noteOperationUnchecked(code, proxyUid,
1144 resolveProxyPackageName, -1, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001145 if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
1146 return proxyMode;
1147 }
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001148 String resolveProxiedPackageName = resolvePackageName(proxiedUid, proxiedPackageName);
1149 if (resolveProxiedPackageName == null) {
1150 return AppOpsManager.MODE_IGNORED;
1151 }
1152 return noteOperationUnchecked(code, proxiedUid, resolveProxiedPackageName,
1153 proxyMode, resolveProxyPackageName);
Svet Ganov99b60432015-06-27 13:15:22 -07001154 }
1155
1156 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001157 public int noteOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001158 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001159 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001160 String resolvedPackageName = resolvePackageName(uid, packageName);
1161 if (resolvedPackageName == null) {
1162 return AppOpsManager.MODE_IGNORED;
1163 }
1164 return noteOperationUnchecked(code, uid, resolvedPackageName, 0, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001165 }
1166
1167 private int noteOperationUnchecked(int code, int uid, String packageName,
1168 int proxyUid, String proxyPackageName) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001169 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001170 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1171 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001172 if (ops == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001173 if (DEBUG) Slog.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001174 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001175 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001176 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001177 Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07001178 if (isOpRestrictedLocked(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001179 return AppOpsManager.MODE_IGNORED;
1180 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001181 if (op.duration == -1) {
1182 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
1183 + " code " + code + " time=" + op.time + " duration=" + op.duration);
1184 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001185 op.duration = 0;
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001186 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001187 UidState uidState = ops.uidState;
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001188 // If there is a non-default per UID policy (we set UID op mode only if
1189 // non-default) it takes over, otherwise use the per package policy.
1190 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -07001191 final int uidMode = uidState.opModes.get(switchCode);
1192 if (uidMode != AppOpsManager.MODE_ALLOWED) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001193 if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + op.mode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07001194 + switchCode + " (" + code + ") uid " + uid + " package "
1195 + packageName);
1196 op.rejectTime = System.currentTimeMillis();
1197 return uidMode;
1198 }
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001199 } else {
1200 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
1201 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001202 if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + op.mode + " for code "
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001203 + switchCode + " (" + code + ") uid " + uid + " package "
1204 + packageName);
1205 op.rejectTime = System.currentTimeMillis();
1206 return switchOp.mode;
1207 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001208 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001209 if (DEBUG) Slog.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001210 + " package " + packageName);
1211 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001212 op.rejectTime = 0;
Svet Ganov99b60432015-06-27 13:15:22 -07001213 op.proxyUid = proxyUid;
1214 op.proxyPackageName = proxyPackageName;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001215 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001216 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001217 }
1218
1219 @Override
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001220 public void startWatchingActive(int[] ops, IAppOpsActiveCallback callback) {
Svet Ganovf7b47252018-02-26 11:11:27 -08001221 int watchedUid = -1;
1222 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
1223 != PackageManager.PERMISSION_GRANTED) {
1224 watchedUid = Binder.getCallingUid();
1225 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001226 if (ops != null) {
1227 Preconditions.checkArrayElementsInRange(ops, 0,
1228 AppOpsManager._NUM_OP - 1, "Invalid op code in: " + Arrays.toString(ops));
1229 }
1230 if (callback == null) {
1231 return;
1232 }
1233 synchronized (this) {
1234 SparseArray<ActiveCallback> callbacks = mActiveWatchers.get(callback.asBinder());
1235 if (callbacks == null) {
1236 callbacks = new SparseArray<>();
1237 mActiveWatchers.put(callback.asBinder(), callbacks);
1238 }
Svet Ganovf7b47252018-02-26 11:11:27 -08001239 final ActiveCallback activeCallback = new ActiveCallback(callback, watchedUid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001240 for (int op : ops) {
1241 callbacks.put(op, activeCallback);
1242 }
1243 }
1244 }
1245
1246 @Override
1247 public void stopWatchingActive(IAppOpsActiveCallback callback) {
1248 if (callback == null) {
1249 return;
1250 }
1251 synchronized (this) {
1252 final SparseArray<ActiveCallback> activeCallbacks =
1253 mActiveWatchers.remove(callback.asBinder());
1254 if (activeCallbacks == null) {
1255 return;
1256 }
1257 final int callbackCount = activeCallbacks.size();
1258 for (int i = 0; i < callbackCount; i++) {
1259 // Apps ops are mapped to a singleton
1260 if (i == 0) {
1261 activeCallbacks.valueAt(i).destroy();
1262 }
1263 }
1264 }
1265 }
1266
1267 @Override
Svet Ganovf7b47252018-02-26 11:11:27 -08001268 public int startOperation(IBinder token, int code, int uid, String packageName,
1269 boolean startIfModeDefault) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001270 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001271 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001272 String resolvedPackageName = resolvePackageName(uid, packageName);
1273 if (resolvedPackageName == null) {
1274 return AppOpsManager.MODE_IGNORED;
1275 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001276 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001277 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001278 Ops ops = getOpsRawLocked(uid, resolvedPackageName, true /* edit */,
1279 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001280 if (ops == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001281 if (DEBUG) Slog.d(TAG, "startOperation: no op for code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001282 + " package " + resolvedPackageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001283 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001284 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001285 Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07001286 if (isOpRestrictedLocked(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001287 return AppOpsManager.MODE_IGNORED;
1288 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001289 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001290 UidState uidState = ops.uidState;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001291 // If there is a non-default per UID policy (we set UID op mode only if
1292 // non-default) it takes over, otherwise use the per package policy.
1293 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -07001294 final int uidMode = uidState.opModes.get(switchCode);
Svet Ganovf7b47252018-02-26 11:11:27 -08001295 if (uidMode != AppOpsManager.MODE_ALLOWED
1296 && (!startIfModeDefault || uidMode != AppOpsManager.MODE_DEFAULT)) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001297 if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + op.mode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07001298 + switchCode + " (" + code + ") uid " + uid + " package "
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001299 + resolvedPackageName);
Svet Ganov2af57082015-07-30 08:44:20 -07001300 op.rejectTime = System.currentTimeMillis();
1301 return uidMode;
1302 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001303 } else {
1304 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
Svet Ganovf7b47252018-02-26 11:11:27 -08001305 if (switchOp.mode != AppOpsManager.MODE_ALLOWED
1306 && (!startIfModeDefault || switchOp.mode != AppOpsManager.MODE_DEFAULT)) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001307 if (DEBUG) Slog.d(TAG, "startOperation: reject #" + op.mode + " for code "
1308 + switchCode + " (" + code + ") uid " + uid + " package "
1309 + resolvedPackageName);
1310 op.rejectTime = System.currentTimeMillis();
1311 return switchOp.mode;
1312 }
Svet Ganov2af57082015-07-30 08:44:20 -07001313 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001314 if (DEBUG) Slog.d(TAG, "startOperation: allowing code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001315 + " package " + resolvedPackageName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001316 if (op.nesting == 0) {
1317 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001318 op.rejectTime = 0;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001319 op.duration = -1;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001320 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001321 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001322 op.nesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001323 if (client.mStartedOps != null) {
1324 client.mStartedOps.add(op);
1325 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001326 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001327
1328 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001329 }
1330
1331 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001332 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001333 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001334 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001335 String resolvedPackageName = resolvePackageName(uid, packageName);
1336 if (resolvedPackageName == null) {
1337 return;
1338 }
1339 if (!(token instanceof ClientState)) {
1340 return;
1341 }
1342 ClientState client = (ClientState) token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001343 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001344 Op op = getOpLocked(code, uid, resolvedPackageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001345 if (op == null) {
1346 return;
1347 }
Svet Ganovf7b47252018-02-26 11:11:27 -08001348 if (!client.mStartedOps.remove(op)) {
Svet Ganovf5d5af12018-03-18 11:51:17 -07001349 // We finish ops when packages get removed to guarantee no dangling
1350 // started ops. However, some part of the system may asynchronously
1351 // finish ops for an already gone package. Hence, finishing an op
1352 // for a non existing package is fine and we don't log as a wtf.
1353 final long identity = Binder.clearCallingIdentity();
1354 try {
1355 if (LocalServices.getService(PackageManagerInternal.class).getPackageUid(
1356 resolvedPackageName, 0, UserHandle.getUserId(uid)) < 0) {
1357 Slog.i(TAG, "Finishing op=" + AppOpsManager.opToName(code)
1358 + " for non-existing package=" + resolvedPackageName
1359 + " in uid=" + uid);
1360 return;
1361 }
1362 } finally {
1363 Binder.restoreCallingIdentity(identity);
1364 }
1365 Slog.wtf(TAG, "Operation not started: uid=" + op.uid + " pkg="
1366 + op.packageName + " op=" + AppOpsManager.opToName(op.op));
Svet Ganov31d83ae2018-03-15 10:45:56 -07001367 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001368 }
Svet Ganova7a0db62018-02-27 20:08:01 -08001369 finishOperationLocked(op, /*finishNested*/ false);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001370 if (op.nesting <= 0) {
1371 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, false);
1372 }
1373 }
1374 }
1375
1376 private void scheduleOpActiveChangedIfNeededLocked(int code, int uid, String packageName,
1377 boolean active) {
1378 ArraySet<ActiveCallback> dispatchedCallbacks = null;
1379 final int callbackListCount = mActiveWatchers.size();
1380 for (int i = 0; i < callbackListCount; i++) {
1381 final SparseArray<ActiveCallback> callbacks = mActiveWatchers.valueAt(i);
1382 ActiveCallback callback = callbacks.get(code);
1383 if (callback != null) {
Svet Ganovf7b47252018-02-26 11:11:27 -08001384 if (callback.mUid >= 0 && callback.mUid != uid) {
1385 continue;
1386 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001387 if (dispatchedCallbacks == null) {
1388 dispatchedCallbacks = new ArraySet<>();
1389 }
1390 dispatchedCallbacks.add(callback);
1391 }
1392 }
1393 if (dispatchedCallbacks == null) {
1394 return;
1395 }
1396 mHandler.sendMessage(PooledLambda.obtainMessage(
1397 AppOpsService::notifyOpActiveChanged,
1398 this, dispatchedCallbacks, code, uid, packageName, active));
1399 }
1400
1401 private void notifyOpActiveChanged(ArraySet<ActiveCallback> callbacks,
1402 int code, int uid, String packageName, boolean active) {
1403 // There are components watching for mode changes such as window manager
1404 // and location manager which are in our process. The callbacks in these
1405 // components may require permissions our remote caller does not have.
1406 final long identity = Binder.clearCallingIdentity();
1407 try {
1408 final int callbackCount = callbacks.size();
1409 for (int i = 0; i < callbackCount; i++) {
1410 final ActiveCallback callback = callbacks.valueAt(i);
1411 try {
1412 callback.mCallback.opActiveChanged(code, uid, packageName, active);
1413 } catch (RemoteException e) {
1414 /* do nothing */
1415 }
1416 }
1417 } finally {
1418 Binder.restoreCallingIdentity(identity);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001419 }
1420 }
1421
Svet Ganovb9d71a62015-04-30 10:38:13 -07001422 @Override
1423 public int permissionToOpCode(String permission) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001424 if (permission == null) {
1425 return AppOpsManager.OP_NONE;
1426 }
Svet Ganovb9d71a62015-04-30 10:38:13 -07001427 return AppOpsManager.permissionToOpCode(permission);
1428 }
1429
Svet Ganova7a0db62018-02-27 20:08:01 -08001430 void finishOperationLocked(Op op, boolean finishNested) {
1431 if (op.nesting <= 1 || finishNested) {
1432 if (op.nesting == 1 || finishNested) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001433 op.duration = (int)(System.currentTimeMillis() - op.time);
1434 op.time += op.duration;
1435 } else {
1436 Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
1437 + op.packageName + " code " + op.op + " time=" + op.time
1438 + " duration=" + op.duration + " nesting=" + op.nesting);
1439 }
1440 op.nesting = 0;
1441 } else {
1442 op.nesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001443 }
1444 }
1445
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001446 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001447 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001448 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001449 }
1450 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001451 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001452 }
1453 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
1454 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001455 }
1456
Dianne Hackborn961321f2013-02-05 17:22:41 -08001457 private void verifyIncomingOp(int op) {
1458 if (op >= 0 && op < AppOpsManager._NUM_OP) {
1459 return;
1460 }
1461 throw new IllegalArgumentException("Bad operation #" + op);
1462 }
1463
Svet Ganov2af57082015-07-30 08:44:20 -07001464 private UidState getUidStateLocked(int uid, boolean edit) {
1465 UidState uidState = mUidStates.get(uid);
1466 if (uidState == null) {
1467 if (!edit) {
1468 return null;
1469 }
1470 uidState = new UidState(uid);
1471 mUidStates.put(uid, uidState);
1472 }
1473 return uidState;
1474 }
1475
Yohei Yukawaa965d652017-10-12 15:02:26 -07001476 private Ops getOpsRawLocked(int uid, String packageName, boolean edit,
1477 boolean uidMismatchExpected) {
Svet Ganov2af57082015-07-30 08:44:20 -07001478 UidState uidState = getUidStateLocked(uid, edit);
1479 if (uidState == null) {
1480 return null;
1481 }
1482
1483 if (uidState.pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001484 if (!edit) {
1485 return null;
1486 }
Svet Ganov2af57082015-07-30 08:44:20 -07001487 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001488 }
Svet Ganov2af57082015-07-30 08:44:20 -07001489
1490 Ops ops = uidState.pkgOps.get(packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001491 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001492 if (!edit) {
1493 return null;
1494 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001495 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001496 // This is the first time we have seen this package name under this uid,
1497 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -08001498 if (uid != 0) {
1499 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001500 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001501 int pkgUid = -1;
1502 try {
Jason Monk1c7c3192014-06-26 12:52:18 -04001503 ApplicationInfo appInfo = ActivityThread.getPackageManager()
Jeff Sharkeycd654482016-01-08 17:42:11 -07001504 .getApplicationInfo(packageName,
1505 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1506 UserHandle.getUserId(uid));
Jason Monk1c7c3192014-06-26 12:52:18 -04001507 if (appInfo != null) {
1508 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001509 isPrivileged = (appInfo.privateFlags
1510 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001511 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08001512 pkgUid = resolveUid(packageName);
1513 if (pkgUid >= 0) {
Chien-Yu Chen75cade02016-01-11 10:56:21 -08001514 isPrivileged = false;
Jason Monk1c7c3192014-06-26 12:52:18 -04001515 }
Dianne Hackborn713df152013-05-17 11:27:57 -07001516 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001517 } catch (RemoteException e) {
1518 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001519 }
1520 if (pkgUid != uid) {
1521 // Oops! The package name is not valid for the uid they are calling
1522 // under. Abort.
Yohei Yukawaa965d652017-10-12 15:02:26 -07001523 if (!uidMismatchExpected) {
1524 RuntimeException ex = new RuntimeException("here");
1525 ex.fillInStackTrace();
1526 Slog.w(TAG, "Bad call: specified package " + packageName
1527 + " under uid " + uid + " but it is really " + pkgUid, ex);
1528 }
Dianne Hackborn514074f2013-02-11 10:52:46 -08001529 return null;
1530 }
1531 } finally {
1532 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001533 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001534 }
Svet Ganov2af57082015-07-30 08:44:20 -07001535 ops = new Ops(packageName, uidState, isPrivileged);
1536 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001537 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08001538 return ops;
1539 }
1540
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001541 private void scheduleWriteLocked() {
1542 if (!mWriteScheduled) {
1543 mWriteScheduled = true;
1544 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
1545 }
1546 }
1547
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001548 private void scheduleFastWriteLocked() {
1549 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001550 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001551 mFastWriteScheduled = true;
1552 mHandler.removeCallbacks(mWriteRunner);
1553 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001554 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001555 }
1556
Dianne Hackborn72e39832013-01-18 18:36:09 -08001557 private Op getOpLocked(int code, int uid, String packageName, boolean edit) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001558 Ops ops = getOpsRawLocked(uid, packageName, edit,
1559 false /* uidMismatchExpected */);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001560 if (ops == null) {
1561 return null;
1562 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001563 return getOpLocked(ops, code, edit);
1564 }
1565
1566 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001567 Op op = ops.get(code);
1568 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001569 if (!edit) {
1570 return null;
1571 }
Svet Ganov2af57082015-07-30 08:44:20 -07001572 op = new Op(ops.uidState.uid, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001573 ops.put(code, op);
1574 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001575 if (edit) {
1576 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001577 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001578 return op;
1579 }
1580
Svet Ganov442ed572016-08-17 17:29:43 -07001581 private boolean isOpRestrictedLocked(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04001582 int userHandle = UserHandle.getUserId(uid);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001583 final int restrictionSetCount = mOpUserRestrictions.size();
Ruben Brunk29931bc2016-03-11 00:24:26 -08001584
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001585 for (int i = 0; i < restrictionSetCount; i++) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08001586 // For each client, check that the given op is not restricted, or that the given
1587 // package is exempt from the restriction.
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07001588 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07001589 if (restrictionState.hasRestriction(code, packageName, userHandle)) {
1590 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
1591 // If we are the system, bypass user restrictions for certain codes
1592 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001593 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1594 false /* uidMismatchExpected */);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07001595 if ((ops != null) && ops.isPrivileged) {
1596 return false;
1597 }
Ruben Brunk32f0fa42016-03-11 19:07:07 -08001598 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08001599 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001600 return true;
Jason Monk1c7c3192014-06-26 12:52:18 -04001601 }
Jason Monk62062992014-05-06 09:55:28 -04001602 }
1603 return false;
1604 }
1605
Dianne Hackborn35654b62013-01-14 17:38:02 -08001606 void readState() {
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001607 int oldVersion = NO_VERSION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001608 synchronized (mFile) {
1609 synchronized (this) {
1610 FileInputStream stream;
1611 try {
1612 stream = mFile.openRead();
1613 } catch (FileNotFoundException e) {
1614 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
1615 return;
1616 }
1617 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001618 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001619 try {
1620 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001621 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001622 int type;
1623 while ((type = parser.next()) != XmlPullParser.START_TAG
1624 && type != XmlPullParser.END_DOCUMENT) {
1625 ;
1626 }
1627
1628 if (type != XmlPullParser.START_TAG) {
1629 throw new IllegalStateException("no start tag found");
1630 }
1631
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001632 final String versionString = parser.getAttributeValue(null, "v");
1633 if (versionString != null) {
1634 oldVersion = Integer.parseInt(versionString);
1635 }
1636
Dianne Hackborn35654b62013-01-14 17:38:02 -08001637 int outerDepth = parser.getDepth();
1638 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1639 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1640 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1641 continue;
1642 }
1643
1644 String tagName = parser.getName();
1645 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001646 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07001647 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07001648 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001649 } else {
1650 Slog.w(TAG, "Unknown element under <app-ops>: "
1651 + parser.getName());
1652 XmlUtils.skipCurrentTag(parser);
1653 }
1654 }
1655 success = true;
1656 } catch (IllegalStateException e) {
1657 Slog.w(TAG, "Failed parsing " + e);
1658 } catch (NullPointerException e) {
1659 Slog.w(TAG, "Failed parsing " + e);
1660 } catch (NumberFormatException e) {
1661 Slog.w(TAG, "Failed parsing " + e);
1662 } catch (XmlPullParserException e) {
1663 Slog.w(TAG, "Failed parsing " + e);
1664 } catch (IOException e) {
1665 Slog.w(TAG, "Failed parsing " + e);
1666 } catch (IndexOutOfBoundsException e) {
1667 Slog.w(TAG, "Failed parsing " + e);
1668 } finally {
1669 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07001670 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001671 }
1672 try {
1673 stream.close();
1674 } catch (IOException e) {
1675 }
1676 }
1677 }
1678 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001679 synchronized (this) {
1680 upgradeLocked(oldVersion);
1681 }
1682 }
1683
1684 private void upgradeRunAnyInBackgroundLocked() {
1685 for (int i = 0; i < mUidStates.size(); i++) {
1686 final UidState uidState = mUidStates.valueAt(i);
1687 if (uidState == null) {
1688 continue;
1689 }
1690 if (uidState.opModes != null) {
1691 final int idx = uidState.opModes.indexOfKey(AppOpsManager.OP_RUN_IN_BACKGROUND);
1692 if (idx >= 0) {
1693 uidState.opModes.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND,
1694 uidState.opModes.valueAt(idx));
1695 }
1696 }
1697 if (uidState.pkgOps == null) {
1698 continue;
1699 }
1700 for (int j = 0; j < uidState.pkgOps.size(); j++) {
1701 Ops ops = uidState.pkgOps.valueAt(j);
1702 if (ops != null) {
1703 final Op op = ops.get(AppOpsManager.OP_RUN_IN_BACKGROUND);
1704 if (op != null && op.mode != AppOpsManager.opToDefaultMode(op.op)) {
1705 final Op copy = new Op(op.uid, op.packageName,
1706 AppOpsManager.OP_RUN_ANY_IN_BACKGROUND);
1707 copy.mode = op.mode;
1708 ops.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, copy);
1709 }
1710 }
1711 }
1712 }
1713 }
1714
1715 private void upgradeLocked(int oldVersion) {
1716 if (oldVersion >= CURRENT_VERSION) {
1717 return;
1718 }
1719 Slog.d(TAG, "Upgrading app-ops xml from version " + oldVersion + " to " + CURRENT_VERSION);
1720 switch (oldVersion) {
1721 case NO_VERSION:
1722 upgradeRunAnyInBackgroundLocked();
1723 // fall through
1724 case 1:
1725 // for future upgrades
1726 }
1727 scheduleFastWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001728 }
1729
Svet Ganov2af57082015-07-30 08:44:20 -07001730 void readUidOps(XmlPullParser parser) throws NumberFormatException,
1731 XmlPullParserException, IOException {
1732 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
1733 int outerDepth = parser.getDepth();
1734 int type;
1735 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1736 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1737 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1738 continue;
1739 }
1740
1741 String tagName = parser.getName();
1742 if (tagName.equals("op")) {
1743 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
1744 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
1745 UidState uidState = getUidStateLocked(uid, true);
1746 if (uidState.opModes == null) {
1747 uidState.opModes = new SparseIntArray();
1748 }
1749 uidState.opModes.put(code, mode);
1750 } else {
1751 Slog.w(TAG, "Unknown element under <uid-ops>: "
1752 + parser.getName());
1753 XmlUtils.skipCurrentTag(parser);
1754 }
1755 }
1756 }
1757
Dave Burke0997c5bd2013-08-02 20:25:02 +00001758 void readPackage(XmlPullParser parser) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001759 XmlPullParserException, IOException {
1760 String pkgName = parser.getAttributeValue(null, "n");
1761 int outerDepth = parser.getDepth();
1762 int type;
1763 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1764 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1765 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1766 continue;
1767 }
1768
1769 String tagName = parser.getName();
1770 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001771 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001772 } else {
1773 Slog.w(TAG, "Unknown element under <pkg>: "
1774 + parser.getName());
1775 XmlUtils.skipCurrentTag(parser);
1776 }
1777 }
1778 }
1779
Dave Burke0997c5bd2013-08-02 20:25:02 +00001780 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001781 XmlPullParserException, IOException {
1782 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Jason Monk1c7c3192014-06-26 12:52:18 -04001783 String isPrivilegedString = parser.getAttributeValue(null, "p");
1784 boolean isPrivileged = false;
1785 if (isPrivilegedString == null) {
1786 try {
1787 IPackageManager packageManager = ActivityThread.getPackageManager();
1788 if (packageManager != null) {
1789 ApplicationInfo appInfo = ActivityThread.getPackageManager()
1790 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
1791 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001792 isPrivileged = (appInfo.privateFlags
1793 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001794 }
1795 } else {
1796 // Could not load data, don't add to cache so it will be loaded later.
1797 return;
1798 }
1799 } catch (RemoteException e) {
1800 Slog.w(TAG, "Could not contact PackageManager", e);
1801 }
1802 } else {
1803 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
1804 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001805 int outerDepth = parser.getDepth();
1806 int type;
1807 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1808 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1809 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1810 continue;
1811 }
1812
1813 String tagName = parser.getName();
1814 if (tagName.equals("op")) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001815 Op op = new Op(uid, pkgName, Integer.parseInt(parser.getAttributeValue(null, "n")));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001816 String mode = parser.getAttributeValue(null, "m");
1817 if (mode != null) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001818 op.mode = Integer.parseInt(mode);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001819 }
1820 String time = parser.getAttributeValue(null, "t");
1821 if (time != null) {
1822 op.time = Long.parseLong(time);
1823 }
1824 time = parser.getAttributeValue(null, "r");
1825 if (time != null) {
1826 op.rejectTime = Long.parseLong(time);
1827 }
1828 String dur = parser.getAttributeValue(null, "d");
1829 if (dur != null) {
1830 op.duration = Integer.parseInt(dur);
1831 }
Svet Ganov99b60432015-06-27 13:15:22 -07001832 String proxyUid = parser.getAttributeValue(null, "pu");
1833 if (proxyUid != null) {
1834 op.proxyUid = Integer.parseInt(proxyUid);
1835 }
1836 String proxyPackageName = parser.getAttributeValue(null, "pp");
1837 if (proxyPackageName != null) {
1838 op.proxyPackageName = proxyPackageName;
1839 }
Svet Ganov2af57082015-07-30 08:44:20 -07001840
1841 UidState uidState = getUidStateLocked(uid, true);
1842 if (uidState.pkgOps == null) {
1843 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001844 }
Svet Ganov2af57082015-07-30 08:44:20 -07001845
1846 Ops ops = uidState.pkgOps.get(pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001847 if (ops == null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001848 ops = new Ops(pkgName, uidState, isPrivileged);
1849 uidState.pkgOps.put(pkgName, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001850 }
1851 ops.put(op.op, op);
1852 } else {
1853 Slog.w(TAG, "Unknown element under <pkg>: "
1854 + parser.getName());
1855 XmlUtils.skipCurrentTag(parser);
1856 }
1857 }
1858 }
1859
1860 void writeState() {
1861 synchronized (mFile) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001862 FileOutputStream stream;
1863 try {
1864 stream = mFile.startWrite();
1865 } catch (IOException e) {
1866 Slog.w(TAG, "Failed to write state: " + e);
1867 return;
1868 }
1869
Dianne Hackborne17b4452018-01-10 13:15:40 -08001870 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
1871
Dianne Hackborn35654b62013-01-14 17:38:02 -08001872 try {
1873 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001874 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001875 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001876 out.startTag(null, "app-ops");
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001877 out.attribute(null, "v", String.valueOf(CURRENT_VERSION));
Svet Ganov2af57082015-07-30 08:44:20 -07001878
1879 final int uidStateCount = mUidStates.size();
1880 for (int i = 0; i < uidStateCount; i++) {
1881 UidState uidState = mUidStates.valueAt(i);
1882 if (uidState.opModes != null && uidState.opModes.size() > 0) {
1883 out.startTag(null, "uid");
1884 out.attribute(null, "n", Integer.toString(uidState.uid));
1885 SparseIntArray uidOpModes = uidState.opModes;
1886 final int opCount = uidOpModes.size();
1887 for (int j = 0; j < opCount; j++) {
1888 final int op = uidOpModes.keyAt(j);
1889 final int mode = uidOpModes.valueAt(j);
1890 out.startTag(null, "op");
1891 out.attribute(null, "n", Integer.toString(op));
1892 out.attribute(null, "m", Integer.toString(mode));
1893 out.endTag(null, "op");
1894 }
1895 out.endTag(null, "uid");
1896 }
1897 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001898
1899 if (allOps != null) {
1900 String lastPkg = null;
1901 for (int i=0; i<allOps.size(); i++) {
1902 AppOpsManager.PackageOps pkg = allOps.get(i);
1903 if (!pkg.getPackageName().equals(lastPkg)) {
1904 if (lastPkg != null) {
1905 out.endTag(null, "pkg");
1906 }
1907 lastPkg = pkg.getPackageName();
1908 out.startTag(null, "pkg");
1909 out.attribute(null, "n", lastPkg);
1910 }
1911 out.startTag(null, "uid");
1912 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04001913 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001914 Ops ops = getOpsRawLocked(pkg.getUid(), pkg.getPackageName(),
1915 false /* edit */, false /* uidMismatchExpected */);
Jason Monk1c7c3192014-06-26 12:52:18 -04001916 // Should always be present as the list of PackageOps is generated
1917 // from Ops.
1918 if (ops != null) {
1919 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
1920 } else {
1921 out.attribute(null, "p", Boolean.toString(false));
1922 }
1923 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001924 List<AppOpsManager.OpEntry> ops = pkg.getOps();
1925 for (int j=0; j<ops.size(); j++) {
1926 AppOpsManager.OpEntry op = ops.get(j);
1927 out.startTag(null, "op");
1928 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07001929 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001930 out.attribute(null, "m", Integer.toString(op.getMode()));
1931 }
1932 long time = op.getTime();
1933 if (time != 0) {
1934 out.attribute(null, "t", Long.toString(time));
1935 }
1936 time = op.getRejectTime();
1937 if (time != 0) {
1938 out.attribute(null, "r", Long.toString(time));
1939 }
1940 int dur = op.getDuration();
1941 if (dur != 0) {
1942 out.attribute(null, "d", Integer.toString(dur));
1943 }
Svet Ganov99b60432015-06-27 13:15:22 -07001944 int proxyUid = op.getProxyUid();
1945 if (proxyUid != -1) {
1946 out.attribute(null, "pu", Integer.toString(proxyUid));
1947 }
1948 String proxyPackageName = op.getProxyPackageName();
1949 if (proxyPackageName != null) {
1950 out.attribute(null, "pp", proxyPackageName);
1951 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001952 out.endTag(null, "op");
1953 }
1954 out.endTag(null, "uid");
1955 }
1956 if (lastPkg != null) {
1957 out.endTag(null, "pkg");
1958 }
1959 }
1960
1961 out.endTag(null, "app-ops");
1962 out.endDocument();
1963 mFile.finishWrite(stream);
1964 } catch (IOException e) {
1965 Slog.w(TAG, "Failed to write state, restoring backup.", e);
1966 mFile.failWrite(stream);
1967 }
1968 }
1969 }
1970
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001971 static class Shell extends ShellCommand {
1972 final IAppOpsService mInterface;
1973 final AppOpsService mInternal;
1974
1975 int userId = UserHandle.USER_SYSTEM;
1976 String packageName;
1977 String opStr;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001978 String modeStr;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001979 int op;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001980 int mode;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001981 int packageUid;
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001982 int nonpackageUid;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05001983 final static Binder sBinder = new Binder();
1984 IBinder mToken;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001985
1986 Shell(IAppOpsService iface, AppOpsService internal) {
1987 mInterface = iface;
1988 mInternal = internal;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05001989 try {
1990 mToken = mInterface.getToken(sBinder);
1991 } catch (RemoteException e) {
1992 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001993 }
1994
1995 @Override
1996 public int onCommand(String cmd) {
1997 return onShellCommand(this, cmd);
1998 }
1999
2000 @Override
2001 public void onHelp() {
2002 PrintWriter pw = getOutPrintWriter();
2003 dumpCommandHelp(pw);
2004 }
2005
2006 private int strOpToOp(String op, PrintWriter err) {
2007 try {
2008 return AppOpsManager.strOpToOp(op);
2009 } catch (IllegalArgumentException e) {
2010 }
2011 try {
2012 return Integer.parseInt(op);
2013 } catch (NumberFormatException e) {
2014 }
2015 try {
2016 return AppOpsManager.strDebugOpToOp(op);
2017 } catch (IllegalArgumentException e) {
2018 err.println("Error: " + e.getMessage());
2019 return -1;
2020 }
2021 }
2022
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002023 int strModeToMode(String modeStr, PrintWriter err) {
2024 switch (modeStr) {
2025 case "allow":
2026 return AppOpsManager.MODE_ALLOWED;
2027 case "deny":
2028 return AppOpsManager.MODE_ERRORED;
2029 case "ignore":
2030 return AppOpsManager.MODE_IGNORED;
2031 case "default":
2032 return AppOpsManager.MODE_DEFAULT;
2033 }
2034 try {
2035 return Integer.parseInt(modeStr);
2036 } catch (NumberFormatException e) {
2037 }
2038 err.println("Error: Mode " + modeStr + " is not valid");
2039 return -1;
2040 }
2041
2042 int parseUserOpMode(int defMode, PrintWriter err) throws RemoteException {
2043 userId = UserHandle.USER_CURRENT;
2044 opStr = null;
2045 modeStr = null;
2046 for (String argument; (argument = getNextArg()) != null;) {
2047 if ("--user".equals(argument)) {
2048 userId = UserHandle.parseUserArg(getNextArgRequired());
2049 } else {
2050 if (opStr == null) {
2051 opStr = argument;
2052 } else if (modeStr == null) {
2053 modeStr = argument;
2054 break;
2055 }
2056 }
2057 }
2058 if (opStr == null) {
2059 err.println("Error: Operation not specified.");
2060 return -1;
2061 }
2062 op = strOpToOp(opStr, err);
2063 if (op < 0) {
2064 return -1;
2065 }
2066 if (modeStr != null) {
2067 if ((mode=strModeToMode(modeStr, err)) < 0) {
2068 return -1;
2069 }
2070 } else {
2071 mode = defMode;
2072 }
2073 return 0;
2074 }
2075
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002076 int parseUserPackageOp(boolean reqOp, PrintWriter err) throws RemoteException {
2077 userId = UserHandle.USER_CURRENT;
2078 packageName = null;
2079 opStr = null;
2080 for (String argument; (argument = getNextArg()) != null;) {
2081 if ("--user".equals(argument)) {
2082 userId = UserHandle.parseUserArg(getNextArgRequired());
2083 } else {
2084 if (packageName == null) {
2085 packageName = argument;
2086 } else if (opStr == null) {
2087 opStr = argument;
2088 break;
2089 }
2090 }
2091 }
2092 if (packageName == null) {
2093 err.println("Error: Package name not specified.");
2094 return -1;
2095 } else if (opStr == null && reqOp) {
2096 err.println("Error: Operation not specified.");
2097 return -1;
2098 }
2099 if (opStr != null) {
2100 op = strOpToOp(opStr, err);
2101 if (op < 0) {
2102 return -1;
2103 }
2104 } else {
2105 op = AppOpsManager.OP_NONE;
2106 }
2107 if (userId == UserHandle.USER_CURRENT) {
2108 userId = ActivityManager.getCurrentUser();
2109 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002110 nonpackageUid = -1;
2111 try {
2112 nonpackageUid = Integer.parseInt(packageName);
2113 } catch (NumberFormatException e) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002114 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002115 if (nonpackageUid == -1 && packageName.length() > 1 && packageName.charAt(0) == 'u'
2116 && packageName.indexOf('.') < 0) {
2117 int i = 1;
2118 while (i < packageName.length() && packageName.charAt(i) >= '0'
2119 && packageName.charAt(i) <= '9') {
2120 i++;
2121 }
2122 if (i > 1 && i < packageName.length()) {
2123 String userStr = packageName.substring(1, i);
2124 try {
2125 int user = Integer.parseInt(userStr);
2126 char type = packageName.charAt(i);
2127 i++;
2128 int startTypeVal = i;
2129 while (i < packageName.length() && packageName.charAt(i) >= '0'
2130 && packageName.charAt(i) <= '9') {
2131 i++;
2132 }
2133 if (i > startTypeVal) {
2134 String typeValStr = packageName.substring(startTypeVal, i);
2135 try {
2136 int typeVal = Integer.parseInt(typeValStr);
2137 if (type == 'a') {
2138 nonpackageUid = UserHandle.getUid(user,
2139 typeVal + Process.FIRST_APPLICATION_UID);
2140 } else if (type == 's') {
2141 nonpackageUid = UserHandle.getUid(user, typeVal);
2142 }
2143 } catch (NumberFormatException e) {
2144 }
2145 }
2146 } catch (NumberFormatException e) {
2147 }
2148 }
2149 }
2150 if (nonpackageUid != -1) {
2151 packageName = null;
2152 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08002153 packageUid = resolveUid(packageName);
2154 if (packageUid < 0) {
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002155 packageUid = AppGlobals.getPackageManager().getPackageUid(packageName,
2156 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
2157 }
2158 if (packageUid < 0) {
2159 err.println("Error: No UID for " + packageName + " in user " + userId);
2160 return -1;
2161 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002162 }
2163 return 0;
2164 }
2165 }
2166
2167 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002168 FileDescriptor err, String[] args, ShellCallback callback,
2169 ResultReceiver resultReceiver) {
2170 (new Shell(this, this)).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002171 }
2172
2173 static void dumpCommandHelp(PrintWriter pw) {
2174 pw.println("AppOps service (appops) commands:");
2175 pw.println(" help");
2176 pw.println(" Print this help text.");
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05002177 pw.println(" start [--user <USER_ID>] <PACKAGE | UID> <OP> ");
2178 pw.println(" Starts a given operation for a particular application.");
2179 pw.println(" stop [--user <USER_ID>] <PACKAGE | UID> <OP> ");
2180 pw.println(" Stops a given operation for a particular application.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002181 pw.println(" set [--user <USER_ID>] <PACKAGE | UID> <OP> <MODE>");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002182 pw.println(" Set the mode for a particular application and operation.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002183 pw.println(" get [--user <USER_ID>] <PACKAGE | UID> [<OP>]");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002184 pw.println(" Return the mode for a particular application and optional operation.");
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002185 pw.println(" query-op [--user <USER_ID>] <OP> [<MODE>]");
2186 pw.println(" Print all packages that currently have the given op in the given mode.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002187 pw.println(" reset [--user <USER_ID>] [<PACKAGE>]");
2188 pw.println(" Reset the given application or all applications to default modes.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002189 pw.println(" write-settings");
2190 pw.println(" Immediately write pending changes to storage.");
2191 pw.println(" read-settings");
2192 pw.println(" Read the last written settings, replacing current state in RAM.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002193 pw.println(" options:");
2194 pw.println(" <PACKAGE> an Android package name.");
2195 pw.println(" <OP> an AppOps operation.");
2196 pw.println(" <MODE> one of allow, ignore, deny, or default");
2197 pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
2198 pw.println(" specified, the current user is assumed.");
2199 }
2200
2201 static int onShellCommand(Shell shell, String cmd) {
2202 if (cmd == null) {
2203 return shell.handleDefaultCommands(cmd);
2204 }
2205 PrintWriter pw = shell.getOutPrintWriter();
2206 PrintWriter err = shell.getErrPrintWriter();
2207 try {
2208 switch (cmd) {
2209 case "set": {
2210 int res = shell.parseUserPackageOp(true, err);
2211 if (res < 0) {
2212 return res;
2213 }
2214 String modeStr = shell.getNextArg();
2215 if (modeStr == null) {
2216 err.println("Error: Mode not specified.");
2217 return -1;
2218 }
2219
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002220 final int mode = shell.strModeToMode(modeStr, err);
2221 if (mode < 0) {
2222 return -1;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002223 }
2224
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002225 if (shell.packageName != null) {
2226 shell.mInterface.setMode(shell.op, shell.packageUid, shell.packageName,
2227 mode);
2228 } else {
2229 shell.mInterface.setUidMode(shell.op, shell.nonpackageUid, mode);
2230 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002231 return 0;
2232 }
2233 case "get": {
2234 int res = shell.parseUserPackageOp(false, err);
2235 if (res < 0) {
2236 return res;
2237 }
2238
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002239 List<AppOpsManager.PackageOps> ops;
2240 if (shell.packageName != null) {
2241 ops = shell.mInterface.getOpsForPackage(
2242 shell.packageUid, shell.packageName,
2243 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
2244 } else {
2245 ops = shell.mInterface.getUidOps(
2246 shell.nonpackageUid,
2247 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
2248 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002249 if (ops == null || ops.size() <= 0) {
2250 pw.println("No operations.");
Svet Ganov82f09bc2018-01-12 22:08:40 -08002251 if (shell.op > AppOpsManager.OP_NONE && shell.op < AppOpsManager._NUM_OP) {
2252 pw.println("Default mode: " + AppOpsManager.modeToString(
2253 AppOpsManager.opToDefaultMode(shell.op)));
2254 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002255 return 0;
2256 }
2257 final long now = System.currentTimeMillis();
2258 for (int i=0; i<ops.size(); i++) {
2259 List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
2260 for (int j=0; j<entries.size(); j++) {
2261 AppOpsManager.OpEntry ent = entries.get(j);
2262 pw.print(AppOpsManager.opToName(ent.getOp()));
2263 pw.print(": ");
Svet Ganov82f09bc2018-01-12 22:08:40 -08002264 pw.print(AppOpsManager.modeToString(ent.getMode()));
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002265 if (ent.getTime() != 0) {
2266 pw.print("; time=");
2267 TimeUtils.formatDuration(now - ent.getTime(), pw);
2268 pw.print(" ago");
2269 }
2270 if (ent.getRejectTime() != 0) {
2271 pw.print("; rejectTime=");
2272 TimeUtils.formatDuration(now - ent.getRejectTime(), pw);
2273 pw.print(" ago");
2274 }
2275 if (ent.getDuration() == -1) {
2276 pw.print(" (running)");
2277 } else if (ent.getDuration() != 0) {
2278 pw.print("; duration=");
2279 TimeUtils.formatDuration(ent.getDuration(), pw);
2280 }
2281 pw.println();
2282 }
2283 }
2284 return 0;
2285 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002286 case "query-op": {
2287 int res = shell.parseUserOpMode(AppOpsManager.MODE_IGNORED, err);
2288 if (res < 0) {
2289 return res;
2290 }
2291 List<AppOpsManager.PackageOps> ops = shell.mInterface.getPackagesForOps(
2292 new int[] {shell.op});
2293 if (ops == null || ops.size() <= 0) {
2294 pw.println("No operations.");
2295 return 0;
2296 }
2297 for (int i=0; i<ops.size(); i++) {
2298 final AppOpsManager.PackageOps pkg = ops.get(i);
2299 boolean hasMatch = false;
2300 final List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
2301 for (int j=0; j<entries.size(); j++) {
2302 AppOpsManager.OpEntry ent = entries.get(j);
2303 if (ent.getOp() == shell.op && ent.getMode() == shell.mode) {
2304 hasMatch = true;
2305 break;
2306 }
2307 }
2308 if (hasMatch) {
2309 pw.println(pkg.getPackageName());
2310 }
2311 }
2312 return 0;
2313 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002314 case "reset": {
2315 String packageName = null;
2316 int userId = UserHandle.USER_CURRENT;
2317 for (String argument; (argument = shell.getNextArg()) != null;) {
2318 if ("--user".equals(argument)) {
2319 String userStr = shell.getNextArgRequired();
2320 userId = UserHandle.parseUserArg(userStr);
2321 } else {
2322 if (packageName == null) {
2323 packageName = argument;
2324 } else {
2325 err.println("Error: Unsupported argument: " + argument);
2326 return -1;
2327 }
2328 }
2329 }
2330
2331 if (userId == UserHandle.USER_CURRENT) {
2332 userId = ActivityManager.getCurrentUser();
2333 }
2334
2335 shell.mInterface.resetAllModes(userId, packageName);
2336 pw.print("Reset all modes for: ");
2337 if (userId == UserHandle.USER_ALL) {
2338 pw.print("all users");
2339 } else {
2340 pw.print("user "); pw.print(userId);
2341 }
2342 pw.print(", ");
2343 if (packageName == null) {
2344 pw.println("all packages");
2345 } else {
2346 pw.print("package "); pw.println(packageName);
2347 }
2348 return 0;
2349 }
2350 case "write-settings": {
2351 shell.mInternal.mContext.enforcePermission(
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -08002352 android.Manifest.permission.MANAGE_APP_OPS_MODES,
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002353 Binder.getCallingPid(), Binder.getCallingUid(), null);
2354 long token = Binder.clearCallingIdentity();
2355 try {
2356 synchronized (shell.mInternal) {
2357 shell.mInternal.mHandler.removeCallbacks(shell.mInternal.mWriteRunner);
2358 }
2359 shell.mInternal.writeState();
2360 pw.println("Current settings written.");
2361 } finally {
2362 Binder.restoreCallingIdentity(token);
2363 }
2364 return 0;
2365 }
2366 case "read-settings": {
2367 shell.mInternal.mContext.enforcePermission(
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -08002368 android.Manifest.permission.MANAGE_APP_OPS_MODES,
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002369 Binder.getCallingPid(), Binder.getCallingUid(), null);
2370 long token = Binder.clearCallingIdentity();
2371 try {
2372 shell.mInternal.readState();
2373 pw.println("Last settings read.");
2374 } finally {
2375 Binder.restoreCallingIdentity(token);
2376 }
2377 return 0;
2378 }
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05002379 case "start": {
2380 int res = shell.parseUserPackageOp(true, err);
2381 if (res < 0) {
2382 return res;
2383 }
2384
2385 if (shell.packageName != null) {
2386 shell.mInterface.startOperation(shell.mToken,
2387 shell.op, shell.packageUid, shell.packageName, true);
2388 } else {
2389 return -1;
2390 }
2391 return 0;
2392 }
2393 case "stop": {
2394 int res = shell.parseUserPackageOp(true, err);
2395 if (res < 0) {
2396 return res;
2397 }
2398
2399 if (shell.packageName != null) {
2400 shell.mInterface.finishOperation(shell.mToken,
2401 shell.op, shell.packageUid, shell.packageName);
2402 } else {
2403 return -1;
2404 }
2405 return 0;
2406 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002407 default:
2408 return shell.handleDefaultCommands(cmd);
2409 }
2410 } catch (RemoteException e) {
2411 pw.println("Remote exception: " + e);
2412 }
2413 return -1;
2414 }
2415
2416 private void dumpHelp(PrintWriter pw) {
2417 pw.println("AppOps service (appops) dump options:");
2418 pw.println(" none");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002419 }
2420
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002421 @Override
2422 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002423 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002424
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002425 if (args != null) {
2426 for (int i=0; i<args.length; i++) {
2427 String arg = args[i];
2428 if ("-h".equals(arg)) {
2429 dumpHelp(pw);
2430 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07002431 } else if ("-a".equals(arg)) {
2432 // dump all data
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002433 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
2434 pw.println("Unknown option: " + arg);
2435 return;
2436 } else {
2437 pw.println("Unknown command: " + arg);
2438 return;
2439 }
2440 }
2441 }
2442
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002443 synchronized (this) {
2444 pw.println("Current AppOps Service state:");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002445 final long now = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002446 boolean needSep = false;
2447 if (mOpModeWatchers.size() > 0) {
2448 needSep = true;
2449 pw.println(" Op mode watchers:");
2450 for (int i=0; i<mOpModeWatchers.size(); i++) {
2451 pw.print(" Op "); pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
2452 pw.println(":");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002453 ArraySet<ModeCallback> callbacks = mOpModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002454 for (int j=0; j<callbacks.size(); j++) {
2455 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08002456 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002457 }
2458 }
2459 }
2460 if (mPackageModeWatchers.size() > 0) {
2461 needSep = true;
2462 pw.println(" Package mode watchers:");
2463 for (int i=0; i<mPackageModeWatchers.size(); i++) {
2464 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
2465 pw.println(":");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002466 ArraySet<ModeCallback> callbacks = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002467 for (int j=0; j<callbacks.size(); j++) {
2468 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08002469 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002470 }
2471 }
2472 }
2473 if (mModeWatchers.size() > 0) {
2474 needSep = true;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002475 pw.println(" All op mode watchers:");
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002476 for (int i=0; i<mModeWatchers.size(); i++) {
2477 pw.print(" "); pw.print(mModeWatchers.keyAt(i));
2478 pw.print(" -> "); pw.println(mModeWatchers.valueAt(i));
2479 }
2480 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002481 if (mActiveWatchers.size() > 0) {
2482 needSep = true;
2483 pw.println(" All op active watchers:");
2484 for (int i = 0; i < mActiveWatchers.size(); i++) {
2485 final SparseArray<ActiveCallback> activeWatchers = mActiveWatchers.valueAt(i);
2486 if (activeWatchers.size() <= 0) {
2487 continue;
2488 }
2489 pw.print(" "); pw.print(mActiveWatchers.keyAt(i));
2490 pw.print(" -> [");
2491 final int opCount = activeWatchers.size();
2492 for (i = 0; i < opCount; i++) {
2493 pw.print(AppOpsManager.opToName(activeWatchers.keyAt(i)));
2494 if (i < opCount - 1) {
2495 pw.print(',');
2496 }
2497 }
2498 pw.print("]" ); pw.println(activeWatchers.valueAt(0));
2499 }
2500 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002501 if (mClients.size() > 0) {
2502 needSep = true;
2503 pw.println(" Clients:");
2504 for (int i=0; i<mClients.size(); i++) {
2505 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
2506 ClientState cs = mClients.valueAt(i);
2507 pw.print(" "); pw.println(cs);
Svet Ganovf7b47252018-02-26 11:11:27 -08002508 if (cs.mStartedOps.size() > 0) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002509 pw.println(" Started ops:");
2510 for (int j=0; j<cs.mStartedOps.size(); j++) {
2511 Op op = cs.mStartedOps.get(j);
2512 pw.print(" "); pw.print("uid="); pw.print(op.uid);
2513 pw.print(" pkg="); pw.print(op.packageName);
2514 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
2515 }
2516 }
2517 }
2518 }
John Spurlock1af30c72014-03-10 08:33:35 -04002519 if (mAudioRestrictions.size() > 0) {
2520 boolean printedHeader = false;
2521 for (int o=0; o<mAudioRestrictions.size(); o++) {
2522 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
2523 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
2524 for (int i=0; i<restrictions.size(); i++) {
2525 if (!printedHeader){
2526 pw.println(" Audio Restrictions:");
2527 printedHeader = true;
2528 needSep = true;
2529 }
John Spurlock7b414672014-07-18 13:02:39 -04002530 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04002531 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04002532 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04002533 Restriction r = restrictions.valueAt(i);
2534 pw.print(": mode="); pw.println(r.mode);
2535 if (!r.exceptionPackages.isEmpty()) {
2536 pw.println(" Exceptions:");
2537 for (int j=0; j<r.exceptionPackages.size(); j++) {
2538 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
2539 }
2540 }
2541 }
2542 }
2543 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002544 if (needSep) {
2545 pw.println();
2546 }
Svet Ganov2af57082015-07-30 08:44:20 -07002547 for (int i=0; i<mUidStates.size(); i++) {
2548 UidState uidState = mUidStates.valueAt(i);
2549
2550 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
Svet Ganovee438d42017-01-19 18:04:38 -08002551 needSep = true;
Svet Ganov2af57082015-07-30 08:44:20 -07002552
2553 SparseIntArray opModes = uidState.opModes;
2554 if (opModes != null) {
2555 final int opModeCount = opModes.size();
2556 for (int j = 0; j < opModeCount; j++) {
2557 final int code = opModes.keyAt(j);
2558 final int mode = opModes.valueAt(j);
2559 pw.print(" "); pw.print(AppOpsManager.opToName(code));
2560 pw.print(": mode="); pw.println(mode);
2561 }
2562 }
2563
2564 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
2565 if (pkgOps == null) {
2566 continue;
2567 }
2568
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002569 for (Ops ops : pkgOps.values()) {
2570 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
2571 for (int j=0; j<ops.size(); j++) {
2572 Op op = ops.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002573 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
2574 pw.print(": mode="); pw.print(op.mode);
2575 if (op.time != 0) {
2576 pw.print("; time="); TimeUtils.formatDuration(now-op.time, pw);
2577 pw.print(" ago");
2578 }
2579 if (op.rejectTime != 0) {
2580 pw.print("; rejectTime="); TimeUtils.formatDuration(now-op.rejectTime, pw);
2581 pw.print(" ago");
2582 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002583 if (op.duration == -1) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002584 pw.print(" (running)");
2585 } else if (op.duration != 0) {
2586 pw.print("; duration="); TimeUtils.formatDuration(op.duration, pw);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002587 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002588 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002589 }
2590 }
2591 }
Svet Ganovee438d42017-01-19 18:04:38 -08002592 if (needSep) {
2593 pw.println();
2594 }
2595
2596 final int userRestrictionCount = mOpUserRestrictions.size();
2597 for (int i = 0; i < userRestrictionCount; i++) {
2598 IBinder token = mOpUserRestrictions.keyAt(i);
2599 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
2600 pw.println(" User restrictions for token " + token + ":");
2601
2602 final int restrictionCount = restrictionState.perUserRestrictions != null
2603 ? restrictionState.perUserRestrictions.size() : 0;
2604 if (restrictionCount > 0) {
2605 pw.println(" Restricted ops:");
2606 for (int j = 0; j < restrictionCount; j++) {
2607 int userId = restrictionState.perUserRestrictions.keyAt(j);
2608 boolean[] restrictedOps = restrictionState.perUserRestrictions.valueAt(j);
2609 if (restrictedOps == null) {
2610 continue;
2611 }
2612 StringBuilder restrictedOpsValue = new StringBuilder();
2613 restrictedOpsValue.append("[");
2614 final int restrictedOpCount = restrictedOps.length;
2615 for (int k = 0; k < restrictedOpCount; k++) {
2616 if (restrictedOps[k]) {
2617 if (restrictedOpsValue.length() > 1) {
2618 restrictedOpsValue.append(", ");
2619 }
2620 restrictedOpsValue.append(AppOpsManager.opToName(k));
2621 }
2622 }
2623 restrictedOpsValue.append("]");
2624 pw.print(" "); pw.print("user: "); pw.print(userId);
2625 pw.print(" restricted ops: "); pw.println(restrictedOpsValue);
2626 }
2627 }
2628
2629 final int excludedPackageCount = restrictionState.perUserExcludedPackages != null
2630 ? restrictionState.perUserExcludedPackages.size() : 0;
2631 if (excludedPackageCount > 0) {
2632 pw.println(" Excluded packages:");
2633 for (int j = 0; j < excludedPackageCount; j++) {
2634 int userId = restrictionState.perUserExcludedPackages.keyAt(j);
2635 String[] packageNames = restrictionState.perUserExcludedPackages.valueAt(j);
2636 pw.print(" "); pw.print("user: "); pw.print(userId);
2637 pw.print(" packages: "); pw.println(Arrays.toString(packageNames));
2638 }
2639 }
2640 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002641 }
2642 }
John Spurlock1af30c72014-03-10 08:33:35 -04002643
2644 private static final class Restriction {
2645 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
2646 int mode;
2647 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
2648 }
Jason Monk62062992014-05-06 09:55:28 -04002649
2650 @Override
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002651 public void setUserRestrictions(Bundle restrictions, IBinder token, int userHandle) {
Jason Monk62062992014-05-06 09:55:28 -04002652 checkSystemUid("setUserRestrictions");
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002653 Preconditions.checkNotNull(restrictions);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002654 Preconditions.checkNotNull(token);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002655 for (int i = 0; i < AppOpsManager._NUM_OP; i++) {
Jason Monk62062992014-05-06 09:55:28 -04002656 String restriction = AppOpsManager.opToRestriction(i);
Suprabh Shukla64e0dcb2016-05-24 16:23:11 -07002657 if (restriction != null) {
2658 setUserRestrictionNoCheck(i, restrictions.getBoolean(restriction, false), token,
2659 userHandle, null);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002660 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002661 }
2662 }
2663
2664 @Override
Ruben Brunk29931bc2016-03-11 00:24:26 -08002665 public void setUserRestriction(int code, boolean restricted, IBinder token, int userHandle,
2666 String[] exceptionPackages) {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002667 if (Binder.getCallingPid() != Process.myPid()) {
2668 mContext.enforcePermission(Manifest.permission.MANAGE_APP_OPS_RESTRICTIONS,
2669 Binder.getCallingPid(), Binder.getCallingUid(), null);
2670 }
2671 if (userHandle != UserHandle.getCallingUserId()) {
2672 if (mContext.checkCallingOrSelfPermission(Manifest.permission
2673 .INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
2674 && mContext.checkCallingOrSelfPermission(Manifest.permission
2675 .INTERACT_ACROSS_USERS) != PackageManager.PERMISSION_GRANTED) {
2676 throw new SecurityException("Need INTERACT_ACROSS_USERS_FULL or"
2677 + " INTERACT_ACROSS_USERS to interact cross user ");
Jason Monk62062992014-05-06 09:55:28 -04002678 }
2679 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002680 verifyIncomingOp(code);
2681 Preconditions.checkNotNull(token);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002682 setUserRestrictionNoCheck(code, restricted, token, userHandle, exceptionPackages);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002683 }
2684
2685 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
Ruben Brunk29931bc2016-03-11 00:24:26 -08002686 int userHandle, String[] exceptionPackages) {
Svet Ganov442ed572016-08-17 17:29:43 -07002687 synchronized (AppOpsService.this) {
2688 ClientRestrictionState restrictionState = mOpUserRestrictions.get(token);
2689
2690 if (restrictionState == null) {
2691 try {
2692 restrictionState = new ClientRestrictionState(token);
2693 } catch (RemoteException e) {
2694 return;
2695 }
2696 mOpUserRestrictions.put(token, restrictionState);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002697 }
Svet Ganov442ed572016-08-17 17:29:43 -07002698
2699 if (restrictionState.setRestriction(code, restricted, exceptionPackages, userHandle)) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002700 mHandler.sendMessage(PooledLambda.obtainMessage(
2701 AppOpsService::notifyWatchersOfChange, this, code));
Svet Ganov442ed572016-08-17 17:29:43 -07002702 }
2703
2704 if (restrictionState.isDefault()) {
2705 mOpUserRestrictions.remove(token);
2706 restrictionState.destroy();
2707 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002708 }
Julia Reynoldsbb21c252016-04-05 16:01:49 -04002709 }
2710
2711 private void notifyWatchersOfChange(int code) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002712 final ArraySet<ModeCallback> clonedCallbacks;
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002713 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002714 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002715 if (callbacks == null) {
2716 return;
2717 }
Dianne Hackborn68d76552017-02-27 15:32:03 -08002718 clonedCallbacks = new ArraySet<>(callbacks);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002719 }
2720
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002721 notifyOpChanged(clonedCallbacks, code, -1, null);
Jason Monk62062992014-05-06 09:55:28 -04002722 }
2723
2724 @Override
2725 public void removeUser(int userHandle) throws RemoteException {
2726 checkSystemUid("removeUser");
Svet Ganov442ed572016-08-17 17:29:43 -07002727 synchronized (AppOpsService.this) {
2728 final int tokenCount = mOpUserRestrictions.size();
2729 for (int i = tokenCount - 1; i >= 0; i--) {
2730 ClientRestrictionState opRestrictions = mOpUserRestrictions.valueAt(i);
2731 opRestrictions.removeUser(userHandle);
2732 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002733 removeUidsForUserLocked(userHandle);
2734 }
2735 }
2736
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002737 @Override
2738 public boolean isOperationActive(int code, int uid, String packageName) {
Svet Ganovf7b47252018-02-26 11:11:27 -08002739 if (Binder.getCallingUid() != uid) {
2740 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
2741 != PackageManager.PERMISSION_GRANTED) {
2742 return false;
2743 }
2744 }
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002745 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002746 final String resolvedPackageName = resolvePackageName(uid, packageName);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002747 if (resolvedPackageName == null) {
2748 return false;
2749 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002750 synchronized (AppOpsService.this) {
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002751 for (int i = mClients.size() - 1; i >= 0; i--) {
2752 final ClientState client = mClients.valueAt(i);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002753 for (int j = client.mStartedOps.size() - 1; j >= 0; j--) {
2754 final Op op = client.mStartedOps.get(j);
2755 if (op.op == code && op.uid == uid) return true;
2756 }
2757 }
2758 }
2759 return false;
2760 }
2761
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002762 private void removeUidsForUserLocked(int userHandle) {
2763 for (int i = mUidStates.size() - 1; i >= 0; --i) {
2764 final int uid = mUidStates.keyAt(i);
2765 if (UserHandle.getUserId(uid) == userHandle) {
2766 mUidStates.removeAt(i);
2767 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002768 }
2769 }
2770
Jason Monk62062992014-05-06 09:55:28 -04002771 private void checkSystemUid(String function) {
2772 int uid = Binder.getCallingUid();
2773 if (uid != Process.SYSTEM_UID) {
2774 throw new SecurityException(function + " must by called by the system");
2775 }
2776 }
2777
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002778 private static String resolvePackageName(int uid, String packageName) {
Svet Ganov82f09bc2018-01-12 22:08:40 -08002779 if (uid == Process.ROOT_UID) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002780 return "root";
2781 } else if (uid == Process.SHELL_UID) {
2782 return "com.android.shell";
Svet Ganov82f09bc2018-01-12 22:08:40 -08002783 } else if (uid == Process.MEDIA_UID) {
2784 return "media";
2785 } else if (uid == Process.AUDIOSERVER_UID) {
2786 return "audioserver";
2787 } else if (uid == Process.CAMERASERVER_UID) {
2788 return "cameraserver";
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002789 } else if (uid == Process.SYSTEM_UID && packageName == null) {
2790 return "android";
2791 }
2792 return packageName;
2793 }
2794
Svet Ganov82f09bc2018-01-12 22:08:40 -08002795 private static int resolveUid(String packageName) {
2796 if (packageName == null) {
2797 return -1;
2798 }
2799 switch (packageName) {
2800 case "root":
2801 return Process.ROOT_UID;
2802 case "shell":
2803 return Process.SHELL_UID;
2804 case "media":
2805 return Process.MEDIA_UID;
2806 case "audioserver":
2807 return Process.AUDIOSERVER_UID;
2808 case "cameraserver":
2809 return Process.CAMERASERVER_UID;
2810 }
2811 return -1;
2812 }
2813
Svet Ganov2af57082015-07-30 08:44:20 -07002814 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07002815 String[] packageNames = null;
Svet Ganov2af57082015-07-30 08:44:20 -07002816 try {
riddle_hsu40b300f2015-11-23 13:22:03 +08002817 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -07002818 } catch (RemoteException e) {
2819 /* ignore - local call */
2820 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07002821 if (packageNames == null) {
2822 return EmptyArray.STRING;
2823 }
2824 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07002825 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002826
2827 private final class ClientRestrictionState implements DeathRecipient {
2828 private final IBinder token;
2829 SparseArray<boolean[]> perUserRestrictions;
2830 SparseArray<String[]> perUserExcludedPackages;
2831
2832 public ClientRestrictionState(IBinder token)
2833 throws RemoteException {
2834 token.linkToDeath(this, 0);
2835 this.token = token;
2836 }
2837
2838 public boolean setRestriction(int code, boolean restricted,
2839 String[] excludedPackages, int userId) {
2840 boolean changed = false;
2841
2842 if (perUserRestrictions == null && restricted) {
2843 perUserRestrictions = new SparseArray<>();
2844 }
2845
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002846 int[] users;
2847 if (userId == UserHandle.USER_ALL) {
2848 List<UserInfo> liveUsers = UserManager.get(mContext).getUsers(false);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002849
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002850 users = new int[liveUsers.size()];
2851 for (int i = 0; i < liveUsers.size(); i++) {
2852 users[i] = liveUsers.get(i).id;
2853 }
2854 } else {
2855 users = new int[]{userId};
2856 }
2857
2858 if (perUserRestrictions != null) {
2859 int numUsers = users.length;
2860
2861 for (int i = 0; i < numUsers; i++) {
2862 int thisUserId = users[i];
2863
2864 boolean[] userRestrictions = perUserRestrictions.get(thisUserId);
2865 if (userRestrictions == null && restricted) {
2866 userRestrictions = new boolean[AppOpsManager._NUM_OP];
2867 perUserRestrictions.put(thisUserId, userRestrictions);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002868 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002869 if (userRestrictions != null && userRestrictions[code] != restricted) {
2870 userRestrictions[code] = restricted;
2871 if (!restricted && isDefault(userRestrictions)) {
2872 perUserRestrictions.remove(thisUserId);
2873 userRestrictions = null;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002874 }
2875 changed = true;
2876 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002877
2878 if (userRestrictions != null) {
2879 final boolean noExcludedPackages = ArrayUtils.isEmpty(excludedPackages);
2880 if (perUserExcludedPackages == null && !noExcludedPackages) {
2881 perUserExcludedPackages = new SparseArray<>();
2882 }
2883 if (perUserExcludedPackages != null && !Arrays.equals(excludedPackages,
2884 perUserExcludedPackages.get(thisUserId))) {
2885 if (noExcludedPackages) {
2886 perUserExcludedPackages.remove(thisUserId);
2887 if (perUserExcludedPackages.size() <= 0) {
2888 perUserExcludedPackages = null;
2889 }
2890 } else {
2891 perUserExcludedPackages.put(thisUserId, excludedPackages);
2892 }
2893 changed = true;
2894 }
2895 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002896 }
2897 }
2898
2899 return changed;
2900 }
2901
2902 public boolean hasRestriction(int restriction, String packageName, int userId) {
2903 if (perUserRestrictions == null) {
2904 return false;
2905 }
2906 boolean[] restrictions = perUserRestrictions.get(userId);
2907 if (restrictions == null) {
2908 return false;
2909 }
2910 if (!restrictions[restriction]) {
2911 return false;
2912 }
2913 if (perUserExcludedPackages == null) {
2914 return true;
2915 }
2916 String[] perUserExclusions = perUserExcludedPackages.get(userId);
2917 if (perUserExclusions == null) {
2918 return true;
2919 }
2920 return !ArrayUtils.contains(perUserExclusions, packageName);
2921 }
2922
2923 public void removeUser(int userId) {
2924 if (perUserExcludedPackages != null) {
2925 perUserExcludedPackages.remove(userId);
2926 if (perUserExcludedPackages.size() <= 0) {
2927 perUserExcludedPackages = null;
2928 }
2929 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002930 if (perUserRestrictions != null) {
2931 perUserRestrictions.remove(userId);
2932 if (perUserRestrictions.size() <= 0) {
2933 perUserRestrictions = null;
2934 }
2935 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002936 }
2937
2938 public boolean isDefault() {
2939 return perUserRestrictions == null || perUserRestrictions.size() <= 0;
2940 }
2941
2942 @Override
2943 public void binderDied() {
2944 synchronized (AppOpsService.this) {
2945 mOpUserRestrictions.remove(token);
2946 if (perUserRestrictions == null) {
2947 return;
2948 }
2949 final int userCount = perUserRestrictions.size();
2950 for (int i = 0; i < userCount; i++) {
2951 final boolean[] restrictions = perUserRestrictions.valueAt(i);
2952 final int restrictionCount = restrictions.length;
2953 for (int j = 0; j < restrictionCount; j++) {
2954 if (restrictions[j]) {
2955 final int changedCode = j;
2956 mHandler.post(() -> notifyWatchersOfChange(changedCode));
2957 }
2958 }
2959 }
2960 destroy();
2961 }
2962 }
2963
2964 public void destroy() {
2965 token.unlinkToDeath(this, 0);
2966 }
2967
2968 private boolean isDefault(boolean[] array) {
2969 if (ArrayUtils.isEmpty(array)) {
2970 return true;
2971 }
2972 for (boolean value : array) {
2973 if (value) {
2974 return false;
2975 }
2976 }
2977 return true;
2978 }
2979 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002980}