blob: d46734c5c2c07adbd1e6c3485184e85dfe8d5e6d [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
Svet Ganov3a95f832018-03-23 17:44:30 -0700100 // Constant meaning that any UID should be matched when dispatching callbacks
101 private static final int UID_ANY = -2;
102
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800103 Context mContext;
104 final AtomicFile mFile;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800105 final Handler mHandler;
106
107 boolean mWriteScheduled;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800108 boolean mFastWriteScheduled;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800109 final Runnable mWriteRunner = new Runnable() {
110 public void run() {
111 synchronized (AppOpsService.this) {
112 mWriteScheduled = false;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800113 mFastWriteScheduled = false;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800114 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
115 @Override protected Void doInBackground(Void... params) {
116 writeState();
117 return null;
118 }
119 };
120 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
121 }
122 }
123 };
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800124
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700125 @VisibleForTesting
126 final SparseArray<UidState> mUidStates = new SparseArray<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800127
Ruben Brunk29931bc2016-03-11 00:24:26 -0800128 /*
129 * These are app op restrictions imposed per user from various parties.
Ruben Brunk29931bc2016-03-11 00:24:26 -0800130 */
Svetoslav Ganova8bbd762016-05-13 17:08:16 -0700131 private final ArrayMap<IBinder, ClientRestrictionState> mOpUserRestrictions = new ArrayMap<>();
Jason Monk62062992014-05-06 09:55:28 -0400132
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700133 @VisibleForTesting
134 static final class UidState {
Svet Ganov2af57082015-07-30 08:44:20 -0700135 public final int uid;
136 public ArrayMap<String, Ops> pkgOps;
137 public SparseIntArray opModes;
138
139 public UidState(int uid) {
140 this.uid = uid;
141 }
142
143 public void clear() {
144 pkgOps = null;
145 opModes = null;
146 }
147
148 public boolean isDefault() {
149 return (pkgOps == null || pkgOps.isEmpty())
150 && (opModes == null || opModes.size() <= 0);
151 }
152 }
153
Dianne Hackbornc2293022013-02-06 23:14:49 -0800154 public final static class Ops extends SparseArray<Op> {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800155 public final String packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700156 public final UidState uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400157 public final boolean isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800158
Svet Ganov2af57082015-07-30 08:44:20 -0700159 public Ops(String _packageName, UidState _uidState, boolean _isPrivileged) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800160 packageName = _packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700161 uidState = _uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400162 isPrivileged = _isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800163 }
164 }
165
Dianne Hackbornc2293022013-02-06 23:14:49 -0800166 public final static class Op {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700167 public final int uid;
168 public final String packageName;
Svet Ganov99b60432015-06-27 13:15:22 -0700169 public int proxyUid = -1;
170 public String proxyPackageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800171 public final int op;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800172 public int mode;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800173 public int duration;
174 public long time;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800175 public long rejectTime;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800176 public int nesting;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800177
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700178 public Op(int _uid, String _packageName, int _op) {
179 uid = _uid;
180 packageName = _packageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800181 op = _op;
David Braunf5d83192013-09-16 13:43:51 -0700182 mode = AppOpsManager.opToDefaultMode(op);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800183 }
184 }
185
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800186 final SparseArray<ArraySet<ModeCallback>> mOpModeWatchers = new SparseArray<>();
187 final ArrayMap<String, ArraySet<ModeCallback>> mPackageModeWatchers = new ArrayMap<>();
188 final ArrayMap<IBinder, ModeCallback> mModeWatchers = new ArrayMap<>();
189 final ArrayMap<IBinder, SparseArray<ActiveCallback>> mActiveWatchers = new ArrayMap<>();
Dianne Hackborn68d76552017-02-27 15:32:03 -0800190 final SparseArray<SparseArray<Restriction>> mAudioRestrictions = new SparseArray<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800191
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800192 public final class ModeCallback implements DeathRecipient {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800193 final IAppOpsCallback mCallback;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800194 final int mUid;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800195
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800196 public ModeCallback(IAppOpsCallback callback, int uid) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800197 mCallback = callback;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800198 mUid = uid;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800199 try {
200 mCallback.asBinder().linkToDeath(this, 0);
201 } catch (RemoteException e) {
202 }
203 }
204
205 public void unlinkToDeath() {
206 mCallback.asBinder().unlinkToDeath(this, 0);
207 }
208
209 @Override
210 public void binderDied() {
211 stopWatchingMode(mCallback);
212 }
213 }
214
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800215 public final class ActiveCallback implements DeathRecipient {
216 final IAppOpsActiveCallback mCallback;
Svet Ganovf7b47252018-02-26 11:11:27 -0800217 final int mUid;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800218
Svet Ganovf7b47252018-02-26 11:11:27 -0800219 public ActiveCallback(IAppOpsActiveCallback callback, int uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800220 mCallback = callback;
Svet Ganovf7b47252018-02-26 11:11:27 -0800221 mUid = uid;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800222 try {
223 mCallback.asBinder().linkToDeath(this, 0);
224 } catch (RemoteException e) {
225 }
226 }
227
228 public void destroy() {
229 mCallback.asBinder().unlinkToDeath(this, 0);
230 }
231
232 @Override
233 public void binderDied() {
234 stopWatchingActive(mCallback);
235 }
236 }
237
Svet Ganova7a0db62018-02-27 20:08:01 -0800238 final ArrayMap<IBinder, ClientState> mClients = new ArrayMap<>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700239
240 public final class ClientState extends Binder implements DeathRecipient {
Svet Ganovf7b47252018-02-26 11:11:27 -0800241 final ArrayList<Op> mStartedOps = new ArrayList<>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700242 final IBinder mAppToken;
243 final int mPid;
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700244
245 public ClientState(IBinder appToken) {
246 mAppToken = appToken;
247 mPid = Binder.getCallingPid();
Svet Ganovf7b47252018-02-26 11:11:27 -0800248 // Watch only for remote processes dying
249 if (!(appToken instanceof Binder)) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700250 try {
251 mAppToken.linkToDeath(this, 0);
252 } catch (RemoteException e) {
Svet Ganovf7b47252018-02-26 11:11:27 -0800253 /* do nothing */
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700254 }
255 }
256 }
257
258 @Override
259 public String toString() {
260 return "ClientState{" +
261 "mAppToken=" + mAppToken +
Svet Ganovf7b47252018-02-26 11:11:27 -0800262 ", " + "pid=" + mPid +
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700263 '}';
264 }
265
266 @Override
267 public void binderDied() {
268 synchronized (AppOpsService.this) {
269 for (int i=mStartedOps.size()-1; i>=0; i--) {
Svet Ganova7a0db62018-02-27 20:08:01 -0800270 finishOperationLocked(mStartedOps.get(i), /*finishNested*/ true);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700271 }
272 mClients.remove(mAppToken);
273 }
274 }
275 }
276
Jeff Brown6f357d32014-01-15 20:40:55 -0800277 public AppOpsService(File storagePath, Handler handler) {
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600278 LockGuard.installLock(this, LockGuard.INDEX_APP_OPS);
Dianne Hackborne17b4452018-01-10 13:15:40 -0800279 mFile = new AtomicFile(storagePath, "appops");
Jeff Brown6f357d32014-01-15 20:40:55 -0800280 mHandler = handler;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800281 readState();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800282 }
David Braunf5d83192013-09-16 13:43:51 -0700283
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800284 public void publish(Context context) {
285 mContext = context;
286 ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
287 }
288
Dianne Hackborn514074f2013-02-11 10:52:46 -0800289 public void systemReady() {
290 synchronized (this) {
291 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700292 for (int i = mUidStates.size() - 1; i >= 0; i--) {
293 UidState uidState = mUidStates.valueAt(i);
294
295 String[] packageNames = getPackagesForUid(uidState.uid);
296 if (ArrayUtils.isEmpty(packageNames)) {
297 uidState.clear();
298 mUidStates.removeAt(i);
299 changed = true;
300 continue;
301 }
302
303 ArrayMap<String, Ops> pkgs = uidState.pkgOps;
304 if (pkgs == null) {
305 continue;
306 }
307
Dianne Hackborn514074f2013-02-11 10:52:46 -0800308 Iterator<Ops> it = pkgs.values().iterator();
309 while (it.hasNext()) {
310 Ops ops = it.next();
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700311 int curUid = -1;
Dianne Hackborn514074f2013-02-11 10:52:46 -0800312 try {
Jeff Sharkeycd654482016-01-08 17:42:11 -0700313 curUid = AppGlobals.getPackageManager().getPackageUid(ops.packageName,
314 PackageManager.MATCH_UNINSTALLED_PACKAGES,
Svet Ganov2af57082015-07-30 08:44:20 -0700315 UserHandle.getUserId(ops.uidState.uid));
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700316 } catch (RemoteException ignored) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800317 }
Svet Ganov2af57082015-07-30 08:44:20 -0700318 if (curUid != ops.uidState.uid) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800319 Slog.i(TAG, "Pruning old package " + ops.packageName
Svet Ganov2af57082015-07-30 08:44:20 -0700320 + "/" + ops.uidState + ": new uid=" + curUid);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800321 it.remove();
322 changed = true;
323 }
324 }
Svet Ganov2af57082015-07-30 08:44:20 -0700325
326 if (uidState.isDefault()) {
327 mUidStates.removeAt(i);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800328 }
329 }
330 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800331 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800332 }
333 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700334
Suprabh Shuklaaef25132017-01-23 18:09:03 -0800335 PackageManagerInternal packageManagerInternal = LocalServices.getService(
336 PackageManagerInternal.class);
337 packageManagerInternal.setExternalSourcesPolicy(
338 new PackageManagerInternal.ExternalSourcesPolicy() {
339 @Override
340 public int getPackageTrustedToInstallApps(String packageName, int uid) {
341 int appOpMode = checkOperation(AppOpsManager.OP_REQUEST_INSTALL_PACKAGES,
342 uid, packageName);
343 switch (appOpMode) {
344 case AppOpsManager.MODE_ALLOWED:
345 return PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
346 case AppOpsManager.MODE_ERRORED:
347 return PackageManagerInternal.ExternalSourcesPolicy.USER_BLOCKED;
348 default:
349 return PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT;
350 }
351 }
352 });
353
Sudheer Shanka2250d562016-11-07 15:41:02 -0800354 StorageManagerInternal storageManagerInternal = LocalServices.getService(
355 StorageManagerInternal.class);
356 storageManagerInternal.addExternalStoragePolicy(
357 new StorageManagerInternal.ExternalStorageMountPolicy() {
Svet Ganov6ee871e2015-07-10 14:29:33 -0700358 @Override
359 public int getMountMode(int uid, String packageName) {
360 if (Process.isIsolated(uid)) {
361 return Zygote.MOUNT_EXTERNAL_NONE;
362 }
363 if (noteOperation(AppOpsManager.OP_READ_EXTERNAL_STORAGE, uid,
364 packageName) != AppOpsManager.MODE_ALLOWED) {
365 return Zygote.MOUNT_EXTERNAL_NONE;
366 }
367 if (noteOperation(AppOpsManager.OP_WRITE_EXTERNAL_STORAGE, uid,
368 packageName) != AppOpsManager.MODE_ALLOWED) {
369 return Zygote.MOUNT_EXTERNAL_READ;
370 }
371 return Zygote.MOUNT_EXTERNAL_WRITE;
372 }
373
374 @Override
375 public boolean hasExternalStorage(int uid, String packageName) {
376 final int mountMode = getMountMode(uid, packageName);
377 return mountMode == Zygote.MOUNT_EXTERNAL_READ
378 || mountMode == Zygote.MOUNT_EXTERNAL_WRITE;
379 }
380 });
Dianne Hackborn514074f2013-02-11 10:52:46 -0800381 }
382
383 public void packageRemoved(int uid, String packageName) {
384 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700385 UidState uidState = mUidStates.get(uid);
386 if (uidState == null) {
387 return;
388 }
389
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800390 Ops ops = null;
Svet Ganov2af57082015-07-30 08:44:20 -0700391
392 // Remove any package state if such.
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800393 if (uidState.pkgOps != null) {
394 ops = uidState.pkgOps.remove(packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700395 }
396
397 // If we just nuked the last package state check if the UID is valid.
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800398 if (ops != null && uidState.pkgOps.isEmpty()
Svet Ganov2af57082015-07-30 08:44:20 -0700399 && getPackagesForUid(uid).length <= 0) {
400 mUidStates.remove(uid);
401 }
402
Svet Ganova7a0db62018-02-27 20:08:01 -0800403 // Finish ops other packages started on behalf of the package.
404 final int clientCount = mClients.size();
405 for (int i = 0; i < clientCount; i++) {
406 final ClientState client = mClients.valueAt(i);
407 if (client.mStartedOps == null) {
408 continue;
409 }
410 final int opCount = client.mStartedOps.size();
411 for (int j = opCount - 1; j >= 0; j--) {
412 final Op op = client.mStartedOps.get(j);
413 if (uid == op.uid && packageName.equals(op.packageName)) {
414 finishOperationLocked(op, /*finishNested*/ true);
415 client.mStartedOps.remove(j);
416 if (op.nesting <= 0) {
417 scheduleOpActiveChangedIfNeededLocked(op.op,
418 uid, packageName, false);
419 }
420 }
421 }
422 }
423
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800424 if (ops != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700425 scheduleFastWriteLocked();
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800426
427 final int opCount = ops.size();
428 for (int i = 0; i < opCount; i++) {
429 final Op op = ops.valueAt(i);
430 if (op.duration == -1) {
431 scheduleOpActiveChangedIfNeededLocked(
432 op.op, op.uid, op.packageName, false);
433 }
434 }
Dianne Hackborn514074f2013-02-11 10:52:46 -0800435 }
436 }
437 }
438
439 public void uidRemoved(int uid) {
440 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700441 if (mUidStates.indexOfKey(uid) >= 0) {
442 mUidStates.remove(uid);
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800443 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800444 }
445 }
446 }
447
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800448 public void shutdown() {
449 Slog.w(TAG, "Writing app ops before shutdown...");
Dianne Hackborn35654b62013-01-14 17:38:02 -0800450 boolean doWrite = false;
451 synchronized (this) {
452 if (mWriteScheduled) {
453 mWriteScheduled = false;
454 doWrite = true;
455 }
456 }
457 if (doWrite) {
458 writeState();
459 }
460 }
461
Dianne Hackborn72e39832013-01-18 18:36:09 -0800462 private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
463 ArrayList<AppOpsManager.OpEntry> resOps = null;
464 if (ops == null) {
465 resOps = new ArrayList<AppOpsManager.OpEntry>();
466 for (int j=0; j<pkgOps.size(); j++) {
467 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800468 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Svet Ganov99b60432015-06-27 13:15:22 -0700469 curOp.rejectTime, curOp.duration, curOp.proxyUid,
470 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800471 }
472 } else {
473 for (int j=0; j<ops.length; j++) {
474 Op curOp = pkgOps.get(ops[j]);
475 if (curOp != null) {
476 if (resOps == null) {
477 resOps = new ArrayList<AppOpsManager.OpEntry>();
478 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800479 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Svet Ganov99b60432015-06-27 13:15:22 -0700480 curOp.rejectTime, curOp.duration, curOp.proxyUid,
481 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800482 }
483 }
484 }
485 return resOps;
486 }
487
Dianne Hackbornc7214a32017-04-11 13:32:47 -0700488 private ArrayList<AppOpsManager.OpEntry> collectOps(SparseIntArray uidOps, int[] ops) {
489 ArrayList<AppOpsManager.OpEntry> resOps = null;
490 if (ops == null) {
491 resOps = new ArrayList<>();
492 for (int j=0; j<uidOps.size(); j++) {
493 resOps.add(new AppOpsManager.OpEntry(uidOps.keyAt(j), uidOps.valueAt(j),
494 0, 0, 0, -1, null));
495 }
496 } else {
497 for (int j=0; j<ops.length; j++) {
498 int index = uidOps.indexOfKey(ops[j]);
499 if (index >= 0) {
500 if (resOps == null) {
501 resOps = new ArrayList<>();
502 }
503 resOps.add(new AppOpsManager.OpEntry(uidOps.keyAt(index), uidOps.valueAt(index),
504 0, 0, 0, -1, null));
505 }
506 }
507 }
508 return resOps;
509 }
510
Dianne Hackborn35654b62013-01-14 17:38:02 -0800511 @Override
512 public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
513 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
514 Binder.getCallingPid(), Binder.getCallingUid(), null);
515 ArrayList<AppOpsManager.PackageOps> res = null;
516 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700517 final int uidStateCount = mUidStates.size();
518 for (int i = 0; i < uidStateCount; i++) {
519 UidState uidState = mUidStates.valueAt(i);
520 if (uidState.pkgOps == null || uidState.pkgOps.isEmpty()) {
521 continue;
522 }
523 ArrayMap<String, Ops> packages = uidState.pkgOps;
524 final int packageCount = packages.size();
525 for (int j = 0; j < packageCount; j++) {
526 Ops pkgOps = packages.valueAt(j);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800527 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800528 if (resOps != null) {
529 if (res == null) {
530 res = new ArrayList<AppOpsManager.PackageOps>();
531 }
532 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700533 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800534 res.add(resPackage);
535 }
536 }
537 }
538 }
539 return res;
540 }
541
542 @Override
Dianne Hackborn72e39832013-01-18 18:36:09 -0800543 public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
544 int[] ops) {
545 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
546 Binder.getCallingPid(), Binder.getCallingUid(), null);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000547 String resolvedPackageName = resolvePackageName(uid, packageName);
548 if (resolvedPackageName == null) {
549 return Collections.emptyList();
550 }
Dianne Hackborn72e39832013-01-18 18:36:09 -0800551 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -0700552 Ops pkgOps = getOpsRawLocked(uid, resolvedPackageName, false /* edit */,
553 false /* uidMismatchExpected */);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800554 if (pkgOps == null) {
555 return null;
556 }
557 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
558 if (resOps == null) {
559 return null;
560 }
561 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
562 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700563 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800564 res.add(resPackage);
565 return res;
566 }
567 }
568
Dianne Hackbornc7214a32017-04-11 13:32:47 -0700569 @Override
570 public List<AppOpsManager.PackageOps> getUidOps(int uid, int[] ops) {
571 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
572 Binder.getCallingPid(), Binder.getCallingUid(), null);
573 synchronized (this) {
574 UidState uidState = getUidStateLocked(uid, false);
575 if (uidState == null) {
576 return null;
577 }
578 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(uidState.opModes, ops);
579 if (resOps == null) {
580 return null;
581 }
582 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
583 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
584 null, uidState.uid, resOps);
585 res.add(resPackage);
586 return res;
587 }
588 }
589
Dianne Hackborn607b4142013-08-02 18:10:10 -0700590 private void pruneOp(Op op, int uid, String packageName) {
591 if (op.time == 0 && op.rejectTime == 0) {
Yohei Yukawaa965d652017-10-12 15:02:26 -0700592 Ops ops = getOpsRawLocked(uid, packageName, false /* edit */,
593 false /* uidMismatchExpected */);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700594 if (ops != null) {
595 ops.remove(op.op);
596 if (ops.size() <= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -0700597 UidState uidState = ops.uidState;
598 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700599 if (pkgOps != null) {
600 pkgOps.remove(ops.packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700601 if (pkgOps.isEmpty()) {
602 uidState.pkgOps = null;
603 }
604 if (uidState.isDefault()) {
605 mUidStates.remove(uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700606 }
607 }
608 }
609 }
610 }
611 }
612
Dianne Hackborn72e39832013-01-18 18:36:09 -0800613 @Override
Svet Ganov2af57082015-07-30 08:44:20 -0700614 public void setUidMode(int code, int uid, int mode) {
615 if (Binder.getCallingPid() != Process.myPid()) {
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -0800616 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
Svet Ganov2af57082015-07-30 08:44:20 -0700617 Binder.getCallingPid(), Binder.getCallingUid(), null);
618 }
619 verifyIncomingOp(code);
620 code = AppOpsManager.opToSwitch(code);
621
622 synchronized (this) {
623 final int defaultMode = AppOpsManager.opToDefaultMode(code);
624
625 UidState uidState = getUidStateLocked(uid, false);
626 if (uidState == null) {
627 if (mode == defaultMode) {
628 return;
629 }
630 uidState = new UidState(uid);
631 uidState.opModes = new SparseIntArray();
632 uidState.opModes.put(code, mode);
633 mUidStates.put(uid, uidState);
634 scheduleWriteLocked();
635 } else if (uidState.opModes == null) {
636 if (mode != defaultMode) {
637 uidState.opModes = new SparseIntArray();
638 uidState.opModes.put(code, mode);
639 scheduleWriteLocked();
640 }
641 } else {
642 if (uidState.opModes.get(code) == mode) {
643 return;
644 }
645 if (mode == defaultMode) {
646 uidState.opModes.delete(code);
647 if (uidState.opModes.size() <= 0) {
648 uidState.opModes = null;
649 }
650 } else {
651 uidState.opModes.put(code, mode);
652 }
653 scheduleWriteLocked();
654 }
655 }
656
Svetoslav215b44a2015-08-04 19:03:40 -0700657 String[] uidPackageNames = getPackagesForUid(uid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800658 ArrayMap<ModeCallback, ArraySet<String>> callbackSpecs = null;
Svet Ganov2af57082015-07-30 08:44:20 -0700659
riddle_hsu40b300f2015-11-23 13:22:03 +0800660 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800661 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -0700662 if (callbacks != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700663 final int callbackCount = callbacks.size();
664 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800665 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +0800666 ArraySet<String> changedPackages = new ArraySet<>();
667 Collections.addAll(changedPackages, uidPackageNames);
668 callbackSpecs = new ArrayMap<>();
669 callbackSpecs.put(callback, changedPackages);
670 }
671 }
672
673 for (String uidPackageName : uidPackageNames) {
674 callbacks = mPackageModeWatchers.get(uidPackageName);
675 if (callbacks != null) {
676 if (callbackSpecs == null) {
677 callbackSpecs = new ArrayMap<>();
Svet Ganov2af57082015-07-30 08:44:20 -0700678 }
riddle_hsu40b300f2015-11-23 13:22:03 +0800679 final int callbackCount = callbacks.size();
680 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800681 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +0800682 ArraySet<String> changedPackages = callbackSpecs.get(callback);
683 if (changedPackages == null) {
684 changedPackages = new ArraySet<>();
685 callbackSpecs.put(callback, changedPackages);
686 }
687 changedPackages.add(uidPackageName);
688 }
Svet Ganov2af57082015-07-30 08:44:20 -0700689 }
690 }
691 }
692
693 if (callbackSpecs == null) {
694 return;
695 }
696
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800697 for (int i = 0; i < callbackSpecs.size(); i++) {
698 final ModeCallback callback = callbackSpecs.keyAt(i);
699 final ArraySet<String> reportedPackageNames = callbackSpecs.valueAt(i);
700 if (reportedPackageNames == null) {
701 mHandler.sendMessage(PooledLambda.obtainMessage(
702 AppOpsService::notifyOpChanged,
703 this, callback, code, uid, (String) null));
704
705 } else {
706 final int reportedPackageCount = reportedPackageNames.size();
707 for (int j = 0; j < reportedPackageCount; j++) {
708 final String reportedPackageName = reportedPackageNames.valueAt(j);
709 mHandler.sendMessage(PooledLambda.obtainMessage(
710 AppOpsService::notifyOpChanged,
711 this, callback, code, uid, reportedPackageName));
Svet Ganov2af57082015-07-30 08:44:20 -0700712 }
713 }
Svet Ganov2af57082015-07-30 08:44:20 -0700714 }
715 }
716
717 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800718 public void setMode(int code, int uid, String packageName, int mode) {
Dianne Hackbornb64afe12014-07-22 16:29:04 -0700719 if (Binder.getCallingPid() != Process.myPid()) {
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -0800720 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
Dianne Hackbornb64afe12014-07-22 16:29:04 -0700721 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborn133b9df2014-07-01 13:06:10 -0700722 }
Dianne Hackborn961321f2013-02-05 17:22:41 -0800723 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800724 ArraySet<ModeCallback> repCbs = null;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800725 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800726 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700727 UidState uidState = getUidStateLocked(uid, false);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800728 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800729 if (op != null) {
730 if (op.mode != mode) {
731 op.mode = mode;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800732 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800733 if (cbs != null) {
734 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800735 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800736 }
737 repCbs.addAll(cbs);
738 }
739 cbs = mPackageModeWatchers.get(packageName);
740 if (cbs != null) {
741 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800742 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800743 }
744 repCbs.addAll(cbs);
745 }
David Braunf5d83192013-09-16 13:43:51 -0700746 if (mode == AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800747 // If going into the default mode, prune this op
748 // if there is nothing else interesting in it.
Dianne Hackborn607b4142013-08-02 18:10:10 -0700749 pruneOp(op, uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800750 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800751 scheduleFastWriteLocked();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800752 }
753 }
754 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800755 if (repCbs != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800756 mHandler.sendMessage(PooledLambda.obtainMessage(
757 AppOpsService::notifyOpChanged,
758 this, repCbs, code, uid, packageName));
Dianne Hackbornc2293022013-02-06 23:14:49 -0800759 }
760 }
761
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800762 private void notifyOpChanged(ArraySet<ModeCallback> callbacks, int code,
763 int uid, String packageName) {
764 for (int i = 0; i < callbacks.size(); i++) {
765 final ModeCallback callback = callbacks.valueAt(i);
766 notifyOpChanged(callback, code, uid, packageName);
767 }
768 }
769
770 private void notifyOpChanged(ModeCallback callback, int code,
771 int uid, String packageName) {
Svet Ganov3a95f832018-03-23 17:44:30 -0700772 if (uid != UID_ANY && callback.mUid >= 0 && callback.mUid != uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800773 return;
774 }
775 // There are components watching for mode changes such as window manager
776 // and location manager which are in our process. The callbacks in these
777 // components may require permissions our remote caller does not have.
778 final long identity = Binder.clearCallingIdentity();
779 try {
780 callback.mCallback.opChanged(code, uid, packageName);
781 } catch (RemoteException e) {
782 /* ignore */
783 } finally {
784 Binder.restoreCallingIdentity(identity);
785 }
786 }
787
788 private static HashMap<ModeCallback, ArrayList<ChangeRec>> addCallbacks(
789 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks,
790 int op, int uid, String packageName, ArraySet<ModeCallback> cbs) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700791 if (cbs == null) {
792 return callbacks;
793 }
794 if (callbacks == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700795 callbacks = new HashMap<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700796 }
Svet Ganov2af57082015-07-30 08:44:20 -0700797 boolean duplicate = false;
Dianne Hackborn68d76552017-02-27 15:32:03 -0800798 final int N = cbs.size();
799 for (int i=0; i<N; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800800 ModeCallback cb = cbs.valueAt(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700801 ArrayList<ChangeRec> reports = callbacks.get(cb);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700802 if (reports == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700803 reports = new ArrayList<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700804 callbacks.put(cb, reports);
Svet Ganov2af57082015-07-30 08:44:20 -0700805 } else {
806 final int reportCount = reports.size();
807 for (int j = 0; j < reportCount; j++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700808 ChangeRec report = reports.get(j);
809 if (report.op == op && report.pkg.equals(packageName)) {
Svet Ganov2af57082015-07-30 08:44:20 -0700810 duplicate = true;
811 break;
812 }
813 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700814 }
Svet Ganov2af57082015-07-30 08:44:20 -0700815 if (!duplicate) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700816 reports.add(new ChangeRec(op, uid, packageName));
Svet Ganov2af57082015-07-30 08:44:20 -0700817 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700818 }
819 return callbacks;
820 }
821
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700822 static final class ChangeRec {
823 final int op;
824 final int uid;
825 final String pkg;
826
827 ChangeRec(int _op, int _uid, String _pkg) {
828 op = _op;
829 uid = _uid;
830 pkg = _pkg;
831 }
832 }
833
Dianne Hackborn607b4142013-08-02 18:10:10 -0700834 @Override
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800835 public void resetAllModes(int reqUserId, String reqPackageName) {
836 final int callingPid = Binder.getCallingPid();
837 final int callingUid = Binder.getCallingUid();
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -0800838 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800839 callingPid, callingUid, null);
840 reqUserId = ActivityManager.handleIncomingUser(callingPid, callingUid, reqUserId,
841 true, true, "resetAllModes", null);
Svet Ganov2af57082015-07-30 08:44:20 -0700842
843 int reqUid = -1;
844 if (reqPackageName != null) {
845 try {
846 reqUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -0700847 reqPackageName, PackageManager.MATCH_UNINSTALLED_PACKAGES, reqUserId);
Svet Ganov2af57082015-07-30 08:44:20 -0700848 } catch (RemoteException e) {
849 /* ignore - local call */
850 }
851 }
852
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800853 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks = null;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700854 synchronized (this) {
855 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700856 for (int i = mUidStates.size() - 1; i >= 0; i--) {
857 UidState uidState = mUidStates.valueAt(i);
858
859 SparseIntArray opModes = uidState.opModes;
860 if (opModes != null && (uidState.uid == reqUid || reqUid == -1)) {
861 final int uidOpCount = opModes.size();
862 for (int j = uidOpCount - 1; j >= 0; j--) {
863 final int code = opModes.keyAt(j);
864 if (AppOpsManager.opAllowsReset(code)) {
865 opModes.removeAt(j);
866 if (opModes.size() <= 0) {
867 uidState.opModes = null;
868 }
869 for (String packageName : getPackagesForUid(uidState.uid)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700870 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700871 mOpModeWatchers.get(code));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700872 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700873 mPackageModeWatchers.get(packageName));
874 }
875 }
876 }
877 }
878
879 if (uidState.pkgOps == null) {
880 continue;
881 }
882
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800883 if (reqUserId != UserHandle.USER_ALL
Svet Ganov2af57082015-07-30 08:44:20 -0700884 && reqUserId != UserHandle.getUserId(uidState.uid)) {
Alexandra Gherghinad6a98972014-08-04 17:05:34 +0100885 // Skip any ops for a different user
886 continue;
887 }
Svet Ganov2af57082015-07-30 08:44:20 -0700888
889 Map<String, Ops> packages = uidState.pkgOps;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700890 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
891 while (it.hasNext()) {
892 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700893 String packageName = ent.getKey();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800894 if (reqPackageName != null && !reqPackageName.equals(packageName)) {
895 // Skip any ops for a different package
896 continue;
897 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700898 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700899 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700900 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -0700901 if (AppOpsManager.opAllowsReset(curOp.op)
902 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -0700903 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700904 changed = true;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700905 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -0700906 mOpModeWatchers.get(curOp.op));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700907 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -0700908 mPackageModeWatchers.get(packageName));
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700909 if (curOp.time == 0 && curOp.rejectTime == 0) {
910 pkgOps.removeAt(j);
911 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700912 }
913 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700914 if (pkgOps.size() == 0) {
915 it.remove();
916 }
917 }
Svet Ganov2af57082015-07-30 08:44:20 -0700918 if (uidState.isDefault()) {
919 mUidStates.remove(uidState.uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700920 }
921 }
Svet Ganov2af57082015-07-30 08:44:20 -0700922
Dianne Hackborn607b4142013-08-02 18:10:10 -0700923 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800924 scheduleFastWriteLocked();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700925 }
926 }
927 if (callbacks != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800928 for (Map.Entry<ModeCallback, ArrayList<ChangeRec>> ent : callbacks.entrySet()) {
929 ModeCallback cb = ent.getKey();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700930 ArrayList<ChangeRec> reports = ent.getValue();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700931 for (int i=0; i<reports.size(); i++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700932 ChangeRec rep = reports.get(i);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800933 mHandler.sendMessage(PooledLambda.obtainMessage(
934 AppOpsService::notifyOpChanged,
935 this, cb, rep.op, rep.uid, rep.pkg));
Dianne Hackborn607b4142013-08-02 18:10:10 -0700936 }
937 }
938 }
939 }
940
Dianne Hackbornc2293022013-02-06 23:14:49 -0800941 @Override
942 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800943 int watchedUid = -1;
944 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
945 != PackageManager.PERMISSION_GRANTED) {
946 watchedUid = Binder.getCallingUid();
947 }
948 Preconditions.checkArgumentInRange(op, AppOpsManager.OP_NONE,
949 AppOpsManager._NUM_OP - 1, "Invalid op code: " + op);
Svetoslav Ganov8de59712015-12-09 18:25:13 -0800950 if (callback == null) {
951 return;
952 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800953 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700954 op = (op != AppOpsManager.OP_NONE) ? AppOpsManager.opToSwitch(op) : op;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800955 ModeCallback cb = mModeWatchers.get(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -0800956 if (cb == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800957 cb = new ModeCallback(callback, watchedUid);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800958 mModeWatchers.put(callback.asBinder(), cb);
959 }
960 if (op != AppOpsManager.OP_NONE) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800961 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(op);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800962 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800963 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800964 mOpModeWatchers.put(op, cbs);
965 }
966 cbs.add(cb);
967 }
968 if (packageName != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800969 ArraySet<ModeCallback> cbs = mPackageModeWatchers.get(packageName);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800970 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800971 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800972 mPackageModeWatchers.put(packageName, cbs);
973 }
974 cbs.add(cb);
975 }
976 }
977 }
978
979 @Override
980 public void stopWatchingMode(IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -0800981 if (callback == null) {
982 return;
983 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800984 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800985 ModeCallback cb = mModeWatchers.remove(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -0800986 if (cb != null) {
987 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700988 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800989 ArraySet<ModeCallback> cbs = mOpModeWatchers.valueAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800990 cbs.remove(cb);
991 if (cbs.size() <= 0) {
992 mOpModeWatchers.removeAt(i);
993 }
994 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700995 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800996 ArraySet<ModeCallback> cbs = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700997 cbs.remove(cb);
998 if (cbs.size() <= 0) {
999 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001000 }
1001 }
1002 }
1003 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001004 }
1005
1006 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001007 public IBinder getToken(IBinder clientToken) {
1008 synchronized (this) {
1009 ClientState cs = mClients.get(clientToken);
1010 if (cs == null) {
1011 cs = new ClientState(clientToken);
1012 mClients.put(clientToken, cs);
1013 }
1014 return cs;
1015 }
1016 }
1017
1018 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -08001019 public int checkOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001020 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001021 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001022 String resolvedPackageName = resolvePackageName(uid, packageName);
1023 if (resolvedPackageName == null) {
1024 return AppOpsManager.MODE_IGNORED;
1025 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001026 synchronized (this) {
Svet Ganov442ed572016-08-17 17:29:43 -07001027 if (isOpRestrictedLocked(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001028 return AppOpsManager.MODE_IGNORED;
1029 }
Svet Ganov2af57082015-07-30 08:44:20 -07001030 code = AppOpsManager.opToSwitch(code);
1031 UidState uidState = getUidStateLocked(uid, false);
Svet Ganovee438d42017-01-19 18:04:38 -08001032 if (uidState != null && uidState.opModes != null
1033 && uidState.opModes.indexOfKey(code) >= 0) {
1034 return uidState.opModes.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001035 }
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001036 Op op = getOpLocked(code, uid, resolvedPackageName, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001037 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -07001038 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001039 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001040 return op.mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001041 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001042 }
1043
1044 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001045 public int checkAudioOperation(int code, int usage, int uid, String packageName) {
Andrei Stingaceanuefc4a342016-03-22 14:43:01 +00001046 boolean suspended;
1047 try {
1048 suspended = isPackageSuspendedForUser(packageName, uid);
1049 } catch (IllegalArgumentException ex) {
1050 // Package not found.
1051 suspended = false;
1052 }
1053
1054 if (suspended) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001055 Slog.i(TAG, "Audio disabled for suspended package=" + packageName + " for uid=" + uid);
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001056 return AppOpsManager.MODE_IGNORED;
1057 }
1058
John Spurlock1af30c72014-03-10 08:33:35 -04001059 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001060 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -04001061 if (mode != AppOpsManager.MODE_ALLOWED) {
1062 return mode;
1063 }
1064 }
1065 return checkOperation(code, uid, packageName);
1066 }
1067
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001068 private boolean isPackageSuspendedForUser(String pkg, int uid) {
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001069 try {
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001070 return AppGlobals.getPackageManager().isPackageSuspendedForUser(
1071 pkg, UserHandle.getUserId(uid));
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001072 } catch (RemoteException re) {
1073 throw new SecurityException("Could not talk to package manager service");
1074 }
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001075 }
1076
John Spurlock7b414672014-07-18 13:02:39 -04001077 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
1078 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1079 if (usageRestrictions != null) {
1080 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001081 if (r != null && !r.exceptionPackages.contains(packageName)) {
1082 return r.mode;
1083 }
1084 }
1085 return AppOpsManager.MODE_ALLOWED;
1086 }
1087
1088 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001089 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -04001090 String[] exceptionPackages) {
1091 verifyIncomingUid(uid);
1092 verifyIncomingOp(code);
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -08001093 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
1094 Binder.getCallingPid(), Binder.getCallingUid(), null);
John Spurlock1af30c72014-03-10 08:33:35 -04001095 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001096 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1097 if (usageRestrictions == null) {
1098 usageRestrictions = new SparseArray<Restriction>();
1099 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -04001100 }
John Spurlock7b414672014-07-18 13:02:39 -04001101 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001102 if (mode != AppOpsManager.MODE_ALLOWED) {
1103 final Restriction r = new Restriction();
1104 r.mode = mode;
1105 if (exceptionPackages != null) {
1106 final int N = exceptionPackages.length;
1107 r.exceptionPackages = new ArraySet<String>(N);
1108 for (int i = 0; i < N; i++) {
1109 final String pkg = exceptionPackages[i];
1110 if (pkg != null) {
1111 r.exceptionPackages.add(pkg.trim());
1112 }
1113 }
1114 }
John Spurlock7b414672014-07-18 13:02:39 -04001115 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -04001116 }
1117 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001118
1119 mHandler.sendMessage(PooledLambda.obtainMessage(
Svet Ganov3a95f832018-03-23 17:44:30 -07001120 AppOpsService::notifyWatchersOfChange, this, code, UID_ANY));
John Spurlock1af30c72014-03-10 08:33:35 -04001121 }
1122
1123 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001124 public int checkPackage(int uid, String packageName) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001125 Preconditions.checkNotNull(packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001126 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001127 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1128 true /* uidMismatchExpected */);
1129 if (ops != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001130 return AppOpsManager.MODE_ALLOWED;
1131 } else {
1132 return AppOpsManager.MODE_ERRORED;
1133 }
1134 }
1135 }
1136
1137 @Override
Svet Ganov99b60432015-06-27 13:15:22 -07001138 public int noteProxyOperation(int code, String proxyPackageName,
1139 int proxiedUid, String proxiedPackageName) {
1140 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001141 final int proxyUid = Binder.getCallingUid();
1142 String resolveProxyPackageName = resolvePackageName(proxyUid, proxyPackageName);
1143 if (resolveProxyPackageName == null) {
1144 return AppOpsManager.MODE_IGNORED;
1145 }
1146 final int proxyMode = noteOperationUnchecked(code, proxyUid,
1147 resolveProxyPackageName, -1, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001148 if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
1149 return proxyMode;
1150 }
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001151 String resolveProxiedPackageName = resolvePackageName(proxiedUid, proxiedPackageName);
1152 if (resolveProxiedPackageName == null) {
1153 return AppOpsManager.MODE_IGNORED;
1154 }
1155 return noteOperationUnchecked(code, proxiedUid, resolveProxiedPackageName,
1156 proxyMode, resolveProxyPackageName);
Svet Ganov99b60432015-06-27 13:15:22 -07001157 }
1158
1159 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001160 public int noteOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001161 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001162 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001163 String resolvedPackageName = resolvePackageName(uid, packageName);
1164 if (resolvedPackageName == null) {
1165 return AppOpsManager.MODE_IGNORED;
1166 }
1167 return noteOperationUnchecked(code, uid, resolvedPackageName, 0, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001168 }
1169
1170 private int noteOperationUnchecked(int code, int uid, String packageName,
1171 int proxyUid, String proxyPackageName) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001172 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001173 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1174 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001175 if (ops == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001176 if (DEBUG) Slog.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001177 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001178 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001179 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001180 Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07001181 if (isOpRestrictedLocked(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001182 return AppOpsManager.MODE_IGNORED;
1183 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001184 if (op.duration == -1) {
1185 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
1186 + " code " + code + " time=" + op.time + " duration=" + op.duration);
1187 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001188 op.duration = 0;
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001189 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001190 UidState uidState = ops.uidState;
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001191 // If there is a non-default per UID policy (we set UID op mode only if
1192 // non-default) it takes over, otherwise use the per package policy.
1193 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -07001194 final int uidMode = uidState.opModes.get(switchCode);
1195 if (uidMode != AppOpsManager.MODE_ALLOWED) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001196 if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + op.mode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07001197 + switchCode + " (" + code + ") uid " + uid + " package "
1198 + packageName);
1199 op.rejectTime = System.currentTimeMillis();
1200 return uidMode;
1201 }
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001202 } else {
1203 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
1204 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001205 if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + op.mode + " for code "
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001206 + switchCode + " (" + code + ") uid " + uid + " package "
1207 + packageName);
1208 op.rejectTime = System.currentTimeMillis();
1209 return switchOp.mode;
1210 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001211 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001212 if (DEBUG) Slog.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001213 + " package " + packageName);
1214 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001215 op.rejectTime = 0;
Svet Ganov99b60432015-06-27 13:15:22 -07001216 op.proxyUid = proxyUid;
1217 op.proxyPackageName = proxyPackageName;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001218 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001219 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001220 }
1221
1222 @Override
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001223 public void startWatchingActive(int[] ops, IAppOpsActiveCallback callback) {
Svet Ganovf7b47252018-02-26 11:11:27 -08001224 int watchedUid = -1;
1225 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
1226 != PackageManager.PERMISSION_GRANTED) {
1227 watchedUid = Binder.getCallingUid();
1228 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001229 if (ops != null) {
1230 Preconditions.checkArrayElementsInRange(ops, 0,
1231 AppOpsManager._NUM_OP - 1, "Invalid op code in: " + Arrays.toString(ops));
1232 }
1233 if (callback == null) {
1234 return;
1235 }
1236 synchronized (this) {
1237 SparseArray<ActiveCallback> callbacks = mActiveWatchers.get(callback.asBinder());
1238 if (callbacks == null) {
1239 callbacks = new SparseArray<>();
1240 mActiveWatchers.put(callback.asBinder(), callbacks);
1241 }
Svet Ganovf7b47252018-02-26 11:11:27 -08001242 final ActiveCallback activeCallback = new ActiveCallback(callback, watchedUid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001243 for (int op : ops) {
1244 callbacks.put(op, activeCallback);
1245 }
1246 }
1247 }
1248
1249 @Override
1250 public void stopWatchingActive(IAppOpsActiveCallback callback) {
1251 if (callback == null) {
1252 return;
1253 }
1254 synchronized (this) {
1255 final SparseArray<ActiveCallback> activeCallbacks =
1256 mActiveWatchers.remove(callback.asBinder());
1257 if (activeCallbacks == null) {
1258 return;
1259 }
1260 final int callbackCount = activeCallbacks.size();
1261 for (int i = 0; i < callbackCount; i++) {
1262 // Apps ops are mapped to a singleton
1263 if (i == 0) {
1264 activeCallbacks.valueAt(i).destroy();
1265 }
1266 }
1267 }
1268 }
1269
1270 @Override
Svet Ganovf7b47252018-02-26 11:11:27 -08001271 public int startOperation(IBinder token, int code, int uid, String packageName,
1272 boolean startIfModeDefault) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001273 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001274 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001275 String resolvedPackageName = resolvePackageName(uid, packageName);
1276 if (resolvedPackageName == null) {
1277 return AppOpsManager.MODE_IGNORED;
1278 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001279 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001280 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001281 Ops ops = getOpsRawLocked(uid, resolvedPackageName, true /* edit */,
1282 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001283 if (ops == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001284 if (DEBUG) Slog.d(TAG, "startOperation: no op for code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001285 + " package " + resolvedPackageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001286 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001287 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001288 Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07001289 if (isOpRestrictedLocked(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001290 return AppOpsManager.MODE_IGNORED;
1291 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001292 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001293 UidState uidState = ops.uidState;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001294 // If there is a non-default per UID policy (we set UID op mode only if
1295 // non-default) it takes over, otherwise use the per package policy.
1296 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -07001297 final int uidMode = uidState.opModes.get(switchCode);
Svet Ganovf7b47252018-02-26 11:11:27 -08001298 if (uidMode != AppOpsManager.MODE_ALLOWED
1299 && (!startIfModeDefault || uidMode != AppOpsManager.MODE_DEFAULT)) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001300 if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + op.mode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07001301 + switchCode + " (" + code + ") uid " + uid + " package "
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001302 + resolvedPackageName);
Svet Ganov2af57082015-07-30 08:44:20 -07001303 op.rejectTime = System.currentTimeMillis();
1304 return uidMode;
1305 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001306 } else {
1307 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
Svet Ganovf7b47252018-02-26 11:11:27 -08001308 if (switchOp.mode != AppOpsManager.MODE_ALLOWED
1309 && (!startIfModeDefault || switchOp.mode != AppOpsManager.MODE_DEFAULT)) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001310 if (DEBUG) Slog.d(TAG, "startOperation: reject #" + op.mode + " for code "
1311 + switchCode + " (" + code + ") uid " + uid + " package "
1312 + resolvedPackageName);
1313 op.rejectTime = System.currentTimeMillis();
1314 return switchOp.mode;
1315 }
Svet Ganov2af57082015-07-30 08:44:20 -07001316 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001317 if (DEBUG) Slog.d(TAG, "startOperation: allowing code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001318 + " package " + resolvedPackageName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001319 if (op.nesting == 0) {
1320 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001321 op.rejectTime = 0;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001322 op.duration = -1;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001323 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001324 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001325 op.nesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001326 if (client.mStartedOps != null) {
1327 client.mStartedOps.add(op);
1328 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001329 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001330
1331 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001332 }
1333
1334 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001335 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001336 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001337 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001338 String resolvedPackageName = resolvePackageName(uid, packageName);
1339 if (resolvedPackageName == null) {
1340 return;
1341 }
1342 if (!(token instanceof ClientState)) {
1343 return;
1344 }
1345 ClientState client = (ClientState) token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001346 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001347 Op op = getOpLocked(code, uid, resolvedPackageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001348 if (op == null) {
1349 return;
1350 }
Svet Ganovf7b47252018-02-26 11:11:27 -08001351 if (!client.mStartedOps.remove(op)) {
Svet Ganov31d83ae2018-03-15 10:45:56 -07001352 Slog.wtf(TAG, "Operation not started: uid" + op.uid
Svet Ganovf7b47252018-02-26 11:11:27 -08001353 + " pkg=" + op.packageName + " op=" + op.op);
Svet Ganov31d83ae2018-03-15 10:45:56 -07001354 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001355 }
Svet Ganova7a0db62018-02-27 20:08:01 -08001356 finishOperationLocked(op, /*finishNested*/ false);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001357 if (op.nesting <= 0) {
1358 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, false);
1359 }
1360 }
1361 }
1362
1363 private void scheduleOpActiveChangedIfNeededLocked(int code, int uid, String packageName,
1364 boolean active) {
1365 ArraySet<ActiveCallback> dispatchedCallbacks = null;
1366 final int callbackListCount = mActiveWatchers.size();
1367 for (int i = 0; i < callbackListCount; i++) {
1368 final SparseArray<ActiveCallback> callbacks = mActiveWatchers.valueAt(i);
1369 ActiveCallback callback = callbacks.get(code);
1370 if (callback != null) {
Svet Ganovf7b47252018-02-26 11:11:27 -08001371 if (callback.mUid >= 0 && callback.mUid != uid) {
1372 continue;
1373 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001374 if (dispatchedCallbacks == null) {
1375 dispatchedCallbacks = new ArraySet<>();
1376 }
1377 dispatchedCallbacks.add(callback);
1378 }
1379 }
1380 if (dispatchedCallbacks == null) {
1381 return;
1382 }
1383 mHandler.sendMessage(PooledLambda.obtainMessage(
1384 AppOpsService::notifyOpActiveChanged,
1385 this, dispatchedCallbacks, code, uid, packageName, active));
1386 }
1387
1388 private void notifyOpActiveChanged(ArraySet<ActiveCallback> callbacks,
1389 int code, int uid, String packageName, boolean active) {
1390 // There are components watching for mode changes such as window manager
1391 // and location manager which are in our process. The callbacks in these
1392 // components may require permissions our remote caller does not have.
1393 final long identity = Binder.clearCallingIdentity();
1394 try {
1395 final int callbackCount = callbacks.size();
1396 for (int i = 0; i < callbackCount; i++) {
1397 final ActiveCallback callback = callbacks.valueAt(i);
1398 try {
1399 callback.mCallback.opActiveChanged(code, uid, packageName, active);
1400 } catch (RemoteException e) {
1401 /* do nothing */
1402 }
1403 }
1404 } finally {
1405 Binder.restoreCallingIdentity(identity);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001406 }
1407 }
1408
Svet Ganovb9d71a62015-04-30 10:38:13 -07001409 @Override
1410 public int permissionToOpCode(String permission) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001411 if (permission == null) {
1412 return AppOpsManager.OP_NONE;
1413 }
Svet Ganovb9d71a62015-04-30 10:38:13 -07001414 return AppOpsManager.permissionToOpCode(permission);
1415 }
1416
Svet Ganova7a0db62018-02-27 20:08:01 -08001417 void finishOperationLocked(Op op, boolean finishNested) {
1418 if (op.nesting <= 1 || finishNested) {
1419 if (op.nesting == 1 || finishNested) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001420 op.duration = (int)(System.currentTimeMillis() - op.time);
1421 op.time += op.duration;
1422 } else {
1423 Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
1424 + op.packageName + " code " + op.op + " time=" + op.time
1425 + " duration=" + op.duration + " nesting=" + op.nesting);
1426 }
1427 op.nesting = 0;
1428 } else {
1429 op.nesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001430 }
1431 }
1432
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001433 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001434 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001435 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001436 }
1437 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001438 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001439 }
1440 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
1441 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001442 }
1443
Dianne Hackborn961321f2013-02-05 17:22:41 -08001444 private void verifyIncomingOp(int op) {
1445 if (op >= 0 && op < AppOpsManager._NUM_OP) {
1446 return;
1447 }
1448 throw new IllegalArgumentException("Bad operation #" + op);
1449 }
1450
Svet Ganov2af57082015-07-30 08:44:20 -07001451 private UidState getUidStateLocked(int uid, boolean edit) {
1452 UidState uidState = mUidStates.get(uid);
1453 if (uidState == null) {
1454 if (!edit) {
1455 return null;
1456 }
1457 uidState = new UidState(uid);
1458 mUidStates.put(uid, uidState);
1459 }
1460 return uidState;
1461 }
1462
Yohei Yukawaa965d652017-10-12 15:02:26 -07001463 private Ops getOpsRawLocked(int uid, String packageName, boolean edit,
1464 boolean uidMismatchExpected) {
Svet Ganov2af57082015-07-30 08:44:20 -07001465 UidState uidState = getUidStateLocked(uid, edit);
1466 if (uidState == null) {
1467 return null;
1468 }
1469
1470 if (uidState.pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001471 if (!edit) {
1472 return null;
1473 }
Svet Ganov2af57082015-07-30 08:44:20 -07001474 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001475 }
Svet Ganov2af57082015-07-30 08:44:20 -07001476
1477 Ops ops = uidState.pkgOps.get(packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001478 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001479 if (!edit) {
1480 return null;
1481 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001482 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001483 // This is the first time we have seen this package name under this uid,
1484 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -08001485 if (uid != 0) {
1486 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001487 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001488 int pkgUid = -1;
1489 try {
Jason Monk1c7c3192014-06-26 12:52:18 -04001490 ApplicationInfo appInfo = ActivityThread.getPackageManager()
Jeff Sharkeycd654482016-01-08 17:42:11 -07001491 .getApplicationInfo(packageName,
1492 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1493 UserHandle.getUserId(uid));
Jason Monk1c7c3192014-06-26 12:52:18 -04001494 if (appInfo != null) {
1495 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001496 isPrivileged = (appInfo.privateFlags
1497 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001498 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08001499 pkgUid = resolveUid(packageName);
1500 if (pkgUid >= 0) {
Chien-Yu Chen75cade02016-01-11 10:56:21 -08001501 isPrivileged = false;
Jason Monk1c7c3192014-06-26 12:52:18 -04001502 }
Dianne Hackborn713df152013-05-17 11:27:57 -07001503 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001504 } catch (RemoteException e) {
1505 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001506 }
1507 if (pkgUid != uid) {
1508 // Oops! The package name is not valid for the uid they are calling
1509 // under. Abort.
Yohei Yukawaa965d652017-10-12 15:02:26 -07001510 if (!uidMismatchExpected) {
1511 RuntimeException ex = new RuntimeException("here");
1512 ex.fillInStackTrace();
1513 Slog.w(TAG, "Bad call: specified package " + packageName
1514 + " under uid " + uid + " but it is really " + pkgUid, ex);
1515 }
Dianne Hackborn514074f2013-02-11 10:52:46 -08001516 return null;
1517 }
1518 } finally {
1519 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001520 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001521 }
Svet Ganov2af57082015-07-30 08:44:20 -07001522 ops = new Ops(packageName, uidState, isPrivileged);
1523 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001524 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08001525 return ops;
1526 }
1527
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001528 private void scheduleWriteLocked() {
1529 if (!mWriteScheduled) {
1530 mWriteScheduled = true;
1531 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
1532 }
1533 }
1534
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001535 private void scheduleFastWriteLocked() {
1536 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001537 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001538 mFastWriteScheduled = true;
1539 mHandler.removeCallbacks(mWriteRunner);
1540 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001541 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001542 }
1543
Dianne Hackborn72e39832013-01-18 18:36:09 -08001544 private Op getOpLocked(int code, int uid, String packageName, boolean edit) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001545 Ops ops = getOpsRawLocked(uid, packageName, edit,
1546 false /* uidMismatchExpected */);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001547 if (ops == null) {
1548 return null;
1549 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001550 return getOpLocked(ops, code, edit);
1551 }
1552
1553 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001554 Op op = ops.get(code);
1555 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001556 if (!edit) {
1557 return null;
1558 }
Svet Ganov2af57082015-07-30 08:44:20 -07001559 op = new Op(ops.uidState.uid, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001560 ops.put(code, op);
1561 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001562 if (edit) {
1563 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001564 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001565 return op;
1566 }
1567
Svet Ganov442ed572016-08-17 17:29:43 -07001568 private boolean isOpRestrictedLocked(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04001569 int userHandle = UserHandle.getUserId(uid);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001570 final int restrictionSetCount = mOpUserRestrictions.size();
Ruben Brunk29931bc2016-03-11 00:24:26 -08001571
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001572 for (int i = 0; i < restrictionSetCount; i++) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08001573 // For each client, check that the given op is not restricted, or that the given
1574 // package is exempt from the restriction.
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07001575 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07001576 if (restrictionState.hasRestriction(code, packageName, userHandle)) {
1577 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
1578 // If we are the system, bypass user restrictions for certain codes
1579 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001580 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1581 false /* uidMismatchExpected */);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07001582 if ((ops != null) && ops.isPrivileged) {
1583 return false;
1584 }
Ruben Brunk32f0fa42016-03-11 19:07:07 -08001585 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08001586 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001587 return true;
Jason Monk1c7c3192014-06-26 12:52:18 -04001588 }
Jason Monk62062992014-05-06 09:55:28 -04001589 }
1590 return false;
1591 }
1592
Dianne Hackborn35654b62013-01-14 17:38:02 -08001593 void readState() {
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001594 int oldVersion = NO_VERSION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001595 synchronized (mFile) {
1596 synchronized (this) {
1597 FileInputStream stream;
1598 try {
1599 stream = mFile.openRead();
1600 } catch (FileNotFoundException e) {
1601 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
1602 return;
1603 }
1604 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001605 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001606 try {
1607 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001608 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001609 int type;
1610 while ((type = parser.next()) != XmlPullParser.START_TAG
1611 && type != XmlPullParser.END_DOCUMENT) {
1612 ;
1613 }
1614
1615 if (type != XmlPullParser.START_TAG) {
1616 throw new IllegalStateException("no start tag found");
1617 }
1618
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001619 final String versionString = parser.getAttributeValue(null, "v");
1620 if (versionString != null) {
1621 oldVersion = Integer.parseInt(versionString);
1622 }
1623
Dianne Hackborn35654b62013-01-14 17:38:02 -08001624 int outerDepth = parser.getDepth();
1625 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1626 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1627 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1628 continue;
1629 }
1630
1631 String tagName = parser.getName();
1632 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001633 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07001634 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07001635 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001636 } else {
1637 Slog.w(TAG, "Unknown element under <app-ops>: "
1638 + parser.getName());
1639 XmlUtils.skipCurrentTag(parser);
1640 }
1641 }
1642 success = true;
1643 } catch (IllegalStateException e) {
1644 Slog.w(TAG, "Failed parsing " + e);
1645 } catch (NullPointerException e) {
1646 Slog.w(TAG, "Failed parsing " + e);
1647 } catch (NumberFormatException e) {
1648 Slog.w(TAG, "Failed parsing " + e);
1649 } catch (XmlPullParserException e) {
1650 Slog.w(TAG, "Failed parsing " + e);
1651 } catch (IOException e) {
1652 Slog.w(TAG, "Failed parsing " + e);
1653 } catch (IndexOutOfBoundsException e) {
1654 Slog.w(TAG, "Failed parsing " + e);
1655 } finally {
1656 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07001657 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001658 }
1659 try {
1660 stream.close();
1661 } catch (IOException e) {
1662 }
1663 }
1664 }
1665 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001666 synchronized (this) {
1667 upgradeLocked(oldVersion);
1668 }
1669 }
1670
1671 private void upgradeRunAnyInBackgroundLocked() {
1672 for (int i = 0; i < mUidStates.size(); i++) {
1673 final UidState uidState = mUidStates.valueAt(i);
1674 if (uidState == null) {
1675 continue;
1676 }
1677 if (uidState.opModes != null) {
1678 final int idx = uidState.opModes.indexOfKey(AppOpsManager.OP_RUN_IN_BACKGROUND);
1679 if (idx >= 0) {
1680 uidState.opModes.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND,
1681 uidState.opModes.valueAt(idx));
1682 }
1683 }
1684 if (uidState.pkgOps == null) {
1685 continue;
1686 }
1687 for (int j = 0; j < uidState.pkgOps.size(); j++) {
1688 Ops ops = uidState.pkgOps.valueAt(j);
1689 if (ops != null) {
1690 final Op op = ops.get(AppOpsManager.OP_RUN_IN_BACKGROUND);
1691 if (op != null && op.mode != AppOpsManager.opToDefaultMode(op.op)) {
1692 final Op copy = new Op(op.uid, op.packageName,
1693 AppOpsManager.OP_RUN_ANY_IN_BACKGROUND);
1694 copy.mode = op.mode;
1695 ops.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, copy);
1696 }
1697 }
1698 }
1699 }
1700 }
1701
1702 private void upgradeLocked(int oldVersion) {
1703 if (oldVersion >= CURRENT_VERSION) {
1704 return;
1705 }
1706 Slog.d(TAG, "Upgrading app-ops xml from version " + oldVersion + " to " + CURRENT_VERSION);
1707 switch (oldVersion) {
1708 case NO_VERSION:
1709 upgradeRunAnyInBackgroundLocked();
1710 // fall through
1711 case 1:
1712 // for future upgrades
1713 }
1714 scheduleFastWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001715 }
1716
Svet Ganov2af57082015-07-30 08:44:20 -07001717 void readUidOps(XmlPullParser parser) throws NumberFormatException,
1718 XmlPullParserException, IOException {
1719 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
1720 int outerDepth = parser.getDepth();
1721 int type;
1722 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1723 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1724 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1725 continue;
1726 }
1727
1728 String tagName = parser.getName();
1729 if (tagName.equals("op")) {
1730 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
1731 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
1732 UidState uidState = getUidStateLocked(uid, true);
1733 if (uidState.opModes == null) {
1734 uidState.opModes = new SparseIntArray();
1735 }
1736 uidState.opModes.put(code, mode);
1737 } else {
1738 Slog.w(TAG, "Unknown element under <uid-ops>: "
1739 + parser.getName());
1740 XmlUtils.skipCurrentTag(parser);
1741 }
1742 }
1743 }
1744
Dave Burke0997c5bd2013-08-02 20:25:02 +00001745 void readPackage(XmlPullParser parser) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001746 XmlPullParserException, IOException {
1747 String pkgName = parser.getAttributeValue(null, "n");
1748 int outerDepth = parser.getDepth();
1749 int type;
1750 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1751 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1752 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1753 continue;
1754 }
1755
1756 String tagName = parser.getName();
1757 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001758 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001759 } else {
1760 Slog.w(TAG, "Unknown element under <pkg>: "
1761 + parser.getName());
1762 XmlUtils.skipCurrentTag(parser);
1763 }
1764 }
1765 }
1766
Dave Burke0997c5bd2013-08-02 20:25:02 +00001767 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001768 XmlPullParserException, IOException {
1769 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Jason Monk1c7c3192014-06-26 12:52:18 -04001770 String isPrivilegedString = parser.getAttributeValue(null, "p");
1771 boolean isPrivileged = false;
1772 if (isPrivilegedString == null) {
1773 try {
1774 IPackageManager packageManager = ActivityThread.getPackageManager();
1775 if (packageManager != null) {
1776 ApplicationInfo appInfo = ActivityThread.getPackageManager()
1777 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
1778 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001779 isPrivileged = (appInfo.privateFlags
1780 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001781 }
1782 } else {
1783 // Could not load data, don't add to cache so it will be loaded later.
1784 return;
1785 }
1786 } catch (RemoteException e) {
1787 Slog.w(TAG, "Could not contact PackageManager", e);
1788 }
1789 } else {
1790 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
1791 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001792 int outerDepth = parser.getDepth();
1793 int type;
1794 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1795 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1796 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1797 continue;
1798 }
1799
1800 String tagName = parser.getName();
1801 if (tagName.equals("op")) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001802 Op op = new Op(uid, pkgName, Integer.parseInt(parser.getAttributeValue(null, "n")));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001803 String mode = parser.getAttributeValue(null, "m");
1804 if (mode != null) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001805 op.mode = Integer.parseInt(mode);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001806 }
1807 String time = parser.getAttributeValue(null, "t");
1808 if (time != null) {
1809 op.time = Long.parseLong(time);
1810 }
1811 time = parser.getAttributeValue(null, "r");
1812 if (time != null) {
1813 op.rejectTime = Long.parseLong(time);
1814 }
1815 String dur = parser.getAttributeValue(null, "d");
1816 if (dur != null) {
1817 op.duration = Integer.parseInt(dur);
1818 }
Svet Ganov99b60432015-06-27 13:15:22 -07001819 String proxyUid = parser.getAttributeValue(null, "pu");
1820 if (proxyUid != null) {
1821 op.proxyUid = Integer.parseInt(proxyUid);
1822 }
1823 String proxyPackageName = parser.getAttributeValue(null, "pp");
1824 if (proxyPackageName != null) {
1825 op.proxyPackageName = proxyPackageName;
1826 }
Svet Ganov2af57082015-07-30 08:44:20 -07001827
1828 UidState uidState = getUidStateLocked(uid, true);
1829 if (uidState.pkgOps == null) {
1830 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001831 }
Svet Ganov2af57082015-07-30 08:44:20 -07001832
1833 Ops ops = uidState.pkgOps.get(pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001834 if (ops == null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001835 ops = new Ops(pkgName, uidState, isPrivileged);
1836 uidState.pkgOps.put(pkgName, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001837 }
1838 ops.put(op.op, op);
1839 } else {
1840 Slog.w(TAG, "Unknown element under <pkg>: "
1841 + parser.getName());
1842 XmlUtils.skipCurrentTag(parser);
1843 }
1844 }
1845 }
1846
1847 void writeState() {
1848 synchronized (mFile) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001849 FileOutputStream stream;
1850 try {
1851 stream = mFile.startWrite();
1852 } catch (IOException e) {
1853 Slog.w(TAG, "Failed to write state: " + e);
1854 return;
1855 }
1856
Dianne Hackborne17b4452018-01-10 13:15:40 -08001857 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
1858
Dianne Hackborn35654b62013-01-14 17:38:02 -08001859 try {
1860 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001861 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001862 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001863 out.startTag(null, "app-ops");
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001864 out.attribute(null, "v", String.valueOf(CURRENT_VERSION));
Svet Ganov2af57082015-07-30 08:44:20 -07001865
1866 final int uidStateCount = mUidStates.size();
1867 for (int i = 0; i < uidStateCount; i++) {
1868 UidState uidState = mUidStates.valueAt(i);
1869 if (uidState.opModes != null && uidState.opModes.size() > 0) {
1870 out.startTag(null, "uid");
1871 out.attribute(null, "n", Integer.toString(uidState.uid));
1872 SparseIntArray uidOpModes = uidState.opModes;
1873 final int opCount = uidOpModes.size();
1874 for (int j = 0; j < opCount; j++) {
1875 final int op = uidOpModes.keyAt(j);
1876 final int mode = uidOpModes.valueAt(j);
1877 out.startTag(null, "op");
1878 out.attribute(null, "n", Integer.toString(op));
1879 out.attribute(null, "m", Integer.toString(mode));
1880 out.endTag(null, "op");
1881 }
1882 out.endTag(null, "uid");
1883 }
1884 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001885
1886 if (allOps != null) {
1887 String lastPkg = null;
1888 for (int i=0; i<allOps.size(); i++) {
1889 AppOpsManager.PackageOps pkg = allOps.get(i);
1890 if (!pkg.getPackageName().equals(lastPkg)) {
1891 if (lastPkg != null) {
1892 out.endTag(null, "pkg");
1893 }
1894 lastPkg = pkg.getPackageName();
1895 out.startTag(null, "pkg");
1896 out.attribute(null, "n", lastPkg);
1897 }
1898 out.startTag(null, "uid");
1899 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04001900 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001901 Ops ops = getOpsRawLocked(pkg.getUid(), pkg.getPackageName(),
1902 false /* edit */, false /* uidMismatchExpected */);
Jason Monk1c7c3192014-06-26 12:52:18 -04001903 // Should always be present as the list of PackageOps is generated
1904 // from Ops.
1905 if (ops != null) {
1906 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
1907 } else {
1908 out.attribute(null, "p", Boolean.toString(false));
1909 }
1910 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001911 List<AppOpsManager.OpEntry> ops = pkg.getOps();
1912 for (int j=0; j<ops.size(); j++) {
1913 AppOpsManager.OpEntry op = ops.get(j);
1914 out.startTag(null, "op");
1915 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07001916 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001917 out.attribute(null, "m", Integer.toString(op.getMode()));
1918 }
1919 long time = op.getTime();
1920 if (time != 0) {
1921 out.attribute(null, "t", Long.toString(time));
1922 }
1923 time = op.getRejectTime();
1924 if (time != 0) {
1925 out.attribute(null, "r", Long.toString(time));
1926 }
1927 int dur = op.getDuration();
1928 if (dur != 0) {
1929 out.attribute(null, "d", Integer.toString(dur));
1930 }
Svet Ganov99b60432015-06-27 13:15:22 -07001931 int proxyUid = op.getProxyUid();
1932 if (proxyUid != -1) {
1933 out.attribute(null, "pu", Integer.toString(proxyUid));
1934 }
1935 String proxyPackageName = op.getProxyPackageName();
1936 if (proxyPackageName != null) {
1937 out.attribute(null, "pp", proxyPackageName);
1938 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001939 out.endTag(null, "op");
1940 }
1941 out.endTag(null, "uid");
1942 }
1943 if (lastPkg != null) {
1944 out.endTag(null, "pkg");
1945 }
1946 }
1947
1948 out.endTag(null, "app-ops");
1949 out.endDocument();
1950 mFile.finishWrite(stream);
1951 } catch (IOException e) {
1952 Slog.w(TAG, "Failed to write state, restoring backup.", e);
1953 mFile.failWrite(stream);
1954 }
1955 }
1956 }
1957
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001958 static class Shell extends ShellCommand {
1959 final IAppOpsService mInterface;
1960 final AppOpsService mInternal;
1961
1962 int userId = UserHandle.USER_SYSTEM;
1963 String packageName;
1964 String opStr;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001965 String modeStr;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001966 int op;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001967 int mode;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001968 int packageUid;
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001969 int nonpackageUid;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05001970 final static Binder sBinder = new Binder();
1971 IBinder mToken;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001972
1973 Shell(IAppOpsService iface, AppOpsService internal) {
1974 mInterface = iface;
1975 mInternal = internal;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05001976 try {
1977 mToken = mInterface.getToken(sBinder);
1978 } catch (RemoteException e) {
1979 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001980 }
1981
1982 @Override
1983 public int onCommand(String cmd) {
1984 return onShellCommand(this, cmd);
1985 }
1986
1987 @Override
1988 public void onHelp() {
1989 PrintWriter pw = getOutPrintWriter();
1990 dumpCommandHelp(pw);
1991 }
1992
1993 private int strOpToOp(String op, PrintWriter err) {
1994 try {
1995 return AppOpsManager.strOpToOp(op);
1996 } catch (IllegalArgumentException e) {
1997 }
1998 try {
1999 return Integer.parseInt(op);
2000 } catch (NumberFormatException e) {
2001 }
2002 try {
2003 return AppOpsManager.strDebugOpToOp(op);
2004 } catch (IllegalArgumentException e) {
2005 err.println("Error: " + e.getMessage());
2006 return -1;
2007 }
2008 }
2009
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002010 int strModeToMode(String modeStr, PrintWriter err) {
2011 switch (modeStr) {
2012 case "allow":
2013 return AppOpsManager.MODE_ALLOWED;
2014 case "deny":
2015 return AppOpsManager.MODE_ERRORED;
2016 case "ignore":
2017 return AppOpsManager.MODE_IGNORED;
2018 case "default":
2019 return AppOpsManager.MODE_DEFAULT;
2020 }
2021 try {
2022 return Integer.parseInt(modeStr);
2023 } catch (NumberFormatException e) {
2024 }
2025 err.println("Error: Mode " + modeStr + " is not valid");
2026 return -1;
2027 }
2028
2029 int parseUserOpMode(int defMode, PrintWriter err) throws RemoteException {
2030 userId = UserHandle.USER_CURRENT;
2031 opStr = null;
2032 modeStr = null;
2033 for (String argument; (argument = getNextArg()) != null;) {
2034 if ("--user".equals(argument)) {
2035 userId = UserHandle.parseUserArg(getNextArgRequired());
2036 } else {
2037 if (opStr == null) {
2038 opStr = argument;
2039 } else if (modeStr == null) {
2040 modeStr = argument;
2041 break;
2042 }
2043 }
2044 }
2045 if (opStr == null) {
2046 err.println("Error: Operation not specified.");
2047 return -1;
2048 }
2049 op = strOpToOp(opStr, err);
2050 if (op < 0) {
2051 return -1;
2052 }
2053 if (modeStr != null) {
2054 if ((mode=strModeToMode(modeStr, err)) < 0) {
2055 return -1;
2056 }
2057 } else {
2058 mode = defMode;
2059 }
2060 return 0;
2061 }
2062
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002063 int parseUserPackageOp(boolean reqOp, PrintWriter err) throws RemoteException {
2064 userId = UserHandle.USER_CURRENT;
2065 packageName = null;
2066 opStr = null;
2067 for (String argument; (argument = getNextArg()) != null;) {
2068 if ("--user".equals(argument)) {
2069 userId = UserHandle.parseUserArg(getNextArgRequired());
2070 } else {
2071 if (packageName == null) {
2072 packageName = argument;
2073 } else if (opStr == null) {
2074 opStr = argument;
2075 break;
2076 }
2077 }
2078 }
2079 if (packageName == null) {
2080 err.println("Error: Package name not specified.");
2081 return -1;
2082 } else if (opStr == null && reqOp) {
2083 err.println("Error: Operation not specified.");
2084 return -1;
2085 }
2086 if (opStr != null) {
2087 op = strOpToOp(opStr, err);
2088 if (op < 0) {
2089 return -1;
2090 }
2091 } else {
2092 op = AppOpsManager.OP_NONE;
2093 }
2094 if (userId == UserHandle.USER_CURRENT) {
2095 userId = ActivityManager.getCurrentUser();
2096 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002097 nonpackageUid = -1;
2098 try {
2099 nonpackageUid = Integer.parseInt(packageName);
2100 } catch (NumberFormatException e) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002101 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002102 if (nonpackageUid == -1 && packageName.length() > 1 && packageName.charAt(0) == 'u'
2103 && packageName.indexOf('.') < 0) {
2104 int i = 1;
2105 while (i < packageName.length() && packageName.charAt(i) >= '0'
2106 && packageName.charAt(i) <= '9') {
2107 i++;
2108 }
2109 if (i > 1 && i < packageName.length()) {
2110 String userStr = packageName.substring(1, i);
2111 try {
2112 int user = Integer.parseInt(userStr);
2113 char type = packageName.charAt(i);
2114 i++;
2115 int startTypeVal = i;
2116 while (i < packageName.length() && packageName.charAt(i) >= '0'
2117 && packageName.charAt(i) <= '9') {
2118 i++;
2119 }
2120 if (i > startTypeVal) {
2121 String typeValStr = packageName.substring(startTypeVal, i);
2122 try {
2123 int typeVal = Integer.parseInt(typeValStr);
2124 if (type == 'a') {
2125 nonpackageUid = UserHandle.getUid(user,
2126 typeVal + Process.FIRST_APPLICATION_UID);
2127 } else if (type == 's') {
2128 nonpackageUid = UserHandle.getUid(user, typeVal);
2129 }
2130 } catch (NumberFormatException e) {
2131 }
2132 }
2133 } catch (NumberFormatException e) {
2134 }
2135 }
2136 }
2137 if (nonpackageUid != -1) {
2138 packageName = null;
2139 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08002140 packageUid = resolveUid(packageName);
2141 if (packageUid < 0) {
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002142 packageUid = AppGlobals.getPackageManager().getPackageUid(packageName,
2143 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
2144 }
2145 if (packageUid < 0) {
2146 err.println("Error: No UID for " + packageName + " in user " + userId);
2147 return -1;
2148 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002149 }
2150 return 0;
2151 }
2152 }
2153
2154 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002155 FileDescriptor err, String[] args, ShellCallback callback,
2156 ResultReceiver resultReceiver) {
2157 (new Shell(this, this)).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002158 }
2159
2160 static void dumpCommandHelp(PrintWriter pw) {
2161 pw.println("AppOps service (appops) commands:");
2162 pw.println(" help");
2163 pw.println(" Print this help text.");
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05002164 pw.println(" start [--user <USER_ID>] <PACKAGE | UID> <OP> ");
2165 pw.println(" Starts a given operation for a particular application.");
2166 pw.println(" stop [--user <USER_ID>] <PACKAGE | UID> <OP> ");
2167 pw.println(" Stops a given operation for a particular application.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002168 pw.println(" set [--user <USER_ID>] <PACKAGE | UID> <OP> <MODE>");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002169 pw.println(" Set the mode for a particular application and operation.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002170 pw.println(" get [--user <USER_ID>] <PACKAGE | UID> [<OP>]");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002171 pw.println(" Return the mode for a particular application and optional operation.");
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002172 pw.println(" query-op [--user <USER_ID>] <OP> [<MODE>]");
2173 pw.println(" Print all packages that currently have the given op in the given mode.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002174 pw.println(" reset [--user <USER_ID>] [<PACKAGE>]");
2175 pw.println(" Reset the given application or all applications to default modes.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002176 pw.println(" write-settings");
2177 pw.println(" Immediately write pending changes to storage.");
2178 pw.println(" read-settings");
2179 pw.println(" Read the last written settings, replacing current state in RAM.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002180 pw.println(" options:");
2181 pw.println(" <PACKAGE> an Android package name.");
2182 pw.println(" <OP> an AppOps operation.");
2183 pw.println(" <MODE> one of allow, ignore, deny, or default");
2184 pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
2185 pw.println(" specified, the current user is assumed.");
2186 }
2187
2188 static int onShellCommand(Shell shell, String cmd) {
2189 if (cmd == null) {
2190 return shell.handleDefaultCommands(cmd);
2191 }
2192 PrintWriter pw = shell.getOutPrintWriter();
2193 PrintWriter err = shell.getErrPrintWriter();
2194 try {
2195 switch (cmd) {
2196 case "set": {
2197 int res = shell.parseUserPackageOp(true, err);
2198 if (res < 0) {
2199 return res;
2200 }
2201 String modeStr = shell.getNextArg();
2202 if (modeStr == null) {
2203 err.println("Error: Mode not specified.");
2204 return -1;
2205 }
2206
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002207 final int mode = shell.strModeToMode(modeStr, err);
2208 if (mode < 0) {
2209 return -1;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002210 }
2211
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002212 if (shell.packageName != null) {
2213 shell.mInterface.setMode(shell.op, shell.packageUid, shell.packageName,
2214 mode);
2215 } else {
2216 shell.mInterface.setUidMode(shell.op, shell.nonpackageUid, mode);
2217 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002218 return 0;
2219 }
2220 case "get": {
2221 int res = shell.parseUserPackageOp(false, err);
2222 if (res < 0) {
2223 return res;
2224 }
2225
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002226 List<AppOpsManager.PackageOps> ops;
2227 if (shell.packageName != null) {
2228 ops = shell.mInterface.getOpsForPackage(
2229 shell.packageUid, shell.packageName,
2230 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
2231 } else {
2232 ops = shell.mInterface.getUidOps(
2233 shell.nonpackageUid,
2234 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
2235 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002236 if (ops == null || ops.size() <= 0) {
2237 pw.println("No operations.");
Svet Ganov82f09bc2018-01-12 22:08:40 -08002238 if (shell.op > AppOpsManager.OP_NONE && shell.op < AppOpsManager._NUM_OP) {
2239 pw.println("Default mode: " + AppOpsManager.modeToString(
2240 AppOpsManager.opToDefaultMode(shell.op)));
2241 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002242 return 0;
2243 }
2244 final long now = System.currentTimeMillis();
2245 for (int i=0; i<ops.size(); i++) {
2246 List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
2247 for (int j=0; j<entries.size(); j++) {
2248 AppOpsManager.OpEntry ent = entries.get(j);
2249 pw.print(AppOpsManager.opToName(ent.getOp()));
2250 pw.print(": ");
Svet Ganov82f09bc2018-01-12 22:08:40 -08002251 pw.print(AppOpsManager.modeToString(ent.getMode()));
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002252 if (ent.getTime() != 0) {
2253 pw.print("; time=");
2254 TimeUtils.formatDuration(now - ent.getTime(), pw);
2255 pw.print(" ago");
2256 }
2257 if (ent.getRejectTime() != 0) {
2258 pw.print("; rejectTime=");
2259 TimeUtils.formatDuration(now - ent.getRejectTime(), pw);
2260 pw.print(" ago");
2261 }
2262 if (ent.getDuration() == -1) {
2263 pw.print(" (running)");
2264 } else if (ent.getDuration() != 0) {
2265 pw.print("; duration=");
2266 TimeUtils.formatDuration(ent.getDuration(), pw);
2267 }
2268 pw.println();
2269 }
2270 }
2271 return 0;
2272 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002273 case "query-op": {
2274 int res = shell.parseUserOpMode(AppOpsManager.MODE_IGNORED, err);
2275 if (res < 0) {
2276 return res;
2277 }
2278 List<AppOpsManager.PackageOps> ops = shell.mInterface.getPackagesForOps(
2279 new int[] {shell.op});
2280 if (ops == null || ops.size() <= 0) {
2281 pw.println("No operations.");
2282 return 0;
2283 }
2284 for (int i=0; i<ops.size(); i++) {
2285 final AppOpsManager.PackageOps pkg = ops.get(i);
2286 boolean hasMatch = false;
2287 final List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
2288 for (int j=0; j<entries.size(); j++) {
2289 AppOpsManager.OpEntry ent = entries.get(j);
2290 if (ent.getOp() == shell.op && ent.getMode() == shell.mode) {
2291 hasMatch = true;
2292 break;
2293 }
2294 }
2295 if (hasMatch) {
2296 pw.println(pkg.getPackageName());
2297 }
2298 }
2299 return 0;
2300 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002301 case "reset": {
2302 String packageName = null;
2303 int userId = UserHandle.USER_CURRENT;
2304 for (String argument; (argument = shell.getNextArg()) != null;) {
2305 if ("--user".equals(argument)) {
2306 String userStr = shell.getNextArgRequired();
2307 userId = UserHandle.parseUserArg(userStr);
2308 } else {
2309 if (packageName == null) {
2310 packageName = argument;
2311 } else {
2312 err.println("Error: Unsupported argument: " + argument);
2313 return -1;
2314 }
2315 }
2316 }
2317
2318 if (userId == UserHandle.USER_CURRENT) {
2319 userId = ActivityManager.getCurrentUser();
2320 }
2321
2322 shell.mInterface.resetAllModes(userId, packageName);
2323 pw.print("Reset all modes for: ");
2324 if (userId == UserHandle.USER_ALL) {
2325 pw.print("all users");
2326 } else {
2327 pw.print("user "); pw.print(userId);
2328 }
2329 pw.print(", ");
2330 if (packageName == null) {
2331 pw.println("all packages");
2332 } else {
2333 pw.print("package "); pw.println(packageName);
2334 }
2335 return 0;
2336 }
2337 case "write-settings": {
2338 shell.mInternal.mContext.enforcePermission(
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -08002339 android.Manifest.permission.MANAGE_APP_OPS_MODES,
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002340 Binder.getCallingPid(), Binder.getCallingUid(), null);
2341 long token = Binder.clearCallingIdentity();
2342 try {
2343 synchronized (shell.mInternal) {
2344 shell.mInternal.mHandler.removeCallbacks(shell.mInternal.mWriteRunner);
2345 }
2346 shell.mInternal.writeState();
2347 pw.println("Current settings written.");
2348 } finally {
2349 Binder.restoreCallingIdentity(token);
2350 }
2351 return 0;
2352 }
2353 case "read-settings": {
2354 shell.mInternal.mContext.enforcePermission(
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -08002355 android.Manifest.permission.MANAGE_APP_OPS_MODES,
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002356 Binder.getCallingPid(), Binder.getCallingUid(), null);
2357 long token = Binder.clearCallingIdentity();
2358 try {
2359 shell.mInternal.readState();
2360 pw.println("Last settings read.");
2361 } finally {
2362 Binder.restoreCallingIdentity(token);
2363 }
2364 return 0;
2365 }
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05002366 case "start": {
2367 int res = shell.parseUserPackageOp(true, err);
2368 if (res < 0) {
2369 return res;
2370 }
2371
2372 if (shell.packageName != null) {
2373 shell.mInterface.startOperation(shell.mToken,
2374 shell.op, shell.packageUid, shell.packageName, true);
2375 } else {
2376 return -1;
2377 }
2378 return 0;
2379 }
2380 case "stop": {
2381 int res = shell.parseUserPackageOp(true, err);
2382 if (res < 0) {
2383 return res;
2384 }
2385
2386 if (shell.packageName != null) {
2387 shell.mInterface.finishOperation(shell.mToken,
2388 shell.op, shell.packageUid, shell.packageName);
2389 } else {
2390 return -1;
2391 }
2392 return 0;
2393 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002394 default:
2395 return shell.handleDefaultCommands(cmd);
2396 }
2397 } catch (RemoteException e) {
2398 pw.println("Remote exception: " + e);
2399 }
2400 return -1;
2401 }
2402
2403 private void dumpHelp(PrintWriter pw) {
2404 pw.println("AppOps service (appops) dump options:");
2405 pw.println(" none");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002406 }
2407
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002408 @Override
2409 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002410 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002411
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002412 if (args != null) {
2413 for (int i=0; i<args.length; i++) {
2414 String arg = args[i];
2415 if ("-h".equals(arg)) {
2416 dumpHelp(pw);
2417 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07002418 } else if ("-a".equals(arg)) {
2419 // dump all data
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002420 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
2421 pw.println("Unknown option: " + arg);
2422 return;
2423 } else {
2424 pw.println("Unknown command: " + arg);
2425 return;
2426 }
2427 }
2428 }
2429
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002430 synchronized (this) {
2431 pw.println("Current AppOps Service state:");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002432 final long now = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002433 boolean needSep = false;
2434 if (mOpModeWatchers.size() > 0) {
2435 needSep = true;
2436 pw.println(" Op mode watchers:");
2437 for (int i=0; i<mOpModeWatchers.size(); i++) {
2438 pw.print(" Op "); pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
2439 pw.println(":");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002440 ArraySet<ModeCallback> callbacks = mOpModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002441 for (int j=0; j<callbacks.size(); j++) {
2442 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08002443 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002444 }
2445 }
2446 }
2447 if (mPackageModeWatchers.size() > 0) {
2448 needSep = true;
2449 pw.println(" Package mode watchers:");
2450 for (int i=0; i<mPackageModeWatchers.size(); i++) {
2451 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
2452 pw.println(":");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002453 ArraySet<ModeCallback> callbacks = mPackageModeWatchers.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 (mModeWatchers.size() > 0) {
2461 needSep = true;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002462 pw.println(" All op mode watchers:");
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002463 for (int i=0; i<mModeWatchers.size(); i++) {
2464 pw.print(" "); pw.print(mModeWatchers.keyAt(i));
2465 pw.print(" -> "); pw.println(mModeWatchers.valueAt(i));
2466 }
2467 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002468 if (mActiveWatchers.size() > 0) {
2469 needSep = true;
2470 pw.println(" All op active watchers:");
2471 for (int i = 0; i < mActiveWatchers.size(); i++) {
2472 final SparseArray<ActiveCallback> activeWatchers = mActiveWatchers.valueAt(i);
2473 if (activeWatchers.size() <= 0) {
2474 continue;
2475 }
2476 pw.print(" "); pw.print(mActiveWatchers.keyAt(i));
2477 pw.print(" -> [");
2478 final int opCount = activeWatchers.size();
2479 for (i = 0; i < opCount; i++) {
2480 pw.print(AppOpsManager.opToName(activeWatchers.keyAt(i)));
2481 if (i < opCount - 1) {
2482 pw.print(',');
2483 }
2484 }
2485 pw.print("]" ); pw.println(activeWatchers.valueAt(0));
2486 }
2487 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002488 if (mClients.size() > 0) {
2489 needSep = true;
2490 pw.println(" Clients:");
2491 for (int i=0; i<mClients.size(); i++) {
2492 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
2493 ClientState cs = mClients.valueAt(i);
2494 pw.print(" "); pw.println(cs);
Svet Ganovf7b47252018-02-26 11:11:27 -08002495 if (cs.mStartedOps.size() > 0) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002496 pw.println(" Started ops:");
2497 for (int j=0; j<cs.mStartedOps.size(); j++) {
2498 Op op = cs.mStartedOps.get(j);
2499 pw.print(" "); pw.print("uid="); pw.print(op.uid);
2500 pw.print(" pkg="); pw.print(op.packageName);
2501 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
2502 }
2503 }
2504 }
2505 }
John Spurlock1af30c72014-03-10 08:33:35 -04002506 if (mAudioRestrictions.size() > 0) {
2507 boolean printedHeader = false;
2508 for (int o=0; o<mAudioRestrictions.size(); o++) {
2509 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
2510 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
2511 for (int i=0; i<restrictions.size(); i++) {
2512 if (!printedHeader){
2513 pw.println(" Audio Restrictions:");
2514 printedHeader = true;
2515 needSep = true;
2516 }
John Spurlock7b414672014-07-18 13:02:39 -04002517 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04002518 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04002519 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04002520 Restriction r = restrictions.valueAt(i);
2521 pw.print(": mode="); pw.println(r.mode);
2522 if (!r.exceptionPackages.isEmpty()) {
2523 pw.println(" Exceptions:");
2524 for (int j=0; j<r.exceptionPackages.size(); j++) {
2525 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
2526 }
2527 }
2528 }
2529 }
2530 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002531 if (needSep) {
2532 pw.println();
2533 }
Svet Ganov2af57082015-07-30 08:44:20 -07002534 for (int i=0; i<mUidStates.size(); i++) {
2535 UidState uidState = mUidStates.valueAt(i);
2536
2537 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
Svet Ganovee438d42017-01-19 18:04:38 -08002538 needSep = true;
Svet Ganov2af57082015-07-30 08:44:20 -07002539
2540 SparseIntArray opModes = uidState.opModes;
2541 if (opModes != null) {
2542 final int opModeCount = opModes.size();
2543 for (int j = 0; j < opModeCount; j++) {
2544 final int code = opModes.keyAt(j);
2545 final int mode = opModes.valueAt(j);
2546 pw.print(" "); pw.print(AppOpsManager.opToName(code));
2547 pw.print(": mode="); pw.println(mode);
2548 }
2549 }
2550
2551 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
2552 if (pkgOps == null) {
2553 continue;
2554 }
2555
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002556 for (Ops ops : pkgOps.values()) {
2557 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
2558 for (int j=0; j<ops.size(); j++) {
2559 Op op = ops.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002560 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
2561 pw.print(": mode="); pw.print(op.mode);
2562 if (op.time != 0) {
2563 pw.print("; time="); TimeUtils.formatDuration(now-op.time, pw);
2564 pw.print(" ago");
2565 }
2566 if (op.rejectTime != 0) {
2567 pw.print("; rejectTime="); TimeUtils.formatDuration(now-op.rejectTime, pw);
2568 pw.print(" ago");
2569 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002570 if (op.duration == -1) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002571 pw.print(" (running)");
2572 } else if (op.duration != 0) {
2573 pw.print("; duration="); TimeUtils.formatDuration(op.duration, pw);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002574 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002575 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002576 }
2577 }
2578 }
Svet Ganovee438d42017-01-19 18:04:38 -08002579 if (needSep) {
2580 pw.println();
2581 }
2582
2583 final int userRestrictionCount = mOpUserRestrictions.size();
2584 for (int i = 0; i < userRestrictionCount; i++) {
2585 IBinder token = mOpUserRestrictions.keyAt(i);
2586 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
2587 pw.println(" User restrictions for token " + token + ":");
2588
2589 final int restrictionCount = restrictionState.perUserRestrictions != null
2590 ? restrictionState.perUserRestrictions.size() : 0;
2591 if (restrictionCount > 0) {
2592 pw.println(" Restricted ops:");
2593 for (int j = 0; j < restrictionCount; j++) {
2594 int userId = restrictionState.perUserRestrictions.keyAt(j);
2595 boolean[] restrictedOps = restrictionState.perUserRestrictions.valueAt(j);
2596 if (restrictedOps == null) {
2597 continue;
2598 }
2599 StringBuilder restrictedOpsValue = new StringBuilder();
2600 restrictedOpsValue.append("[");
2601 final int restrictedOpCount = restrictedOps.length;
2602 for (int k = 0; k < restrictedOpCount; k++) {
2603 if (restrictedOps[k]) {
2604 if (restrictedOpsValue.length() > 1) {
2605 restrictedOpsValue.append(", ");
2606 }
2607 restrictedOpsValue.append(AppOpsManager.opToName(k));
2608 }
2609 }
2610 restrictedOpsValue.append("]");
2611 pw.print(" "); pw.print("user: "); pw.print(userId);
2612 pw.print(" restricted ops: "); pw.println(restrictedOpsValue);
2613 }
2614 }
2615
2616 final int excludedPackageCount = restrictionState.perUserExcludedPackages != null
2617 ? restrictionState.perUserExcludedPackages.size() : 0;
2618 if (excludedPackageCount > 0) {
2619 pw.println(" Excluded packages:");
2620 for (int j = 0; j < excludedPackageCount; j++) {
2621 int userId = restrictionState.perUserExcludedPackages.keyAt(j);
2622 String[] packageNames = restrictionState.perUserExcludedPackages.valueAt(j);
2623 pw.print(" "); pw.print("user: "); pw.print(userId);
2624 pw.print(" packages: "); pw.println(Arrays.toString(packageNames));
2625 }
2626 }
2627 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002628 }
2629 }
John Spurlock1af30c72014-03-10 08:33:35 -04002630
2631 private static final class Restriction {
2632 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
2633 int mode;
2634 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
2635 }
Jason Monk62062992014-05-06 09:55:28 -04002636
2637 @Override
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002638 public void setUserRestrictions(Bundle restrictions, IBinder token, int userHandle) {
Jason Monk62062992014-05-06 09:55:28 -04002639 checkSystemUid("setUserRestrictions");
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002640 Preconditions.checkNotNull(restrictions);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002641 Preconditions.checkNotNull(token);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002642 for (int i = 0; i < AppOpsManager._NUM_OP; i++) {
Jason Monk62062992014-05-06 09:55:28 -04002643 String restriction = AppOpsManager.opToRestriction(i);
Suprabh Shukla64e0dcb2016-05-24 16:23:11 -07002644 if (restriction != null) {
2645 setUserRestrictionNoCheck(i, restrictions.getBoolean(restriction, false), token,
2646 userHandle, null);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002647 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002648 }
2649 }
2650
2651 @Override
Ruben Brunk29931bc2016-03-11 00:24:26 -08002652 public void setUserRestriction(int code, boolean restricted, IBinder token, int userHandle,
2653 String[] exceptionPackages) {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002654 if (Binder.getCallingPid() != Process.myPid()) {
2655 mContext.enforcePermission(Manifest.permission.MANAGE_APP_OPS_RESTRICTIONS,
2656 Binder.getCallingPid(), Binder.getCallingUid(), null);
2657 }
2658 if (userHandle != UserHandle.getCallingUserId()) {
2659 if (mContext.checkCallingOrSelfPermission(Manifest.permission
2660 .INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
2661 && mContext.checkCallingOrSelfPermission(Manifest.permission
2662 .INTERACT_ACROSS_USERS) != PackageManager.PERMISSION_GRANTED) {
2663 throw new SecurityException("Need INTERACT_ACROSS_USERS_FULL or"
2664 + " INTERACT_ACROSS_USERS to interact cross user ");
Jason Monk62062992014-05-06 09:55:28 -04002665 }
2666 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002667 verifyIncomingOp(code);
2668 Preconditions.checkNotNull(token);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002669 setUserRestrictionNoCheck(code, restricted, token, userHandle, exceptionPackages);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002670 }
2671
2672 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
Ruben Brunk29931bc2016-03-11 00:24:26 -08002673 int userHandle, String[] exceptionPackages) {
Svet Ganov442ed572016-08-17 17:29:43 -07002674 synchronized (AppOpsService.this) {
2675 ClientRestrictionState restrictionState = mOpUserRestrictions.get(token);
2676
2677 if (restrictionState == null) {
2678 try {
2679 restrictionState = new ClientRestrictionState(token);
2680 } catch (RemoteException e) {
2681 return;
2682 }
2683 mOpUserRestrictions.put(token, restrictionState);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002684 }
Svet Ganov442ed572016-08-17 17:29:43 -07002685
2686 if (restrictionState.setRestriction(code, restricted, exceptionPackages, userHandle)) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002687 mHandler.sendMessage(PooledLambda.obtainMessage(
Svet Ganov3a95f832018-03-23 17:44:30 -07002688 AppOpsService::notifyWatchersOfChange, this, code, UID_ANY));
Svet Ganov442ed572016-08-17 17:29:43 -07002689 }
2690
2691 if (restrictionState.isDefault()) {
2692 mOpUserRestrictions.remove(token);
2693 restrictionState.destroy();
2694 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002695 }
Julia Reynoldsbb21c252016-04-05 16:01:49 -04002696 }
2697
Svet Ganov3a95f832018-03-23 17:44:30 -07002698 private void notifyWatchersOfChange(int code, int uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002699 final ArraySet<ModeCallback> clonedCallbacks;
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002700 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002701 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002702 if (callbacks == null) {
2703 return;
2704 }
Dianne Hackborn68d76552017-02-27 15:32:03 -08002705 clonedCallbacks = new ArraySet<>(callbacks);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002706 }
2707
Svet Ganov3a95f832018-03-23 17:44:30 -07002708 notifyOpChanged(clonedCallbacks, code, uid, null);
Jason Monk62062992014-05-06 09:55:28 -04002709 }
2710
2711 @Override
2712 public void removeUser(int userHandle) throws RemoteException {
2713 checkSystemUid("removeUser");
Svet Ganov442ed572016-08-17 17:29:43 -07002714 synchronized (AppOpsService.this) {
2715 final int tokenCount = mOpUserRestrictions.size();
2716 for (int i = tokenCount - 1; i >= 0; i--) {
2717 ClientRestrictionState opRestrictions = mOpUserRestrictions.valueAt(i);
2718 opRestrictions.removeUser(userHandle);
2719 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002720 removeUidsForUserLocked(userHandle);
2721 }
2722 }
2723
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002724 @Override
2725 public boolean isOperationActive(int code, int uid, String packageName) {
Svet Ganovf7b47252018-02-26 11:11:27 -08002726 if (Binder.getCallingUid() != uid) {
2727 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
2728 != PackageManager.PERMISSION_GRANTED) {
2729 return false;
2730 }
2731 }
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002732 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002733 final String resolvedPackageName = resolvePackageName(uid, packageName);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002734 if (resolvedPackageName == null) {
2735 return false;
2736 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002737 synchronized (AppOpsService.this) {
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002738 for (int i = mClients.size() - 1; i >= 0; i--) {
2739 final ClientState client = mClients.valueAt(i);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002740 for (int j = client.mStartedOps.size() - 1; j >= 0; j--) {
2741 final Op op = client.mStartedOps.get(j);
2742 if (op.op == code && op.uid == uid) return true;
2743 }
2744 }
2745 }
2746 return false;
2747 }
2748
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002749 private void removeUidsForUserLocked(int userHandle) {
2750 for (int i = mUidStates.size() - 1; i >= 0; --i) {
2751 final int uid = mUidStates.keyAt(i);
2752 if (UserHandle.getUserId(uid) == userHandle) {
2753 mUidStates.removeAt(i);
2754 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002755 }
2756 }
2757
Jason Monk62062992014-05-06 09:55:28 -04002758 private void checkSystemUid(String function) {
2759 int uid = Binder.getCallingUid();
2760 if (uid != Process.SYSTEM_UID) {
2761 throw new SecurityException(function + " must by called by the system");
2762 }
2763 }
2764
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002765 private static String resolvePackageName(int uid, String packageName) {
Svet Ganov82f09bc2018-01-12 22:08:40 -08002766 if (uid == Process.ROOT_UID) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002767 return "root";
2768 } else if (uid == Process.SHELL_UID) {
2769 return "com.android.shell";
Svet Ganov82f09bc2018-01-12 22:08:40 -08002770 } else if (uid == Process.MEDIA_UID) {
2771 return "media";
2772 } else if (uid == Process.AUDIOSERVER_UID) {
2773 return "audioserver";
2774 } else if (uid == Process.CAMERASERVER_UID) {
2775 return "cameraserver";
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002776 } else if (uid == Process.SYSTEM_UID && packageName == null) {
2777 return "android";
2778 }
2779 return packageName;
2780 }
2781
Svet Ganov82f09bc2018-01-12 22:08:40 -08002782 private static int resolveUid(String packageName) {
2783 if (packageName == null) {
2784 return -1;
2785 }
2786 switch (packageName) {
2787 case "root":
2788 return Process.ROOT_UID;
2789 case "shell":
2790 return Process.SHELL_UID;
2791 case "media":
2792 return Process.MEDIA_UID;
2793 case "audioserver":
2794 return Process.AUDIOSERVER_UID;
2795 case "cameraserver":
2796 return Process.CAMERASERVER_UID;
2797 }
2798 return -1;
2799 }
2800
Svet Ganov2af57082015-07-30 08:44:20 -07002801 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07002802 String[] packageNames = null;
Svet Ganov2af57082015-07-30 08:44:20 -07002803 try {
riddle_hsu40b300f2015-11-23 13:22:03 +08002804 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -07002805 } catch (RemoteException e) {
2806 /* ignore - local call */
2807 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07002808 if (packageNames == null) {
2809 return EmptyArray.STRING;
2810 }
2811 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07002812 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002813
2814 private final class ClientRestrictionState implements DeathRecipient {
2815 private final IBinder token;
2816 SparseArray<boolean[]> perUserRestrictions;
2817 SparseArray<String[]> perUserExcludedPackages;
2818
2819 public ClientRestrictionState(IBinder token)
2820 throws RemoteException {
2821 token.linkToDeath(this, 0);
2822 this.token = token;
2823 }
2824
2825 public boolean setRestriction(int code, boolean restricted,
2826 String[] excludedPackages, int userId) {
2827 boolean changed = false;
2828
2829 if (perUserRestrictions == null && restricted) {
2830 perUserRestrictions = new SparseArray<>();
2831 }
2832
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002833 int[] users;
2834 if (userId == UserHandle.USER_ALL) {
2835 List<UserInfo> liveUsers = UserManager.get(mContext).getUsers(false);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002836
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002837 users = new int[liveUsers.size()];
2838 for (int i = 0; i < liveUsers.size(); i++) {
2839 users[i] = liveUsers.get(i).id;
2840 }
2841 } else {
2842 users = new int[]{userId};
2843 }
2844
2845 if (perUserRestrictions != null) {
2846 int numUsers = users.length;
2847
2848 for (int i = 0; i < numUsers; i++) {
2849 int thisUserId = users[i];
2850
2851 boolean[] userRestrictions = perUserRestrictions.get(thisUserId);
2852 if (userRestrictions == null && restricted) {
2853 userRestrictions = new boolean[AppOpsManager._NUM_OP];
2854 perUserRestrictions.put(thisUserId, userRestrictions);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002855 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002856 if (userRestrictions != null && userRestrictions[code] != restricted) {
2857 userRestrictions[code] = restricted;
2858 if (!restricted && isDefault(userRestrictions)) {
2859 perUserRestrictions.remove(thisUserId);
2860 userRestrictions = null;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002861 }
2862 changed = true;
2863 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002864
2865 if (userRestrictions != null) {
2866 final boolean noExcludedPackages = ArrayUtils.isEmpty(excludedPackages);
2867 if (perUserExcludedPackages == null && !noExcludedPackages) {
2868 perUserExcludedPackages = new SparseArray<>();
2869 }
2870 if (perUserExcludedPackages != null && !Arrays.equals(excludedPackages,
2871 perUserExcludedPackages.get(thisUserId))) {
2872 if (noExcludedPackages) {
2873 perUserExcludedPackages.remove(thisUserId);
2874 if (perUserExcludedPackages.size() <= 0) {
2875 perUserExcludedPackages = null;
2876 }
2877 } else {
2878 perUserExcludedPackages.put(thisUserId, excludedPackages);
2879 }
2880 changed = true;
2881 }
2882 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002883 }
2884 }
2885
2886 return changed;
2887 }
2888
2889 public boolean hasRestriction(int restriction, String packageName, int userId) {
2890 if (perUserRestrictions == null) {
2891 return false;
2892 }
2893 boolean[] restrictions = perUserRestrictions.get(userId);
2894 if (restrictions == null) {
2895 return false;
2896 }
2897 if (!restrictions[restriction]) {
2898 return false;
2899 }
2900 if (perUserExcludedPackages == null) {
2901 return true;
2902 }
2903 String[] perUserExclusions = perUserExcludedPackages.get(userId);
2904 if (perUserExclusions == null) {
2905 return true;
2906 }
2907 return !ArrayUtils.contains(perUserExclusions, packageName);
2908 }
2909
2910 public void removeUser(int userId) {
2911 if (perUserExcludedPackages != null) {
2912 perUserExcludedPackages.remove(userId);
2913 if (perUserExcludedPackages.size() <= 0) {
2914 perUserExcludedPackages = null;
2915 }
2916 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002917 if (perUserRestrictions != null) {
2918 perUserRestrictions.remove(userId);
2919 if (perUserRestrictions.size() <= 0) {
2920 perUserRestrictions = null;
2921 }
2922 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002923 }
2924
2925 public boolean isDefault() {
2926 return perUserRestrictions == null || perUserRestrictions.size() <= 0;
2927 }
2928
2929 @Override
2930 public void binderDied() {
2931 synchronized (AppOpsService.this) {
2932 mOpUserRestrictions.remove(token);
2933 if (perUserRestrictions == null) {
2934 return;
2935 }
2936 final int userCount = perUserRestrictions.size();
2937 for (int i = 0; i < userCount; i++) {
2938 final boolean[] restrictions = perUserRestrictions.valueAt(i);
2939 final int restrictionCount = restrictions.length;
2940 for (int j = 0; j < restrictionCount; j++) {
2941 if (restrictions[j]) {
2942 final int changedCode = j;
Svet Ganov3a95f832018-03-23 17:44:30 -07002943 mHandler.post(() -> notifyWatchersOfChange(changedCode, UID_ANY));
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002944 }
2945 }
2946 }
2947 destroy();
2948 }
2949 }
2950
2951 public void destroy() {
2952 token.unlinkToDeath(this, 0);
2953 }
2954
2955 private boolean isDefault(boolean[] array) {
2956 if (ArrayUtils.isEmpty(array)) {
2957 return true;
2958 }
2959 for (boolean value : array) {
2960 if (value) {
2961 return false;
2962 }
2963 }
2964 return true;
2965 }
2966 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002967}