blob: 9756d17f662ede188aa44b8b90a39eba36ac3322 [file] [log] [blame]
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Philip P. Moltmanne683f192017-06-23 14:05:04 -070019import android.Manifest;
20import android.app.ActivityManager;
21import android.app.ActivityThread;
22import android.app.AppGlobals;
23import android.app.AppOpsManager;
24import android.content.Context;
25import android.content.pm.ApplicationInfo;
26import android.content.pm.IPackageManager;
27import android.content.pm.PackageManager;
28import android.content.pm.PackageManagerInternal;
29import android.content.pm.UserInfo;
30import android.media.AudioAttributes;
31import android.os.AsyncTask;
32import android.os.Binder;
33import android.os.Bundle;
34import android.os.Handler;
35import android.os.IBinder;
36import android.os.Process;
37import android.os.RemoteException;
38import android.os.ResultReceiver;
39import android.os.ServiceManager;
40import android.os.ShellCallback;
41import android.os.ShellCommand;
42import android.os.UserHandle;
43import android.os.UserManager;
44import android.os.storage.StorageManagerInternal;
45import android.util.ArrayMap;
46import android.util.ArraySet;
47import android.util.AtomicFile;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070048import android.util.Slog;
49import android.util.SparseArray;
50import android.util.SparseIntArray;
51import android.util.TimeUtils;
52import android.util.Xml;
53
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070054import com.android.internal.annotations.VisibleForTesting;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -080055import com.android.internal.app.IAppOpsActiveCallback;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070056import com.android.internal.app.IAppOpsCallback;
57import com.android.internal.app.IAppOpsService;
58import com.android.internal.os.Zygote;
59import com.android.internal.util.ArrayUtils;
60import com.android.internal.util.DumpUtils;
61import com.android.internal.util.FastXmlSerializer;
62import com.android.internal.util.Preconditions;
63import com.android.internal.util.XmlUtils;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -080064import com.android.internal.util.function.pooled.PooledLambda;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -050065
Philip P. Moltmanne683f192017-06-23 14:05:04 -070066import libcore.util.EmptyArray;
67
68import org.xmlpull.v1.XmlPullParser;
69import org.xmlpull.v1.XmlPullParserException;
70import org.xmlpull.v1.XmlSerializer;
71
Dianne Hackborna06de0f2012-12-11 16:34:47 -080072import java.io.File;
73import java.io.FileDescriptor;
Dianne Hackborn35654b62013-01-14 17:38:02 -080074import java.io.FileInputStream;
75import java.io.FileNotFoundException;
76import java.io.FileOutputStream;
77import java.io.IOException;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080078import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010079import java.nio.charset.StandardCharsets;
Dianne Hackborn35654b62013-01-14 17:38:02 -080080import java.util.ArrayList;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -070081import java.util.Arrays;
Svetoslav215b44a2015-08-04 19:03:40 -070082import java.util.Collections;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080083import java.util.HashMap;
Dianne Hackbornc2293022013-02-06 23:14:49 -080084import java.util.Iterator;
Dianne Hackborn35654b62013-01-14 17:38:02 -080085import java.util.List;
Dianne Hackborn607b4142013-08-02 18:10:10 -070086import java.util.Map;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080087
Dianne Hackborna06de0f2012-12-11 16:34:47 -080088public class AppOpsService extends IAppOpsService.Stub {
89 static final String TAG = "AppOps";
Dianne Hackborn35654b62013-01-14 17:38:02 -080090 static final boolean DEBUG = false;
91
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070092 private static final int NO_VERSION = -1;
93 /** Increment by one every time and add the corresponding upgrade logic in
94 * {@link #upgradeLocked(int)} below. The first version was 1 */
95 private static final int CURRENT_VERSION = 1;
96
Dianne Hackborn35654b62013-01-14 17:38:02 -080097 // Write at most every 30 minutes.
98 static final long WRITE_DELAY = DEBUG ? 1000 : 30*60*1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080099
100 Context mContext;
101 final AtomicFile mFile;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800102 final Handler mHandler;
103
104 boolean mWriteScheduled;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800105 boolean mFastWriteScheduled;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800106 final Runnable mWriteRunner = new Runnable() {
107 public void run() {
108 synchronized (AppOpsService.this) {
109 mWriteScheduled = false;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800110 mFastWriteScheduled = false;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800111 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
112 @Override protected Void doInBackground(Void... params) {
113 writeState();
114 return null;
115 }
116 };
117 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
118 }
119 }
120 };
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800121
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700122 @VisibleForTesting
123 final SparseArray<UidState> mUidStates = new SparseArray<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800124
Ruben Brunk29931bc2016-03-11 00:24:26 -0800125 /*
126 * These are app op restrictions imposed per user from various parties.
Ruben Brunk29931bc2016-03-11 00:24:26 -0800127 */
Svetoslav Ganova8bbd762016-05-13 17:08:16 -0700128 private final ArrayMap<IBinder, ClientRestrictionState> mOpUserRestrictions = new ArrayMap<>();
Jason Monk62062992014-05-06 09:55:28 -0400129
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700130 @VisibleForTesting
131 static final class UidState {
Svet Ganov2af57082015-07-30 08:44:20 -0700132 public final int uid;
133 public ArrayMap<String, Ops> pkgOps;
134 public SparseIntArray opModes;
135
136 public UidState(int uid) {
137 this.uid = uid;
138 }
139
140 public void clear() {
141 pkgOps = null;
142 opModes = null;
143 }
144
145 public boolean isDefault() {
146 return (pkgOps == null || pkgOps.isEmpty())
147 && (opModes == null || opModes.size() <= 0);
148 }
149 }
150
Dianne Hackbornc2293022013-02-06 23:14:49 -0800151 public final static class Ops extends SparseArray<Op> {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800152 public final String packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700153 public final UidState uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400154 public final boolean isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800155
Svet Ganov2af57082015-07-30 08:44:20 -0700156 public Ops(String _packageName, UidState _uidState, boolean _isPrivileged) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800157 packageName = _packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700158 uidState = _uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400159 isPrivileged = _isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800160 }
161 }
162
Dianne Hackbornc2293022013-02-06 23:14:49 -0800163 public final static class Op {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700164 public final int uid;
165 public final String packageName;
Svet Ganov99b60432015-06-27 13:15:22 -0700166 public int proxyUid = -1;
167 public String proxyPackageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800168 public final int op;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800169 public int mode;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800170 public int duration;
171 public long time;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800172 public long rejectTime;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800173 public int nesting;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800174
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700175 public Op(int _uid, String _packageName, int _op) {
176 uid = _uid;
177 packageName = _packageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800178 op = _op;
David Braunf5d83192013-09-16 13:43:51 -0700179 mode = AppOpsManager.opToDefaultMode(op);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800180 }
181 }
182
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800183 final SparseArray<ArraySet<ModeCallback>> mOpModeWatchers = new SparseArray<>();
184 final ArrayMap<String, ArraySet<ModeCallback>> mPackageModeWatchers = new ArrayMap<>();
185 final ArrayMap<IBinder, ModeCallback> mModeWatchers = new ArrayMap<>();
186 final ArrayMap<IBinder, SparseArray<ActiveCallback>> mActiveWatchers = new ArrayMap<>();
Dianne Hackborn68d76552017-02-27 15:32:03 -0800187 final SparseArray<SparseArray<Restriction>> mAudioRestrictions = new SparseArray<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800188
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800189 public final class ModeCallback implements DeathRecipient {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800190 final IAppOpsCallback mCallback;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800191 final int mUid;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800192
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800193 public ModeCallback(IAppOpsCallback callback, int uid) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800194 mCallback = callback;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800195 mUid = uid;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800196 try {
197 mCallback.asBinder().linkToDeath(this, 0);
198 } catch (RemoteException e) {
199 }
200 }
201
202 public void unlinkToDeath() {
203 mCallback.asBinder().unlinkToDeath(this, 0);
204 }
205
206 @Override
207 public void binderDied() {
208 stopWatchingMode(mCallback);
209 }
210 }
211
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800212 public final class ActiveCallback implements DeathRecipient {
213 final IAppOpsActiveCallback mCallback;
Svet Ganovf7b47252018-02-26 11:11:27 -0800214 final int mUid;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800215
Svet Ganovf7b47252018-02-26 11:11:27 -0800216 public ActiveCallback(IAppOpsActiveCallback callback, int uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800217 mCallback = callback;
Svet Ganovf7b47252018-02-26 11:11:27 -0800218 mUid = uid;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800219 try {
220 mCallback.asBinder().linkToDeath(this, 0);
221 } catch (RemoteException e) {
222 }
223 }
224
225 public void destroy() {
226 mCallback.asBinder().unlinkToDeath(this, 0);
227 }
228
229 @Override
230 public void binderDied() {
231 stopWatchingActive(mCallback);
232 }
233 }
234
Svet Ganova7a0db62018-02-27 20:08:01 -0800235 final ArrayMap<IBinder, ClientState> mClients = new ArrayMap<>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700236
237 public final class ClientState extends Binder implements DeathRecipient {
Svet Ganovf7b47252018-02-26 11:11:27 -0800238 final ArrayList<Op> mStartedOps = new ArrayList<>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700239 final IBinder mAppToken;
240 final int mPid;
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700241
242 public ClientState(IBinder appToken) {
243 mAppToken = appToken;
244 mPid = Binder.getCallingPid();
Svet Ganovf7b47252018-02-26 11:11:27 -0800245 // Watch only for remote processes dying
246 if (!(appToken instanceof Binder)) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700247 try {
248 mAppToken.linkToDeath(this, 0);
249 } catch (RemoteException e) {
Svet Ganovf7b47252018-02-26 11:11:27 -0800250 /* do nothing */
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700251 }
252 }
253 }
254
255 @Override
256 public String toString() {
257 return "ClientState{" +
258 "mAppToken=" + mAppToken +
Svet Ganovf7b47252018-02-26 11:11:27 -0800259 ", " + "pid=" + mPid +
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700260 '}';
261 }
262
263 @Override
264 public void binderDied() {
265 synchronized (AppOpsService.this) {
266 for (int i=mStartedOps.size()-1; i>=0; i--) {
Svet Ganova7a0db62018-02-27 20:08:01 -0800267 finishOperationLocked(mStartedOps.get(i), /*finishNested*/ true);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700268 }
269 mClients.remove(mAppToken);
270 }
271 }
272 }
273
Jeff Brown6f357d32014-01-15 20:40:55 -0800274 public AppOpsService(File storagePath, Handler handler) {
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600275 LockGuard.installLock(this, LockGuard.INDEX_APP_OPS);
Dianne Hackborne17b4452018-01-10 13:15:40 -0800276 mFile = new AtomicFile(storagePath, "appops");
Jeff Brown6f357d32014-01-15 20:40:55 -0800277 mHandler = handler;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800278 readState();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800279 }
David Braunf5d83192013-09-16 13:43:51 -0700280
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800281 public void publish(Context context) {
282 mContext = context;
283 ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
284 }
285
Dianne Hackborn514074f2013-02-11 10:52:46 -0800286 public void systemReady() {
287 synchronized (this) {
288 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700289 for (int i = mUidStates.size() - 1; i >= 0; i--) {
290 UidState uidState = mUidStates.valueAt(i);
291
292 String[] packageNames = getPackagesForUid(uidState.uid);
293 if (ArrayUtils.isEmpty(packageNames)) {
294 uidState.clear();
295 mUidStates.removeAt(i);
296 changed = true;
297 continue;
298 }
299
300 ArrayMap<String, Ops> pkgs = uidState.pkgOps;
301 if (pkgs == null) {
302 continue;
303 }
304
Dianne Hackborn514074f2013-02-11 10:52:46 -0800305 Iterator<Ops> it = pkgs.values().iterator();
306 while (it.hasNext()) {
307 Ops ops = it.next();
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700308 int curUid = -1;
Dianne Hackborn514074f2013-02-11 10:52:46 -0800309 try {
Jeff Sharkeycd654482016-01-08 17:42:11 -0700310 curUid = AppGlobals.getPackageManager().getPackageUid(ops.packageName,
311 PackageManager.MATCH_UNINSTALLED_PACKAGES,
Svet Ganov2af57082015-07-30 08:44:20 -0700312 UserHandle.getUserId(ops.uidState.uid));
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700313 } catch (RemoteException ignored) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800314 }
Svet Ganov2af57082015-07-30 08:44:20 -0700315 if (curUid != ops.uidState.uid) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800316 Slog.i(TAG, "Pruning old package " + ops.packageName
Svet Ganov2af57082015-07-30 08:44:20 -0700317 + "/" + ops.uidState + ": new uid=" + curUid);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800318 it.remove();
319 changed = true;
320 }
321 }
Svet Ganov2af57082015-07-30 08:44:20 -0700322
323 if (uidState.isDefault()) {
324 mUidStates.removeAt(i);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800325 }
326 }
327 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800328 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800329 }
330 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700331
Suprabh Shuklaaef25132017-01-23 18:09:03 -0800332 PackageManagerInternal packageManagerInternal = LocalServices.getService(
333 PackageManagerInternal.class);
334 packageManagerInternal.setExternalSourcesPolicy(
335 new PackageManagerInternal.ExternalSourcesPolicy() {
336 @Override
337 public int getPackageTrustedToInstallApps(String packageName, int uid) {
338 int appOpMode = checkOperation(AppOpsManager.OP_REQUEST_INSTALL_PACKAGES,
339 uid, packageName);
340 switch (appOpMode) {
341 case AppOpsManager.MODE_ALLOWED:
342 return PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
343 case AppOpsManager.MODE_ERRORED:
344 return PackageManagerInternal.ExternalSourcesPolicy.USER_BLOCKED;
345 default:
346 return PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT;
347 }
348 }
349 });
350
Sudheer Shanka2250d562016-11-07 15:41:02 -0800351 StorageManagerInternal storageManagerInternal = LocalServices.getService(
352 StorageManagerInternal.class);
353 storageManagerInternal.addExternalStoragePolicy(
354 new StorageManagerInternal.ExternalStorageMountPolicy() {
Svet Ganov6ee871e2015-07-10 14:29:33 -0700355 @Override
356 public int getMountMode(int uid, String packageName) {
357 if (Process.isIsolated(uid)) {
358 return Zygote.MOUNT_EXTERNAL_NONE;
359 }
360 if (noteOperation(AppOpsManager.OP_READ_EXTERNAL_STORAGE, uid,
361 packageName) != AppOpsManager.MODE_ALLOWED) {
362 return Zygote.MOUNT_EXTERNAL_NONE;
363 }
364 if (noteOperation(AppOpsManager.OP_WRITE_EXTERNAL_STORAGE, uid,
365 packageName) != AppOpsManager.MODE_ALLOWED) {
366 return Zygote.MOUNT_EXTERNAL_READ;
367 }
368 return Zygote.MOUNT_EXTERNAL_WRITE;
369 }
370
371 @Override
372 public boolean hasExternalStorage(int uid, String packageName) {
373 final int mountMode = getMountMode(uid, packageName);
374 return mountMode == Zygote.MOUNT_EXTERNAL_READ
375 || mountMode == Zygote.MOUNT_EXTERNAL_WRITE;
376 }
377 });
Dianne Hackborn514074f2013-02-11 10:52:46 -0800378 }
379
380 public void packageRemoved(int uid, String packageName) {
381 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700382 UidState uidState = mUidStates.get(uid);
383 if (uidState == null) {
384 return;
385 }
386
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800387 Ops ops = null;
Svet Ganov2af57082015-07-30 08:44:20 -0700388
389 // Remove any package state if such.
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800390 if (uidState.pkgOps != null) {
391 ops = uidState.pkgOps.remove(packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700392 }
393
394 // If we just nuked the last package state check if the UID is valid.
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800395 if (ops != null && uidState.pkgOps.isEmpty()
Svet Ganov2af57082015-07-30 08:44:20 -0700396 && getPackagesForUid(uid).length <= 0) {
397 mUidStates.remove(uid);
398 }
399
Svet Ganova7a0db62018-02-27 20:08:01 -0800400 // Finish ops other packages started on behalf of the package.
401 final int clientCount = mClients.size();
402 for (int i = 0; i < clientCount; i++) {
403 final ClientState client = mClients.valueAt(i);
404 if (client.mStartedOps == null) {
405 continue;
406 }
407 final int opCount = client.mStartedOps.size();
408 for (int j = opCount - 1; j >= 0; j--) {
409 final Op op = client.mStartedOps.get(j);
410 if (uid == op.uid && packageName.equals(op.packageName)) {
411 finishOperationLocked(op, /*finishNested*/ true);
412 client.mStartedOps.remove(j);
413 if (op.nesting <= 0) {
414 scheduleOpActiveChangedIfNeededLocked(op.op,
415 uid, packageName, false);
416 }
417 }
418 }
419 }
420
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800421 if (ops != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700422 scheduleFastWriteLocked();
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800423
424 final int opCount = ops.size();
425 for (int i = 0; i < opCount; i++) {
426 final Op op = ops.valueAt(i);
427 if (op.duration == -1) {
428 scheduleOpActiveChangedIfNeededLocked(
429 op.op, op.uid, op.packageName, false);
430 }
431 }
Dianne Hackborn514074f2013-02-11 10:52:46 -0800432 }
433 }
434 }
435
436 public void uidRemoved(int uid) {
437 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700438 if (mUidStates.indexOfKey(uid) >= 0) {
439 mUidStates.remove(uid);
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800440 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800441 }
442 }
443 }
444
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800445 public void shutdown() {
446 Slog.w(TAG, "Writing app ops before shutdown...");
Dianne Hackborn35654b62013-01-14 17:38:02 -0800447 boolean doWrite = false;
448 synchronized (this) {
449 if (mWriteScheduled) {
450 mWriteScheduled = false;
451 doWrite = true;
452 }
453 }
454 if (doWrite) {
455 writeState();
456 }
457 }
458
Dianne Hackborn72e39832013-01-18 18:36:09 -0800459 private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
460 ArrayList<AppOpsManager.OpEntry> resOps = null;
461 if (ops == null) {
462 resOps = new ArrayList<AppOpsManager.OpEntry>();
463 for (int j=0; j<pkgOps.size(); j++) {
464 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800465 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Svet Ganov99b60432015-06-27 13:15:22 -0700466 curOp.rejectTime, curOp.duration, curOp.proxyUid,
467 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800468 }
469 } else {
470 for (int j=0; j<ops.length; j++) {
471 Op curOp = pkgOps.get(ops[j]);
472 if (curOp != null) {
473 if (resOps == null) {
474 resOps = new ArrayList<AppOpsManager.OpEntry>();
475 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800476 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Svet Ganov99b60432015-06-27 13:15:22 -0700477 curOp.rejectTime, curOp.duration, curOp.proxyUid,
478 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800479 }
480 }
481 }
482 return resOps;
483 }
484
Dianne Hackbornc7214a32017-04-11 13:32:47 -0700485 private ArrayList<AppOpsManager.OpEntry> collectOps(SparseIntArray uidOps, int[] ops) {
486 ArrayList<AppOpsManager.OpEntry> resOps = null;
487 if (ops == null) {
488 resOps = new ArrayList<>();
489 for (int j=0; j<uidOps.size(); j++) {
490 resOps.add(new AppOpsManager.OpEntry(uidOps.keyAt(j), uidOps.valueAt(j),
491 0, 0, 0, -1, null));
492 }
493 } else {
494 for (int j=0; j<ops.length; j++) {
495 int index = uidOps.indexOfKey(ops[j]);
496 if (index >= 0) {
497 if (resOps == null) {
498 resOps = new ArrayList<>();
499 }
500 resOps.add(new AppOpsManager.OpEntry(uidOps.keyAt(index), uidOps.valueAt(index),
501 0, 0, 0, -1, null));
502 }
503 }
504 }
505 return resOps;
506 }
507
Dianne Hackborn35654b62013-01-14 17:38:02 -0800508 @Override
509 public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
510 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
511 Binder.getCallingPid(), Binder.getCallingUid(), null);
512 ArrayList<AppOpsManager.PackageOps> res = null;
513 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700514 final int uidStateCount = mUidStates.size();
515 for (int i = 0; i < uidStateCount; i++) {
516 UidState uidState = mUidStates.valueAt(i);
517 if (uidState.pkgOps == null || uidState.pkgOps.isEmpty()) {
518 continue;
519 }
520 ArrayMap<String, Ops> packages = uidState.pkgOps;
521 final int packageCount = packages.size();
522 for (int j = 0; j < packageCount; j++) {
523 Ops pkgOps = packages.valueAt(j);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800524 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800525 if (resOps != null) {
526 if (res == null) {
527 res = new ArrayList<AppOpsManager.PackageOps>();
528 }
529 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700530 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800531 res.add(resPackage);
532 }
533 }
534 }
535 }
536 return res;
537 }
538
539 @Override
Dianne Hackborn72e39832013-01-18 18:36:09 -0800540 public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
541 int[] ops) {
542 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
543 Binder.getCallingPid(), Binder.getCallingUid(), null);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000544 String resolvedPackageName = resolvePackageName(uid, packageName);
545 if (resolvedPackageName == null) {
546 return Collections.emptyList();
547 }
Dianne Hackborn72e39832013-01-18 18:36:09 -0800548 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -0700549 Ops pkgOps = getOpsRawLocked(uid, resolvedPackageName, false /* edit */,
550 false /* uidMismatchExpected */);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800551 if (pkgOps == null) {
552 return null;
553 }
554 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
555 if (resOps == null) {
556 return null;
557 }
558 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
559 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700560 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800561 res.add(resPackage);
562 return res;
563 }
564 }
565
Dianne Hackbornc7214a32017-04-11 13:32:47 -0700566 @Override
567 public List<AppOpsManager.PackageOps> getUidOps(int uid, int[] ops) {
568 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
569 Binder.getCallingPid(), Binder.getCallingUid(), null);
570 synchronized (this) {
571 UidState uidState = getUidStateLocked(uid, false);
572 if (uidState == null) {
573 return null;
574 }
575 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(uidState.opModes, ops);
576 if (resOps == null) {
577 return null;
578 }
579 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
580 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
581 null, uidState.uid, resOps);
582 res.add(resPackage);
583 return res;
584 }
585 }
586
Dianne Hackborn607b4142013-08-02 18:10:10 -0700587 private void pruneOp(Op op, int uid, String packageName) {
588 if (op.time == 0 && op.rejectTime == 0) {
Yohei Yukawaa965d652017-10-12 15:02:26 -0700589 Ops ops = getOpsRawLocked(uid, packageName, false /* edit */,
590 false /* uidMismatchExpected */);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700591 if (ops != null) {
592 ops.remove(op.op);
593 if (ops.size() <= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -0700594 UidState uidState = ops.uidState;
595 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700596 if (pkgOps != null) {
597 pkgOps.remove(ops.packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700598 if (pkgOps.isEmpty()) {
599 uidState.pkgOps = null;
600 }
601 if (uidState.isDefault()) {
602 mUidStates.remove(uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700603 }
604 }
605 }
606 }
607 }
608 }
609
Dianne Hackborn72e39832013-01-18 18:36:09 -0800610 @Override
Svet Ganov2af57082015-07-30 08:44:20 -0700611 public void setUidMode(int code, int uid, int mode) {
612 if (Binder.getCallingPid() != Process.myPid()) {
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -0800613 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
Svet Ganov2af57082015-07-30 08:44:20 -0700614 Binder.getCallingPid(), Binder.getCallingUid(), null);
615 }
616 verifyIncomingOp(code);
617 code = AppOpsManager.opToSwitch(code);
618
619 synchronized (this) {
620 final int defaultMode = AppOpsManager.opToDefaultMode(code);
621
622 UidState uidState = getUidStateLocked(uid, false);
623 if (uidState == null) {
624 if (mode == defaultMode) {
625 return;
626 }
627 uidState = new UidState(uid);
628 uidState.opModes = new SparseIntArray();
629 uidState.opModes.put(code, mode);
630 mUidStates.put(uid, uidState);
631 scheduleWriteLocked();
632 } else if (uidState.opModes == null) {
633 if (mode != defaultMode) {
634 uidState.opModes = new SparseIntArray();
635 uidState.opModes.put(code, mode);
636 scheduleWriteLocked();
637 }
638 } else {
639 if (uidState.opModes.get(code) == mode) {
640 return;
641 }
642 if (mode == defaultMode) {
643 uidState.opModes.delete(code);
644 if (uidState.opModes.size() <= 0) {
645 uidState.opModes = null;
646 }
647 } else {
648 uidState.opModes.put(code, mode);
649 }
650 scheduleWriteLocked();
651 }
652 }
653
Svetoslav215b44a2015-08-04 19:03:40 -0700654 String[] uidPackageNames = getPackagesForUid(uid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800655 ArrayMap<ModeCallback, ArraySet<String>> callbackSpecs = null;
Svet Ganov2af57082015-07-30 08:44:20 -0700656
riddle_hsu40b300f2015-11-23 13:22:03 +0800657 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800658 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -0700659 if (callbacks != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700660 final int callbackCount = callbacks.size();
661 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800662 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +0800663 ArraySet<String> changedPackages = new ArraySet<>();
664 Collections.addAll(changedPackages, uidPackageNames);
665 callbackSpecs = new ArrayMap<>();
666 callbackSpecs.put(callback, changedPackages);
667 }
668 }
669
670 for (String uidPackageName : uidPackageNames) {
671 callbacks = mPackageModeWatchers.get(uidPackageName);
672 if (callbacks != null) {
673 if (callbackSpecs == null) {
674 callbackSpecs = new ArrayMap<>();
Svet Ganov2af57082015-07-30 08:44:20 -0700675 }
riddle_hsu40b300f2015-11-23 13:22:03 +0800676 final int callbackCount = callbacks.size();
677 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800678 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +0800679 ArraySet<String> changedPackages = callbackSpecs.get(callback);
680 if (changedPackages == null) {
681 changedPackages = new ArraySet<>();
682 callbackSpecs.put(callback, changedPackages);
683 }
684 changedPackages.add(uidPackageName);
685 }
Svet Ganov2af57082015-07-30 08:44:20 -0700686 }
687 }
688 }
689
690 if (callbackSpecs == null) {
691 return;
692 }
693
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800694 for (int i = 0; i < callbackSpecs.size(); i++) {
695 final ModeCallback callback = callbackSpecs.keyAt(i);
696 final ArraySet<String> reportedPackageNames = callbackSpecs.valueAt(i);
697 if (reportedPackageNames == null) {
698 mHandler.sendMessage(PooledLambda.obtainMessage(
699 AppOpsService::notifyOpChanged,
700 this, callback, code, uid, (String) null));
701
702 } else {
703 final int reportedPackageCount = reportedPackageNames.size();
704 for (int j = 0; j < reportedPackageCount; j++) {
705 final String reportedPackageName = reportedPackageNames.valueAt(j);
706 mHandler.sendMessage(PooledLambda.obtainMessage(
707 AppOpsService::notifyOpChanged,
708 this, callback, code, uid, reportedPackageName));
Svet Ganov2af57082015-07-30 08:44:20 -0700709 }
710 }
Svet Ganov2af57082015-07-30 08:44:20 -0700711 }
712 }
713
714 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800715 public void setMode(int code, int uid, String packageName, int mode) {
Dianne Hackbornb64afe12014-07-22 16:29:04 -0700716 if (Binder.getCallingPid() != Process.myPid()) {
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -0800717 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
Dianne Hackbornb64afe12014-07-22 16:29:04 -0700718 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborn133b9df2014-07-01 13:06:10 -0700719 }
Dianne Hackborn961321f2013-02-05 17:22:41 -0800720 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800721 ArraySet<ModeCallback> repCbs = null;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800722 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800723 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700724 UidState uidState = getUidStateLocked(uid, false);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800725 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800726 if (op != null) {
727 if (op.mode != mode) {
728 op.mode = mode;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800729 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800730 if (cbs != null) {
731 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800732 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800733 }
734 repCbs.addAll(cbs);
735 }
736 cbs = mPackageModeWatchers.get(packageName);
737 if (cbs != null) {
738 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800739 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800740 }
741 repCbs.addAll(cbs);
742 }
David Braunf5d83192013-09-16 13:43:51 -0700743 if (mode == AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800744 // If going into the default mode, prune this op
745 // if there is nothing else interesting in it.
Dianne Hackborn607b4142013-08-02 18:10:10 -0700746 pruneOp(op, uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800747 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800748 scheduleFastWriteLocked();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800749 }
750 }
751 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800752 if (repCbs != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800753 mHandler.sendMessage(PooledLambda.obtainMessage(
754 AppOpsService::notifyOpChanged,
755 this, repCbs, code, uid, packageName));
Dianne Hackbornc2293022013-02-06 23:14:49 -0800756 }
757 }
758
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800759 private void notifyOpChanged(ArraySet<ModeCallback> callbacks, int code,
760 int uid, String packageName) {
761 for (int i = 0; i < callbacks.size(); i++) {
762 final ModeCallback callback = callbacks.valueAt(i);
763 notifyOpChanged(callback, code, uid, packageName);
764 }
765 }
766
767 private void notifyOpChanged(ModeCallback callback, int code,
768 int uid, String packageName) {
769 if (callback.mUid >= 0 && callback.mUid != uid) {
770 return;
771 }
772 // There are components watching for mode changes such as window manager
773 // and location manager which are in our process. The callbacks in these
774 // components may require permissions our remote caller does not have.
775 final long identity = Binder.clearCallingIdentity();
776 try {
777 callback.mCallback.opChanged(code, uid, packageName);
778 } catch (RemoteException e) {
779 /* ignore */
780 } finally {
781 Binder.restoreCallingIdentity(identity);
782 }
783 }
784
785 private static HashMap<ModeCallback, ArrayList<ChangeRec>> addCallbacks(
786 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks,
787 int op, int uid, String packageName, ArraySet<ModeCallback> cbs) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700788 if (cbs == null) {
789 return callbacks;
790 }
791 if (callbacks == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700792 callbacks = new HashMap<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700793 }
Svet Ganov2af57082015-07-30 08:44:20 -0700794 boolean duplicate = false;
Dianne Hackborn68d76552017-02-27 15:32:03 -0800795 final int N = cbs.size();
796 for (int i=0; i<N; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800797 ModeCallback cb = cbs.valueAt(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700798 ArrayList<ChangeRec> reports = callbacks.get(cb);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700799 if (reports == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700800 reports = new ArrayList<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700801 callbacks.put(cb, reports);
Svet Ganov2af57082015-07-30 08:44:20 -0700802 } else {
803 final int reportCount = reports.size();
804 for (int j = 0; j < reportCount; j++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700805 ChangeRec report = reports.get(j);
806 if (report.op == op && report.pkg.equals(packageName)) {
Svet Ganov2af57082015-07-30 08:44:20 -0700807 duplicate = true;
808 break;
809 }
810 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700811 }
Svet Ganov2af57082015-07-30 08:44:20 -0700812 if (!duplicate) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700813 reports.add(new ChangeRec(op, uid, packageName));
Svet Ganov2af57082015-07-30 08:44:20 -0700814 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700815 }
816 return callbacks;
817 }
818
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700819 static final class ChangeRec {
820 final int op;
821 final int uid;
822 final String pkg;
823
824 ChangeRec(int _op, int _uid, String _pkg) {
825 op = _op;
826 uid = _uid;
827 pkg = _pkg;
828 }
829 }
830
Dianne Hackborn607b4142013-08-02 18:10:10 -0700831 @Override
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800832 public void resetAllModes(int reqUserId, String reqPackageName) {
833 final int callingPid = Binder.getCallingPid();
834 final int callingUid = Binder.getCallingUid();
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -0800835 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800836 callingPid, callingUid, null);
837 reqUserId = ActivityManager.handleIncomingUser(callingPid, callingUid, reqUserId,
838 true, true, "resetAllModes", null);
Svet Ganov2af57082015-07-30 08:44:20 -0700839
840 int reqUid = -1;
841 if (reqPackageName != null) {
842 try {
843 reqUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -0700844 reqPackageName, PackageManager.MATCH_UNINSTALLED_PACKAGES, reqUserId);
Svet Ganov2af57082015-07-30 08:44:20 -0700845 } catch (RemoteException e) {
846 /* ignore - local call */
847 }
848 }
849
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800850 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks = null;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700851 synchronized (this) {
852 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700853 for (int i = mUidStates.size() - 1; i >= 0; i--) {
854 UidState uidState = mUidStates.valueAt(i);
855
856 SparseIntArray opModes = uidState.opModes;
857 if (opModes != null && (uidState.uid == reqUid || reqUid == -1)) {
858 final int uidOpCount = opModes.size();
859 for (int j = uidOpCount - 1; j >= 0; j--) {
860 final int code = opModes.keyAt(j);
861 if (AppOpsManager.opAllowsReset(code)) {
862 opModes.removeAt(j);
863 if (opModes.size() <= 0) {
864 uidState.opModes = null;
865 }
866 for (String packageName : getPackagesForUid(uidState.uid)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700867 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700868 mOpModeWatchers.get(code));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700869 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700870 mPackageModeWatchers.get(packageName));
871 }
872 }
873 }
874 }
875
876 if (uidState.pkgOps == null) {
877 continue;
878 }
879
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800880 if (reqUserId != UserHandle.USER_ALL
Svet Ganov2af57082015-07-30 08:44:20 -0700881 && reqUserId != UserHandle.getUserId(uidState.uid)) {
Alexandra Gherghinad6a98972014-08-04 17:05:34 +0100882 // Skip any ops for a different user
883 continue;
884 }
Svet Ganov2af57082015-07-30 08:44:20 -0700885
886 Map<String, Ops> packages = uidState.pkgOps;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700887 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
888 while (it.hasNext()) {
889 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700890 String packageName = ent.getKey();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800891 if (reqPackageName != null && !reqPackageName.equals(packageName)) {
892 // Skip any ops for a different package
893 continue;
894 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700895 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700896 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700897 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -0700898 if (AppOpsManager.opAllowsReset(curOp.op)
899 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -0700900 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700901 changed = true;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700902 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -0700903 mOpModeWatchers.get(curOp.op));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700904 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -0700905 mPackageModeWatchers.get(packageName));
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700906 if (curOp.time == 0 && curOp.rejectTime == 0) {
907 pkgOps.removeAt(j);
908 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700909 }
910 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700911 if (pkgOps.size() == 0) {
912 it.remove();
913 }
914 }
Svet Ganov2af57082015-07-30 08:44:20 -0700915 if (uidState.isDefault()) {
916 mUidStates.remove(uidState.uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700917 }
918 }
Svet Ganov2af57082015-07-30 08:44:20 -0700919
Dianne Hackborn607b4142013-08-02 18:10:10 -0700920 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800921 scheduleFastWriteLocked();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700922 }
923 }
924 if (callbacks != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800925 for (Map.Entry<ModeCallback, ArrayList<ChangeRec>> ent : callbacks.entrySet()) {
926 ModeCallback cb = ent.getKey();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700927 ArrayList<ChangeRec> reports = ent.getValue();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700928 for (int i=0; i<reports.size(); i++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700929 ChangeRec rep = reports.get(i);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800930 mHandler.sendMessage(PooledLambda.obtainMessage(
931 AppOpsService::notifyOpChanged,
932 this, cb, rep.op, rep.uid, rep.pkg));
Dianne Hackborn607b4142013-08-02 18:10:10 -0700933 }
934 }
935 }
936 }
937
Dianne Hackbornc2293022013-02-06 23:14:49 -0800938 @Override
939 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800940 int watchedUid = -1;
941 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
942 != PackageManager.PERMISSION_GRANTED) {
943 watchedUid = Binder.getCallingUid();
944 }
945 Preconditions.checkArgumentInRange(op, AppOpsManager.OP_NONE,
946 AppOpsManager._NUM_OP - 1, "Invalid op code: " + op);
Svetoslav Ganov8de59712015-12-09 18:25:13 -0800947 if (callback == null) {
948 return;
949 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800950 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700951 op = (op != AppOpsManager.OP_NONE) ? AppOpsManager.opToSwitch(op) : op;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800952 ModeCallback cb = mModeWatchers.get(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -0800953 if (cb == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800954 cb = new ModeCallback(callback, watchedUid);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800955 mModeWatchers.put(callback.asBinder(), cb);
956 }
957 if (op != AppOpsManager.OP_NONE) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800958 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(op);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800959 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800960 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800961 mOpModeWatchers.put(op, cbs);
962 }
963 cbs.add(cb);
964 }
965 if (packageName != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800966 ArraySet<ModeCallback> cbs = mPackageModeWatchers.get(packageName);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800967 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800968 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800969 mPackageModeWatchers.put(packageName, cbs);
970 }
971 cbs.add(cb);
972 }
973 }
974 }
975
976 @Override
977 public void stopWatchingMode(IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -0800978 if (callback == null) {
979 return;
980 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800981 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800982 ModeCallback cb = mModeWatchers.remove(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -0800983 if (cb != null) {
984 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700985 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800986 ArraySet<ModeCallback> cbs = mOpModeWatchers.valueAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800987 cbs.remove(cb);
988 if (cbs.size() <= 0) {
989 mOpModeWatchers.removeAt(i);
990 }
991 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700992 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800993 ArraySet<ModeCallback> cbs = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700994 cbs.remove(cb);
995 if (cbs.size() <= 0) {
996 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800997 }
998 }
999 }
1000 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001001 }
1002
1003 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001004 public IBinder getToken(IBinder clientToken) {
1005 synchronized (this) {
1006 ClientState cs = mClients.get(clientToken);
1007 if (cs == null) {
1008 cs = new ClientState(clientToken);
1009 mClients.put(clientToken, cs);
1010 }
1011 return cs;
1012 }
1013 }
1014
1015 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -08001016 public int checkOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001017 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001018 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001019 String resolvedPackageName = resolvePackageName(uid, packageName);
1020 if (resolvedPackageName == null) {
1021 return AppOpsManager.MODE_IGNORED;
1022 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001023 synchronized (this) {
Svet Ganov442ed572016-08-17 17:29:43 -07001024 if (isOpRestrictedLocked(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001025 return AppOpsManager.MODE_IGNORED;
1026 }
Svet Ganov2af57082015-07-30 08:44:20 -07001027 code = AppOpsManager.opToSwitch(code);
1028 UidState uidState = getUidStateLocked(uid, false);
Svet Ganovee438d42017-01-19 18:04:38 -08001029 if (uidState != null && uidState.opModes != null
1030 && uidState.opModes.indexOfKey(code) >= 0) {
1031 return uidState.opModes.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001032 }
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001033 Op op = getOpLocked(code, uid, resolvedPackageName, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001034 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -07001035 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001036 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001037 return op.mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001038 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001039 }
1040
1041 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001042 public int checkAudioOperation(int code, int usage, int uid, String packageName) {
Andrei Stingaceanuefc4a342016-03-22 14:43:01 +00001043 boolean suspended;
1044 try {
1045 suspended = isPackageSuspendedForUser(packageName, uid);
1046 } catch (IllegalArgumentException ex) {
1047 // Package not found.
1048 suspended = false;
1049 }
1050
1051 if (suspended) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001052 Slog.i(TAG, "Audio disabled for suspended package=" + packageName + " for uid=" + uid);
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001053 return AppOpsManager.MODE_IGNORED;
1054 }
1055
John Spurlock1af30c72014-03-10 08:33:35 -04001056 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001057 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -04001058 if (mode != AppOpsManager.MODE_ALLOWED) {
1059 return mode;
1060 }
1061 }
1062 return checkOperation(code, uid, packageName);
1063 }
1064
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001065 private boolean isPackageSuspendedForUser(String pkg, int uid) {
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001066 try {
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001067 return AppGlobals.getPackageManager().isPackageSuspendedForUser(
1068 pkg, UserHandle.getUserId(uid));
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001069 } catch (RemoteException re) {
1070 throw new SecurityException("Could not talk to package manager service");
1071 }
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001072 }
1073
John Spurlock7b414672014-07-18 13:02:39 -04001074 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
1075 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1076 if (usageRestrictions != null) {
1077 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001078 if (r != null && !r.exceptionPackages.contains(packageName)) {
1079 return r.mode;
1080 }
1081 }
1082 return AppOpsManager.MODE_ALLOWED;
1083 }
1084
1085 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001086 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -04001087 String[] exceptionPackages) {
1088 verifyIncomingUid(uid);
1089 verifyIncomingOp(code);
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -08001090 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
1091 Binder.getCallingPid(), Binder.getCallingUid(), null);
John Spurlock1af30c72014-03-10 08:33:35 -04001092 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001093 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1094 if (usageRestrictions == null) {
1095 usageRestrictions = new SparseArray<Restriction>();
1096 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -04001097 }
John Spurlock7b414672014-07-18 13:02:39 -04001098 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001099 if (mode != AppOpsManager.MODE_ALLOWED) {
1100 final Restriction r = new Restriction();
1101 r.mode = mode;
1102 if (exceptionPackages != null) {
1103 final int N = exceptionPackages.length;
1104 r.exceptionPackages = new ArraySet<String>(N);
1105 for (int i = 0; i < N; i++) {
1106 final String pkg = exceptionPackages[i];
1107 if (pkg != null) {
1108 r.exceptionPackages.add(pkg.trim());
1109 }
1110 }
1111 }
John Spurlock7b414672014-07-18 13:02:39 -04001112 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -04001113 }
1114 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001115
1116 mHandler.sendMessage(PooledLambda.obtainMessage(
1117 AppOpsService::notifyWatchersOfChange, this, code));
John Spurlock1af30c72014-03-10 08:33:35 -04001118 }
1119
1120 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001121 public int checkPackage(int uid, String packageName) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001122 Preconditions.checkNotNull(packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001123 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001124 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1125 true /* uidMismatchExpected */);
1126 if (ops != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001127 return AppOpsManager.MODE_ALLOWED;
1128 } else {
1129 return AppOpsManager.MODE_ERRORED;
1130 }
1131 }
1132 }
1133
1134 @Override
Svet Ganov99b60432015-06-27 13:15:22 -07001135 public int noteProxyOperation(int code, String proxyPackageName,
1136 int proxiedUid, String proxiedPackageName) {
1137 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001138 final int proxyUid = Binder.getCallingUid();
1139 String resolveProxyPackageName = resolvePackageName(proxyUid, proxyPackageName);
1140 if (resolveProxyPackageName == null) {
1141 return AppOpsManager.MODE_IGNORED;
1142 }
1143 final int proxyMode = noteOperationUnchecked(code, proxyUid,
1144 resolveProxyPackageName, -1, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001145 if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
1146 return proxyMode;
1147 }
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001148 String resolveProxiedPackageName = resolvePackageName(proxiedUid, proxiedPackageName);
1149 if (resolveProxiedPackageName == null) {
1150 return AppOpsManager.MODE_IGNORED;
1151 }
1152 return noteOperationUnchecked(code, proxiedUid, resolveProxiedPackageName,
1153 proxyMode, resolveProxyPackageName);
Svet Ganov99b60432015-06-27 13:15:22 -07001154 }
1155
1156 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001157 public int noteOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001158 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001159 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001160 String resolvedPackageName = resolvePackageName(uid, packageName);
1161 if (resolvedPackageName == null) {
1162 return AppOpsManager.MODE_IGNORED;
1163 }
1164 return noteOperationUnchecked(code, uid, resolvedPackageName, 0, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001165 }
1166
1167 private int noteOperationUnchecked(int code, int uid, String packageName,
1168 int proxyUid, String proxyPackageName) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001169 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001170 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1171 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001172 if (ops == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001173 if (DEBUG) Slog.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001174 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001175 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001176 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001177 Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07001178 if (isOpRestrictedLocked(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001179 return AppOpsManager.MODE_IGNORED;
1180 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001181 if (op.duration == -1) {
1182 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
1183 + " code " + code + " time=" + op.time + " duration=" + op.duration);
1184 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001185 op.duration = 0;
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001186 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001187 UidState uidState = ops.uidState;
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001188 // If there is a non-default per UID policy (we set UID op mode only if
1189 // non-default) it takes over, otherwise use the per package policy.
1190 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -07001191 final int uidMode = uidState.opModes.get(switchCode);
1192 if (uidMode != AppOpsManager.MODE_ALLOWED) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001193 if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + op.mode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07001194 + switchCode + " (" + code + ") uid " + uid + " package "
1195 + packageName);
1196 op.rejectTime = System.currentTimeMillis();
1197 return uidMode;
1198 }
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001199 } else {
1200 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
1201 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001202 if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + op.mode + " for code "
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001203 + switchCode + " (" + code + ") uid " + uid + " package "
1204 + packageName);
1205 op.rejectTime = System.currentTimeMillis();
1206 return switchOp.mode;
1207 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001208 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001209 if (DEBUG) Slog.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001210 + " package " + packageName);
1211 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001212 op.rejectTime = 0;
Svet Ganov99b60432015-06-27 13:15:22 -07001213 op.proxyUid = proxyUid;
1214 op.proxyPackageName = proxyPackageName;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001215 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001216 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001217 }
1218
1219 @Override
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001220 public void startWatchingActive(int[] ops, IAppOpsActiveCallback callback) {
Svet Ganovf7b47252018-02-26 11:11:27 -08001221 int watchedUid = -1;
1222 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
1223 != PackageManager.PERMISSION_GRANTED) {
1224 watchedUid = Binder.getCallingUid();
1225 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001226 if (ops != null) {
1227 Preconditions.checkArrayElementsInRange(ops, 0,
1228 AppOpsManager._NUM_OP - 1, "Invalid op code in: " + Arrays.toString(ops));
1229 }
1230 if (callback == null) {
1231 return;
1232 }
1233 synchronized (this) {
1234 SparseArray<ActiveCallback> callbacks = mActiveWatchers.get(callback.asBinder());
1235 if (callbacks == null) {
1236 callbacks = new SparseArray<>();
1237 mActiveWatchers.put(callback.asBinder(), callbacks);
1238 }
Svet Ganovf7b47252018-02-26 11:11:27 -08001239 final ActiveCallback activeCallback = new ActiveCallback(callback, watchedUid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001240 for (int op : ops) {
1241 callbacks.put(op, activeCallback);
1242 }
1243 }
1244 }
1245
1246 @Override
1247 public void stopWatchingActive(IAppOpsActiveCallback callback) {
1248 if (callback == null) {
1249 return;
1250 }
1251 synchronized (this) {
1252 final SparseArray<ActiveCallback> activeCallbacks =
1253 mActiveWatchers.remove(callback.asBinder());
1254 if (activeCallbacks == null) {
1255 return;
1256 }
1257 final int callbackCount = activeCallbacks.size();
1258 for (int i = 0; i < callbackCount; i++) {
1259 // Apps ops are mapped to a singleton
1260 if (i == 0) {
1261 activeCallbacks.valueAt(i).destroy();
1262 }
1263 }
1264 }
1265 }
1266
1267 @Override
Svet Ganovf7b47252018-02-26 11:11:27 -08001268 public int startOperation(IBinder token, int code, int uid, String packageName,
1269 boolean startIfModeDefault) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001270 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001271 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001272 String resolvedPackageName = resolvePackageName(uid, packageName);
1273 if (resolvedPackageName == null) {
1274 return AppOpsManager.MODE_IGNORED;
1275 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001276 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001277 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001278 Ops ops = getOpsRawLocked(uid, resolvedPackageName, true /* edit */,
1279 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001280 if (ops == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001281 if (DEBUG) Slog.d(TAG, "startOperation: no op for code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001282 + " package " + resolvedPackageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001283 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001284 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001285 Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07001286 if (isOpRestrictedLocked(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001287 return AppOpsManager.MODE_IGNORED;
1288 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001289 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001290 UidState uidState = ops.uidState;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001291 // If there is a non-default per UID policy (we set UID op mode only if
1292 // non-default) it takes over, otherwise use the per package policy.
1293 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -07001294 final int uidMode = uidState.opModes.get(switchCode);
Svet Ganovf7b47252018-02-26 11:11:27 -08001295 if (uidMode != AppOpsManager.MODE_ALLOWED
1296 && (!startIfModeDefault || uidMode != AppOpsManager.MODE_DEFAULT)) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001297 if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + op.mode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07001298 + switchCode + " (" + code + ") uid " + uid + " package "
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001299 + resolvedPackageName);
Svet Ganov2af57082015-07-30 08:44:20 -07001300 op.rejectTime = System.currentTimeMillis();
1301 return uidMode;
1302 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001303 } else {
1304 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
Svet Ganovf7b47252018-02-26 11:11:27 -08001305 if (switchOp.mode != AppOpsManager.MODE_ALLOWED
1306 && (!startIfModeDefault || switchOp.mode != AppOpsManager.MODE_DEFAULT)) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001307 if (DEBUG) Slog.d(TAG, "startOperation: reject #" + op.mode + " for code "
1308 + switchCode + " (" + code + ") uid " + uid + " package "
1309 + resolvedPackageName);
1310 op.rejectTime = System.currentTimeMillis();
1311 return switchOp.mode;
1312 }
Svet Ganov2af57082015-07-30 08:44:20 -07001313 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001314 if (DEBUG) Slog.d(TAG, "startOperation: allowing code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001315 + " package " + resolvedPackageName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001316 if (op.nesting == 0) {
1317 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001318 op.rejectTime = 0;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001319 op.duration = -1;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001320 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001321 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001322 op.nesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001323 if (client.mStartedOps != null) {
1324 client.mStartedOps.add(op);
1325 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001326 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001327
1328 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001329 }
1330
1331 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001332 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001333 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001334 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001335 String resolvedPackageName = resolvePackageName(uid, packageName);
1336 if (resolvedPackageName == null) {
1337 return;
1338 }
1339 if (!(token instanceof ClientState)) {
1340 return;
1341 }
1342 ClientState client = (ClientState) token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001343 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001344 Op op = getOpLocked(code, uid, resolvedPackageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001345 if (op == null) {
1346 return;
1347 }
Svet Ganovf7b47252018-02-26 11:11:27 -08001348 if (!client.mStartedOps.remove(op)) {
Svet Ganov31d83ae2018-03-15 10:45:56 -07001349 Slog.wtf(TAG, "Operation not started: uid" + op.uid
Svet Ganovf7b47252018-02-26 11:11:27 -08001350 + " pkg=" + op.packageName + " op=" + op.op);
Svet Ganov31d83ae2018-03-15 10:45:56 -07001351 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001352 }
Svet Ganova7a0db62018-02-27 20:08:01 -08001353 finishOperationLocked(op, /*finishNested*/ false);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001354 if (op.nesting <= 0) {
1355 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, false);
1356 }
1357 }
1358 }
1359
1360 private void scheduleOpActiveChangedIfNeededLocked(int code, int uid, String packageName,
1361 boolean active) {
1362 ArraySet<ActiveCallback> dispatchedCallbacks = null;
1363 final int callbackListCount = mActiveWatchers.size();
1364 for (int i = 0; i < callbackListCount; i++) {
1365 final SparseArray<ActiveCallback> callbacks = mActiveWatchers.valueAt(i);
1366 ActiveCallback callback = callbacks.get(code);
1367 if (callback != null) {
Svet Ganovf7b47252018-02-26 11:11:27 -08001368 if (callback.mUid >= 0 && callback.mUid != uid) {
1369 continue;
1370 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001371 if (dispatchedCallbacks == null) {
1372 dispatchedCallbacks = new ArraySet<>();
1373 }
1374 dispatchedCallbacks.add(callback);
1375 }
1376 }
1377 if (dispatchedCallbacks == null) {
1378 return;
1379 }
1380 mHandler.sendMessage(PooledLambda.obtainMessage(
1381 AppOpsService::notifyOpActiveChanged,
1382 this, dispatchedCallbacks, code, uid, packageName, active));
1383 }
1384
1385 private void notifyOpActiveChanged(ArraySet<ActiveCallback> callbacks,
1386 int code, int uid, String packageName, boolean active) {
1387 // There are components watching for mode changes such as window manager
1388 // and location manager which are in our process. The callbacks in these
1389 // components may require permissions our remote caller does not have.
1390 final long identity = Binder.clearCallingIdentity();
1391 try {
1392 final int callbackCount = callbacks.size();
1393 for (int i = 0; i < callbackCount; i++) {
1394 final ActiveCallback callback = callbacks.valueAt(i);
1395 try {
1396 callback.mCallback.opActiveChanged(code, uid, packageName, active);
1397 } catch (RemoteException e) {
1398 /* do nothing */
1399 }
1400 }
1401 } finally {
1402 Binder.restoreCallingIdentity(identity);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001403 }
1404 }
1405
Svet Ganovb9d71a62015-04-30 10:38:13 -07001406 @Override
1407 public int permissionToOpCode(String permission) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001408 if (permission == null) {
1409 return AppOpsManager.OP_NONE;
1410 }
Svet Ganovb9d71a62015-04-30 10:38:13 -07001411 return AppOpsManager.permissionToOpCode(permission);
1412 }
1413
Svet Ganova7a0db62018-02-27 20:08:01 -08001414 void finishOperationLocked(Op op, boolean finishNested) {
1415 if (op.nesting <= 1 || finishNested) {
1416 if (op.nesting == 1 || finishNested) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001417 op.duration = (int)(System.currentTimeMillis() - op.time);
1418 op.time += op.duration;
1419 } else {
1420 Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
1421 + op.packageName + " code " + op.op + " time=" + op.time
1422 + " duration=" + op.duration + " nesting=" + op.nesting);
1423 }
1424 op.nesting = 0;
1425 } else {
1426 op.nesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001427 }
1428 }
1429
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001430 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001431 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001432 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001433 }
1434 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001435 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001436 }
1437 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
1438 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001439 }
1440
Dianne Hackborn961321f2013-02-05 17:22:41 -08001441 private void verifyIncomingOp(int op) {
1442 if (op >= 0 && op < AppOpsManager._NUM_OP) {
1443 return;
1444 }
1445 throw new IllegalArgumentException("Bad operation #" + op);
1446 }
1447
Svet Ganov2af57082015-07-30 08:44:20 -07001448 private UidState getUidStateLocked(int uid, boolean edit) {
1449 UidState uidState = mUidStates.get(uid);
1450 if (uidState == null) {
1451 if (!edit) {
1452 return null;
1453 }
1454 uidState = new UidState(uid);
1455 mUidStates.put(uid, uidState);
1456 }
1457 return uidState;
1458 }
1459
Yohei Yukawaa965d652017-10-12 15:02:26 -07001460 private Ops getOpsRawLocked(int uid, String packageName, boolean edit,
1461 boolean uidMismatchExpected) {
Svet Ganov2af57082015-07-30 08:44:20 -07001462 UidState uidState = getUidStateLocked(uid, edit);
1463 if (uidState == null) {
1464 return null;
1465 }
1466
1467 if (uidState.pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001468 if (!edit) {
1469 return null;
1470 }
Svet Ganov2af57082015-07-30 08:44:20 -07001471 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001472 }
Svet Ganov2af57082015-07-30 08:44:20 -07001473
1474 Ops ops = uidState.pkgOps.get(packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001475 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001476 if (!edit) {
1477 return null;
1478 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001479 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001480 // This is the first time we have seen this package name under this uid,
1481 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -08001482 if (uid != 0) {
1483 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001484 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001485 int pkgUid = -1;
1486 try {
Jason Monk1c7c3192014-06-26 12:52:18 -04001487 ApplicationInfo appInfo = ActivityThread.getPackageManager()
Jeff Sharkeycd654482016-01-08 17:42:11 -07001488 .getApplicationInfo(packageName,
1489 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1490 UserHandle.getUserId(uid));
Jason Monk1c7c3192014-06-26 12:52:18 -04001491 if (appInfo != null) {
1492 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001493 isPrivileged = (appInfo.privateFlags
1494 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001495 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08001496 pkgUid = resolveUid(packageName);
1497 if (pkgUid >= 0) {
Chien-Yu Chen75cade02016-01-11 10:56:21 -08001498 isPrivileged = false;
Jason Monk1c7c3192014-06-26 12:52:18 -04001499 }
Dianne Hackborn713df152013-05-17 11:27:57 -07001500 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001501 } catch (RemoteException e) {
1502 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001503 }
1504 if (pkgUid != uid) {
1505 // Oops! The package name is not valid for the uid they are calling
1506 // under. Abort.
Yohei Yukawaa965d652017-10-12 15:02:26 -07001507 if (!uidMismatchExpected) {
1508 RuntimeException ex = new RuntimeException("here");
1509 ex.fillInStackTrace();
1510 Slog.w(TAG, "Bad call: specified package " + packageName
1511 + " under uid " + uid + " but it is really " + pkgUid, ex);
1512 }
Dianne Hackborn514074f2013-02-11 10:52:46 -08001513 return null;
1514 }
1515 } finally {
1516 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001517 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001518 }
Svet Ganov2af57082015-07-30 08:44:20 -07001519 ops = new Ops(packageName, uidState, isPrivileged);
1520 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001521 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08001522 return ops;
1523 }
1524
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001525 private void scheduleWriteLocked() {
1526 if (!mWriteScheduled) {
1527 mWriteScheduled = true;
1528 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
1529 }
1530 }
1531
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001532 private void scheduleFastWriteLocked() {
1533 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001534 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001535 mFastWriteScheduled = true;
1536 mHandler.removeCallbacks(mWriteRunner);
1537 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001538 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001539 }
1540
Dianne Hackborn72e39832013-01-18 18:36:09 -08001541 private Op getOpLocked(int code, int uid, String packageName, boolean edit) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001542 Ops ops = getOpsRawLocked(uid, packageName, edit,
1543 false /* uidMismatchExpected */);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001544 if (ops == null) {
1545 return null;
1546 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001547 return getOpLocked(ops, code, edit);
1548 }
1549
1550 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001551 Op op = ops.get(code);
1552 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001553 if (!edit) {
1554 return null;
1555 }
Svet Ganov2af57082015-07-30 08:44:20 -07001556 op = new Op(ops.uidState.uid, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001557 ops.put(code, op);
1558 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001559 if (edit) {
1560 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001561 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001562 return op;
1563 }
1564
Svet Ganov442ed572016-08-17 17:29:43 -07001565 private boolean isOpRestrictedLocked(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04001566 int userHandle = UserHandle.getUserId(uid);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001567 final int restrictionSetCount = mOpUserRestrictions.size();
Ruben Brunk29931bc2016-03-11 00:24:26 -08001568
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001569 for (int i = 0; i < restrictionSetCount; i++) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08001570 // For each client, check that the given op is not restricted, or that the given
1571 // package is exempt from the restriction.
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07001572 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07001573 if (restrictionState.hasRestriction(code, packageName, userHandle)) {
1574 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
1575 // If we are the system, bypass user restrictions for certain codes
1576 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001577 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1578 false /* uidMismatchExpected */);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07001579 if ((ops != null) && ops.isPrivileged) {
1580 return false;
1581 }
Ruben Brunk32f0fa42016-03-11 19:07:07 -08001582 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08001583 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001584 return true;
Jason Monk1c7c3192014-06-26 12:52:18 -04001585 }
Jason Monk62062992014-05-06 09:55:28 -04001586 }
1587 return false;
1588 }
1589
Dianne Hackborn35654b62013-01-14 17:38:02 -08001590 void readState() {
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001591 int oldVersion = NO_VERSION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001592 synchronized (mFile) {
1593 synchronized (this) {
1594 FileInputStream stream;
1595 try {
1596 stream = mFile.openRead();
1597 } catch (FileNotFoundException e) {
1598 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
1599 return;
1600 }
1601 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001602 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001603 try {
1604 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001605 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001606 int type;
1607 while ((type = parser.next()) != XmlPullParser.START_TAG
1608 && type != XmlPullParser.END_DOCUMENT) {
1609 ;
1610 }
1611
1612 if (type != XmlPullParser.START_TAG) {
1613 throw new IllegalStateException("no start tag found");
1614 }
1615
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001616 final String versionString = parser.getAttributeValue(null, "v");
1617 if (versionString != null) {
1618 oldVersion = Integer.parseInt(versionString);
1619 }
1620
Dianne Hackborn35654b62013-01-14 17:38:02 -08001621 int outerDepth = parser.getDepth();
1622 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1623 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1624 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1625 continue;
1626 }
1627
1628 String tagName = parser.getName();
1629 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001630 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07001631 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07001632 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001633 } else {
1634 Slog.w(TAG, "Unknown element under <app-ops>: "
1635 + parser.getName());
1636 XmlUtils.skipCurrentTag(parser);
1637 }
1638 }
1639 success = true;
1640 } catch (IllegalStateException e) {
1641 Slog.w(TAG, "Failed parsing " + e);
1642 } catch (NullPointerException e) {
1643 Slog.w(TAG, "Failed parsing " + e);
1644 } catch (NumberFormatException e) {
1645 Slog.w(TAG, "Failed parsing " + e);
1646 } catch (XmlPullParserException e) {
1647 Slog.w(TAG, "Failed parsing " + e);
1648 } catch (IOException e) {
1649 Slog.w(TAG, "Failed parsing " + e);
1650 } catch (IndexOutOfBoundsException e) {
1651 Slog.w(TAG, "Failed parsing " + e);
1652 } finally {
1653 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07001654 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001655 }
1656 try {
1657 stream.close();
1658 } catch (IOException e) {
1659 }
1660 }
1661 }
1662 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001663 synchronized (this) {
1664 upgradeLocked(oldVersion);
1665 }
1666 }
1667
1668 private void upgradeRunAnyInBackgroundLocked() {
1669 for (int i = 0; i < mUidStates.size(); i++) {
1670 final UidState uidState = mUidStates.valueAt(i);
1671 if (uidState == null) {
1672 continue;
1673 }
1674 if (uidState.opModes != null) {
1675 final int idx = uidState.opModes.indexOfKey(AppOpsManager.OP_RUN_IN_BACKGROUND);
1676 if (idx >= 0) {
1677 uidState.opModes.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND,
1678 uidState.opModes.valueAt(idx));
1679 }
1680 }
1681 if (uidState.pkgOps == null) {
1682 continue;
1683 }
1684 for (int j = 0; j < uidState.pkgOps.size(); j++) {
1685 Ops ops = uidState.pkgOps.valueAt(j);
1686 if (ops != null) {
1687 final Op op = ops.get(AppOpsManager.OP_RUN_IN_BACKGROUND);
1688 if (op != null && op.mode != AppOpsManager.opToDefaultMode(op.op)) {
1689 final Op copy = new Op(op.uid, op.packageName,
1690 AppOpsManager.OP_RUN_ANY_IN_BACKGROUND);
1691 copy.mode = op.mode;
1692 ops.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, copy);
1693 }
1694 }
1695 }
1696 }
1697 }
1698
1699 private void upgradeLocked(int oldVersion) {
1700 if (oldVersion >= CURRENT_VERSION) {
1701 return;
1702 }
1703 Slog.d(TAG, "Upgrading app-ops xml from version " + oldVersion + " to " + CURRENT_VERSION);
1704 switch (oldVersion) {
1705 case NO_VERSION:
1706 upgradeRunAnyInBackgroundLocked();
1707 // fall through
1708 case 1:
1709 // for future upgrades
1710 }
1711 scheduleFastWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001712 }
1713
Svet Ganov2af57082015-07-30 08:44:20 -07001714 void readUidOps(XmlPullParser parser) throws NumberFormatException,
1715 XmlPullParserException, IOException {
1716 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
1717 int outerDepth = parser.getDepth();
1718 int type;
1719 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1720 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1721 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1722 continue;
1723 }
1724
1725 String tagName = parser.getName();
1726 if (tagName.equals("op")) {
1727 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
1728 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
1729 UidState uidState = getUidStateLocked(uid, true);
1730 if (uidState.opModes == null) {
1731 uidState.opModes = new SparseIntArray();
1732 }
1733 uidState.opModes.put(code, mode);
1734 } else {
1735 Slog.w(TAG, "Unknown element under <uid-ops>: "
1736 + parser.getName());
1737 XmlUtils.skipCurrentTag(parser);
1738 }
1739 }
1740 }
1741
Dave Burke0997c5bd2013-08-02 20:25:02 +00001742 void readPackage(XmlPullParser parser) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001743 XmlPullParserException, IOException {
1744 String pkgName = parser.getAttributeValue(null, "n");
1745 int outerDepth = parser.getDepth();
1746 int type;
1747 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1748 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1749 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1750 continue;
1751 }
1752
1753 String tagName = parser.getName();
1754 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001755 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001756 } else {
1757 Slog.w(TAG, "Unknown element under <pkg>: "
1758 + parser.getName());
1759 XmlUtils.skipCurrentTag(parser);
1760 }
1761 }
1762 }
1763
Dave Burke0997c5bd2013-08-02 20:25:02 +00001764 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001765 XmlPullParserException, IOException {
1766 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Jason Monk1c7c3192014-06-26 12:52:18 -04001767 String isPrivilegedString = parser.getAttributeValue(null, "p");
1768 boolean isPrivileged = false;
1769 if (isPrivilegedString == null) {
1770 try {
1771 IPackageManager packageManager = ActivityThread.getPackageManager();
1772 if (packageManager != null) {
1773 ApplicationInfo appInfo = ActivityThread.getPackageManager()
1774 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
1775 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001776 isPrivileged = (appInfo.privateFlags
1777 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001778 }
1779 } else {
1780 // Could not load data, don't add to cache so it will be loaded later.
1781 return;
1782 }
1783 } catch (RemoteException e) {
1784 Slog.w(TAG, "Could not contact PackageManager", e);
1785 }
1786 } else {
1787 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
1788 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001789 int outerDepth = parser.getDepth();
1790 int type;
1791 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1792 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1793 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1794 continue;
1795 }
1796
1797 String tagName = parser.getName();
1798 if (tagName.equals("op")) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001799 Op op = new Op(uid, pkgName, Integer.parseInt(parser.getAttributeValue(null, "n")));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001800 String mode = parser.getAttributeValue(null, "m");
1801 if (mode != null) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001802 op.mode = Integer.parseInt(mode);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001803 }
1804 String time = parser.getAttributeValue(null, "t");
1805 if (time != null) {
1806 op.time = Long.parseLong(time);
1807 }
1808 time = parser.getAttributeValue(null, "r");
1809 if (time != null) {
1810 op.rejectTime = Long.parseLong(time);
1811 }
1812 String dur = parser.getAttributeValue(null, "d");
1813 if (dur != null) {
1814 op.duration = Integer.parseInt(dur);
1815 }
Svet Ganov99b60432015-06-27 13:15:22 -07001816 String proxyUid = parser.getAttributeValue(null, "pu");
1817 if (proxyUid != null) {
1818 op.proxyUid = Integer.parseInt(proxyUid);
1819 }
1820 String proxyPackageName = parser.getAttributeValue(null, "pp");
1821 if (proxyPackageName != null) {
1822 op.proxyPackageName = proxyPackageName;
1823 }
Svet Ganov2af57082015-07-30 08:44:20 -07001824
1825 UidState uidState = getUidStateLocked(uid, true);
1826 if (uidState.pkgOps == null) {
1827 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001828 }
Svet Ganov2af57082015-07-30 08:44:20 -07001829
1830 Ops ops = uidState.pkgOps.get(pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001831 if (ops == null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001832 ops = new Ops(pkgName, uidState, isPrivileged);
1833 uidState.pkgOps.put(pkgName, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001834 }
1835 ops.put(op.op, op);
1836 } else {
1837 Slog.w(TAG, "Unknown element under <pkg>: "
1838 + parser.getName());
1839 XmlUtils.skipCurrentTag(parser);
1840 }
1841 }
1842 }
1843
1844 void writeState() {
1845 synchronized (mFile) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001846 FileOutputStream stream;
1847 try {
1848 stream = mFile.startWrite();
1849 } catch (IOException e) {
1850 Slog.w(TAG, "Failed to write state: " + e);
1851 return;
1852 }
1853
Dianne Hackborne17b4452018-01-10 13:15:40 -08001854 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
1855
Dianne Hackborn35654b62013-01-14 17:38:02 -08001856 try {
1857 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001858 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001859 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001860 out.startTag(null, "app-ops");
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001861 out.attribute(null, "v", String.valueOf(CURRENT_VERSION));
Svet Ganov2af57082015-07-30 08:44:20 -07001862
1863 final int uidStateCount = mUidStates.size();
1864 for (int i = 0; i < uidStateCount; i++) {
1865 UidState uidState = mUidStates.valueAt(i);
1866 if (uidState.opModes != null && uidState.opModes.size() > 0) {
1867 out.startTag(null, "uid");
1868 out.attribute(null, "n", Integer.toString(uidState.uid));
1869 SparseIntArray uidOpModes = uidState.opModes;
1870 final int opCount = uidOpModes.size();
1871 for (int j = 0; j < opCount; j++) {
1872 final int op = uidOpModes.keyAt(j);
1873 final int mode = uidOpModes.valueAt(j);
1874 out.startTag(null, "op");
1875 out.attribute(null, "n", Integer.toString(op));
1876 out.attribute(null, "m", Integer.toString(mode));
1877 out.endTag(null, "op");
1878 }
1879 out.endTag(null, "uid");
1880 }
1881 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001882
1883 if (allOps != null) {
1884 String lastPkg = null;
1885 for (int i=0; i<allOps.size(); i++) {
1886 AppOpsManager.PackageOps pkg = allOps.get(i);
1887 if (!pkg.getPackageName().equals(lastPkg)) {
1888 if (lastPkg != null) {
1889 out.endTag(null, "pkg");
1890 }
1891 lastPkg = pkg.getPackageName();
1892 out.startTag(null, "pkg");
1893 out.attribute(null, "n", lastPkg);
1894 }
1895 out.startTag(null, "uid");
1896 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04001897 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001898 Ops ops = getOpsRawLocked(pkg.getUid(), pkg.getPackageName(),
1899 false /* edit */, false /* uidMismatchExpected */);
Jason Monk1c7c3192014-06-26 12:52:18 -04001900 // Should always be present as the list of PackageOps is generated
1901 // from Ops.
1902 if (ops != null) {
1903 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
1904 } else {
1905 out.attribute(null, "p", Boolean.toString(false));
1906 }
1907 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001908 List<AppOpsManager.OpEntry> ops = pkg.getOps();
1909 for (int j=0; j<ops.size(); j++) {
1910 AppOpsManager.OpEntry op = ops.get(j);
1911 out.startTag(null, "op");
1912 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07001913 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001914 out.attribute(null, "m", Integer.toString(op.getMode()));
1915 }
1916 long time = op.getTime();
1917 if (time != 0) {
1918 out.attribute(null, "t", Long.toString(time));
1919 }
1920 time = op.getRejectTime();
1921 if (time != 0) {
1922 out.attribute(null, "r", Long.toString(time));
1923 }
1924 int dur = op.getDuration();
1925 if (dur != 0) {
1926 out.attribute(null, "d", Integer.toString(dur));
1927 }
Svet Ganov99b60432015-06-27 13:15:22 -07001928 int proxyUid = op.getProxyUid();
1929 if (proxyUid != -1) {
1930 out.attribute(null, "pu", Integer.toString(proxyUid));
1931 }
1932 String proxyPackageName = op.getProxyPackageName();
1933 if (proxyPackageName != null) {
1934 out.attribute(null, "pp", proxyPackageName);
1935 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001936 out.endTag(null, "op");
1937 }
1938 out.endTag(null, "uid");
1939 }
1940 if (lastPkg != null) {
1941 out.endTag(null, "pkg");
1942 }
1943 }
1944
1945 out.endTag(null, "app-ops");
1946 out.endDocument();
1947 mFile.finishWrite(stream);
1948 } catch (IOException e) {
1949 Slog.w(TAG, "Failed to write state, restoring backup.", e);
1950 mFile.failWrite(stream);
1951 }
1952 }
1953 }
1954
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001955 static class Shell extends ShellCommand {
1956 final IAppOpsService mInterface;
1957 final AppOpsService mInternal;
1958
1959 int userId = UserHandle.USER_SYSTEM;
1960 String packageName;
1961 String opStr;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001962 String modeStr;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001963 int op;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001964 int mode;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001965 int packageUid;
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001966 int nonpackageUid;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05001967 final static Binder sBinder = new Binder();
1968 IBinder mToken;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001969
1970 Shell(IAppOpsService iface, AppOpsService internal) {
1971 mInterface = iface;
1972 mInternal = internal;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05001973 try {
1974 mToken = mInterface.getToken(sBinder);
1975 } catch (RemoteException e) {
1976 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001977 }
1978
1979 @Override
1980 public int onCommand(String cmd) {
1981 return onShellCommand(this, cmd);
1982 }
1983
1984 @Override
1985 public void onHelp() {
1986 PrintWriter pw = getOutPrintWriter();
1987 dumpCommandHelp(pw);
1988 }
1989
1990 private int strOpToOp(String op, PrintWriter err) {
1991 try {
1992 return AppOpsManager.strOpToOp(op);
1993 } catch (IllegalArgumentException e) {
1994 }
1995 try {
1996 return Integer.parseInt(op);
1997 } catch (NumberFormatException e) {
1998 }
1999 try {
2000 return AppOpsManager.strDebugOpToOp(op);
2001 } catch (IllegalArgumentException e) {
2002 err.println("Error: " + e.getMessage());
2003 return -1;
2004 }
2005 }
2006
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002007 int strModeToMode(String modeStr, PrintWriter err) {
2008 switch (modeStr) {
2009 case "allow":
2010 return AppOpsManager.MODE_ALLOWED;
2011 case "deny":
2012 return AppOpsManager.MODE_ERRORED;
2013 case "ignore":
2014 return AppOpsManager.MODE_IGNORED;
2015 case "default":
2016 return AppOpsManager.MODE_DEFAULT;
2017 }
2018 try {
2019 return Integer.parseInt(modeStr);
2020 } catch (NumberFormatException e) {
2021 }
2022 err.println("Error: Mode " + modeStr + " is not valid");
2023 return -1;
2024 }
2025
2026 int parseUserOpMode(int defMode, PrintWriter err) throws RemoteException {
2027 userId = UserHandle.USER_CURRENT;
2028 opStr = null;
2029 modeStr = null;
2030 for (String argument; (argument = getNextArg()) != null;) {
2031 if ("--user".equals(argument)) {
2032 userId = UserHandle.parseUserArg(getNextArgRequired());
2033 } else {
2034 if (opStr == null) {
2035 opStr = argument;
2036 } else if (modeStr == null) {
2037 modeStr = argument;
2038 break;
2039 }
2040 }
2041 }
2042 if (opStr == null) {
2043 err.println("Error: Operation not specified.");
2044 return -1;
2045 }
2046 op = strOpToOp(opStr, err);
2047 if (op < 0) {
2048 return -1;
2049 }
2050 if (modeStr != null) {
2051 if ((mode=strModeToMode(modeStr, err)) < 0) {
2052 return -1;
2053 }
2054 } else {
2055 mode = defMode;
2056 }
2057 return 0;
2058 }
2059
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002060 int parseUserPackageOp(boolean reqOp, PrintWriter err) throws RemoteException {
2061 userId = UserHandle.USER_CURRENT;
2062 packageName = null;
2063 opStr = null;
2064 for (String argument; (argument = getNextArg()) != null;) {
2065 if ("--user".equals(argument)) {
2066 userId = UserHandle.parseUserArg(getNextArgRequired());
2067 } else {
2068 if (packageName == null) {
2069 packageName = argument;
2070 } else if (opStr == null) {
2071 opStr = argument;
2072 break;
2073 }
2074 }
2075 }
2076 if (packageName == null) {
2077 err.println("Error: Package name not specified.");
2078 return -1;
2079 } else if (opStr == null && reqOp) {
2080 err.println("Error: Operation not specified.");
2081 return -1;
2082 }
2083 if (opStr != null) {
2084 op = strOpToOp(opStr, err);
2085 if (op < 0) {
2086 return -1;
2087 }
2088 } else {
2089 op = AppOpsManager.OP_NONE;
2090 }
2091 if (userId == UserHandle.USER_CURRENT) {
2092 userId = ActivityManager.getCurrentUser();
2093 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002094 nonpackageUid = -1;
2095 try {
2096 nonpackageUid = Integer.parseInt(packageName);
2097 } catch (NumberFormatException e) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002098 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002099 if (nonpackageUid == -1 && packageName.length() > 1 && packageName.charAt(0) == 'u'
2100 && packageName.indexOf('.') < 0) {
2101 int i = 1;
2102 while (i < packageName.length() && packageName.charAt(i) >= '0'
2103 && packageName.charAt(i) <= '9') {
2104 i++;
2105 }
2106 if (i > 1 && i < packageName.length()) {
2107 String userStr = packageName.substring(1, i);
2108 try {
2109 int user = Integer.parseInt(userStr);
2110 char type = packageName.charAt(i);
2111 i++;
2112 int startTypeVal = i;
2113 while (i < packageName.length() && packageName.charAt(i) >= '0'
2114 && packageName.charAt(i) <= '9') {
2115 i++;
2116 }
2117 if (i > startTypeVal) {
2118 String typeValStr = packageName.substring(startTypeVal, i);
2119 try {
2120 int typeVal = Integer.parseInt(typeValStr);
2121 if (type == 'a') {
2122 nonpackageUid = UserHandle.getUid(user,
2123 typeVal + Process.FIRST_APPLICATION_UID);
2124 } else if (type == 's') {
2125 nonpackageUid = UserHandle.getUid(user, typeVal);
2126 }
2127 } catch (NumberFormatException e) {
2128 }
2129 }
2130 } catch (NumberFormatException e) {
2131 }
2132 }
2133 }
2134 if (nonpackageUid != -1) {
2135 packageName = null;
2136 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08002137 packageUid = resolveUid(packageName);
2138 if (packageUid < 0) {
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002139 packageUid = AppGlobals.getPackageManager().getPackageUid(packageName,
2140 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
2141 }
2142 if (packageUid < 0) {
2143 err.println("Error: No UID for " + packageName + " in user " + userId);
2144 return -1;
2145 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002146 }
2147 return 0;
2148 }
2149 }
2150
2151 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002152 FileDescriptor err, String[] args, ShellCallback callback,
2153 ResultReceiver resultReceiver) {
2154 (new Shell(this, this)).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002155 }
2156
2157 static void dumpCommandHelp(PrintWriter pw) {
2158 pw.println("AppOps service (appops) commands:");
2159 pw.println(" help");
2160 pw.println(" Print this help text.");
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05002161 pw.println(" start [--user <USER_ID>] <PACKAGE | UID> <OP> ");
2162 pw.println(" Starts a given operation for a particular application.");
2163 pw.println(" stop [--user <USER_ID>] <PACKAGE | UID> <OP> ");
2164 pw.println(" Stops a given operation for a particular application.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002165 pw.println(" set [--user <USER_ID>] <PACKAGE | UID> <OP> <MODE>");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002166 pw.println(" Set the mode for a particular application and operation.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002167 pw.println(" get [--user <USER_ID>] <PACKAGE | UID> [<OP>]");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002168 pw.println(" Return the mode for a particular application and optional operation.");
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002169 pw.println(" query-op [--user <USER_ID>] <OP> [<MODE>]");
2170 pw.println(" Print all packages that currently have the given op in the given mode.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002171 pw.println(" reset [--user <USER_ID>] [<PACKAGE>]");
2172 pw.println(" Reset the given application or all applications to default modes.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002173 pw.println(" write-settings");
2174 pw.println(" Immediately write pending changes to storage.");
2175 pw.println(" read-settings");
2176 pw.println(" Read the last written settings, replacing current state in RAM.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002177 pw.println(" options:");
2178 pw.println(" <PACKAGE> an Android package name.");
2179 pw.println(" <OP> an AppOps operation.");
2180 pw.println(" <MODE> one of allow, ignore, deny, or default");
2181 pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
2182 pw.println(" specified, the current user is assumed.");
2183 }
2184
2185 static int onShellCommand(Shell shell, String cmd) {
2186 if (cmd == null) {
2187 return shell.handleDefaultCommands(cmd);
2188 }
2189 PrintWriter pw = shell.getOutPrintWriter();
2190 PrintWriter err = shell.getErrPrintWriter();
2191 try {
2192 switch (cmd) {
2193 case "set": {
2194 int res = shell.parseUserPackageOp(true, err);
2195 if (res < 0) {
2196 return res;
2197 }
2198 String modeStr = shell.getNextArg();
2199 if (modeStr == null) {
2200 err.println("Error: Mode not specified.");
2201 return -1;
2202 }
2203
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002204 final int mode = shell.strModeToMode(modeStr, err);
2205 if (mode < 0) {
2206 return -1;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002207 }
2208
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002209 if (shell.packageName != null) {
2210 shell.mInterface.setMode(shell.op, shell.packageUid, shell.packageName,
2211 mode);
2212 } else {
2213 shell.mInterface.setUidMode(shell.op, shell.nonpackageUid, mode);
2214 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002215 return 0;
2216 }
2217 case "get": {
2218 int res = shell.parseUserPackageOp(false, err);
2219 if (res < 0) {
2220 return res;
2221 }
2222
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002223 List<AppOpsManager.PackageOps> ops;
2224 if (shell.packageName != null) {
2225 ops = shell.mInterface.getOpsForPackage(
2226 shell.packageUid, shell.packageName,
2227 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
2228 } else {
2229 ops = shell.mInterface.getUidOps(
2230 shell.nonpackageUid,
2231 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
2232 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002233 if (ops == null || ops.size() <= 0) {
2234 pw.println("No operations.");
Svet Ganov82f09bc2018-01-12 22:08:40 -08002235 if (shell.op > AppOpsManager.OP_NONE && shell.op < AppOpsManager._NUM_OP) {
2236 pw.println("Default mode: " + AppOpsManager.modeToString(
2237 AppOpsManager.opToDefaultMode(shell.op)));
2238 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002239 return 0;
2240 }
2241 final long now = System.currentTimeMillis();
2242 for (int i=0; i<ops.size(); i++) {
2243 List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
2244 for (int j=0; j<entries.size(); j++) {
2245 AppOpsManager.OpEntry ent = entries.get(j);
2246 pw.print(AppOpsManager.opToName(ent.getOp()));
2247 pw.print(": ");
Svet Ganov82f09bc2018-01-12 22:08:40 -08002248 pw.print(AppOpsManager.modeToString(ent.getMode()));
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002249 if (ent.getTime() != 0) {
2250 pw.print("; time=");
2251 TimeUtils.formatDuration(now - ent.getTime(), pw);
2252 pw.print(" ago");
2253 }
2254 if (ent.getRejectTime() != 0) {
2255 pw.print("; rejectTime=");
2256 TimeUtils.formatDuration(now - ent.getRejectTime(), pw);
2257 pw.print(" ago");
2258 }
2259 if (ent.getDuration() == -1) {
2260 pw.print(" (running)");
2261 } else if (ent.getDuration() != 0) {
2262 pw.print("; duration=");
2263 TimeUtils.formatDuration(ent.getDuration(), pw);
2264 }
2265 pw.println();
2266 }
2267 }
2268 return 0;
2269 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002270 case "query-op": {
2271 int res = shell.parseUserOpMode(AppOpsManager.MODE_IGNORED, err);
2272 if (res < 0) {
2273 return res;
2274 }
2275 List<AppOpsManager.PackageOps> ops = shell.mInterface.getPackagesForOps(
2276 new int[] {shell.op});
2277 if (ops == null || ops.size() <= 0) {
2278 pw.println("No operations.");
2279 return 0;
2280 }
2281 for (int i=0; i<ops.size(); i++) {
2282 final AppOpsManager.PackageOps pkg = ops.get(i);
2283 boolean hasMatch = false;
2284 final List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
2285 for (int j=0; j<entries.size(); j++) {
2286 AppOpsManager.OpEntry ent = entries.get(j);
2287 if (ent.getOp() == shell.op && ent.getMode() == shell.mode) {
2288 hasMatch = true;
2289 break;
2290 }
2291 }
2292 if (hasMatch) {
2293 pw.println(pkg.getPackageName());
2294 }
2295 }
2296 return 0;
2297 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002298 case "reset": {
2299 String packageName = null;
2300 int userId = UserHandle.USER_CURRENT;
2301 for (String argument; (argument = shell.getNextArg()) != null;) {
2302 if ("--user".equals(argument)) {
2303 String userStr = shell.getNextArgRequired();
2304 userId = UserHandle.parseUserArg(userStr);
2305 } else {
2306 if (packageName == null) {
2307 packageName = argument;
2308 } else {
2309 err.println("Error: Unsupported argument: " + argument);
2310 return -1;
2311 }
2312 }
2313 }
2314
2315 if (userId == UserHandle.USER_CURRENT) {
2316 userId = ActivityManager.getCurrentUser();
2317 }
2318
2319 shell.mInterface.resetAllModes(userId, packageName);
2320 pw.print("Reset all modes for: ");
2321 if (userId == UserHandle.USER_ALL) {
2322 pw.print("all users");
2323 } else {
2324 pw.print("user "); pw.print(userId);
2325 }
2326 pw.print(", ");
2327 if (packageName == null) {
2328 pw.println("all packages");
2329 } else {
2330 pw.print("package "); pw.println(packageName);
2331 }
2332 return 0;
2333 }
2334 case "write-settings": {
2335 shell.mInternal.mContext.enforcePermission(
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -08002336 android.Manifest.permission.MANAGE_APP_OPS_MODES,
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002337 Binder.getCallingPid(), Binder.getCallingUid(), null);
2338 long token = Binder.clearCallingIdentity();
2339 try {
2340 synchronized (shell.mInternal) {
2341 shell.mInternal.mHandler.removeCallbacks(shell.mInternal.mWriteRunner);
2342 }
2343 shell.mInternal.writeState();
2344 pw.println("Current settings written.");
2345 } finally {
2346 Binder.restoreCallingIdentity(token);
2347 }
2348 return 0;
2349 }
2350 case "read-settings": {
2351 shell.mInternal.mContext.enforcePermission(
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -08002352 android.Manifest.permission.MANAGE_APP_OPS_MODES,
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002353 Binder.getCallingPid(), Binder.getCallingUid(), null);
2354 long token = Binder.clearCallingIdentity();
2355 try {
2356 shell.mInternal.readState();
2357 pw.println("Last settings read.");
2358 } finally {
2359 Binder.restoreCallingIdentity(token);
2360 }
2361 return 0;
2362 }
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05002363 case "start": {
2364 int res = shell.parseUserPackageOp(true, err);
2365 if (res < 0) {
2366 return res;
2367 }
2368
2369 if (shell.packageName != null) {
2370 shell.mInterface.startOperation(shell.mToken,
2371 shell.op, shell.packageUid, shell.packageName, true);
2372 } else {
2373 return -1;
2374 }
2375 return 0;
2376 }
2377 case "stop": {
2378 int res = shell.parseUserPackageOp(true, err);
2379 if (res < 0) {
2380 return res;
2381 }
2382
2383 if (shell.packageName != null) {
2384 shell.mInterface.finishOperation(shell.mToken,
2385 shell.op, shell.packageUid, shell.packageName);
2386 } else {
2387 return -1;
2388 }
2389 return 0;
2390 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002391 default:
2392 return shell.handleDefaultCommands(cmd);
2393 }
2394 } catch (RemoteException e) {
2395 pw.println("Remote exception: " + e);
2396 }
2397 return -1;
2398 }
2399
2400 private void dumpHelp(PrintWriter pw) {
2401 pw.println("AppOps service (appops) dump options:");
2402 pw.println(" none");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002403 }
2404
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002405 @Override
2406 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002407 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002408
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002409 if (args != null) {
2410 for (int i=0; i<args.length; i++) {
2411 String arg = args[i];
2412 if ("-h".equals(arg)) {
2413 dumpHelp(pw);
2414 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07002415 } else if ("-a".equals(arg)) {
2416 // dump all data
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002417 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
2418 pw.println("Unknown option: " + arg);
2419 return;
2420 } else {
2421 pw.println("Unknown command: " + arg);
2422 return;
2423 }
2424 }
2425 }
2426
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002427 synchronized (this) {
2428 pw.println("Current AppOps Service state:");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002429 final long now = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002430 boolean needSep = false;
2431 if (mOpModeWatchers.size() > 0) {
2432 needSep = true;
2433 pw.println(" Op mode watchers:");
2434 for (int i=0; i<mOpModeWatchers.size(); i++) {
2435 pw.print(" Op "); pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
2436 pw.println(":");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002437 ArraySet<ModeCallback> callbacks = mOpModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002438 for (int j=0; j<callbacks.size(); j++) {
2439 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08002440 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002441 }
2442 }
2443 }
2444 if (mPackageModeWatchers.size() > 0) {
2445 needSep = true;
2446 pw.println(" Package mode watchers:");
2447 for (int i=0; i<mPackageModeWatchers.size(); i++) {
2448 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
2449 pw.println(":");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002450 ArraySet<ModeCallback> callbacks = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002451 for (int j=0; j<callbacks.size(); j++) {
2452 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08002453 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002454 }
2455 }
2456 }
2457 if (mModeWatchers.size() > 0) {
2458 needSep = true;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002459 pw.println(" All op mode watchers:");
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002460 for (int i=0; i<mModeWatchers.size(); i++) {
2461 pw.print(" "); pw.print(mModeWatchers.keyAt(i));
2462 pw.print(" -> "); pw.println(mModeWatchers.valueAt(i));
2463 }
2464 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002465 if (mActiveWatchers.size() > 0) {
2466 needSep = true;
2467 pw.println(" All op active watchers:");
2468 for (int i = 0; i < mActiveWatchers.size(); i++) {
2469 final SparseArray<ActiveCallback> activeWatchers = mActiveWatchers.valueAt(i);
2470 if (activeWatchers.size() <= 0) {
2471 continue;
2472 }
2473 pw.print(" "); pw.print(mActiveWatchers.keyAt(i));
2474 pw.print(" -> [");
2475 final int opCount = activeWatchers.size();
2476 for (i = 0; i < opCount; i++) {
2477 pw.print(AppOpsManager.opToName(activeWatchers.keyAt(i)));
2478 if (i < opCount - 1) {
2479 pw.print(',');
2480 }
2481 }
2482 pw.print("]" ); pw.println(activeWatchers.valueAt(0));
2483 }
2484 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002485 if (mClients.size() > 0) {
2486 needSep = true;
2487 pw.println(" Clients:");
2488 for (int i=0; i<mClients.size(); i++) {
2489 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
2490 ClientState cs = mClients.valueAt(i);
2491 pw.print(" "); pw.println(cs);
Svet Ganovf7b47252018-02-26 11:11:27 -08002492 if (cs.mStartedOps.size() > 0) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002493 pw.println(" Started ops:");
2494 for (int j=0; j<cs.mStartedOps.size(); j++) {
2495 Op op = cs.mStartedOps.get(j);
2496 pw.print(" "); pw.print("uid="); pw.print(op.uid);
2497 pw.print(" pkg="); pw.print(op.packageName);
2498 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
2499 }
2500 }
2501 }
2502 }
John Spurlock1af30c72014-03-10 08:33:35 -04002503 if (mAudioRestrictions.size() > 0) {
2504 boolean printedHeader = false;
2505 for (int o=0; o<mAudioRestrictions.size(); o++) {
2506 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
2507 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
2508 for (int i=0; i<restrictions.size(); i++) {
2509 if (!printedHeader){
2510 pw.println(" Audio Restrictions:");
2511 printedHeader = true;
2512 needSep = true;
2513 }
John Spurlock7b414672014-07-18 13:02:39 -04002514 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04002515 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04002516 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04002517 Restriction r = restrictions.valueAt(i);
2518 pw.print(": mode="); pw.println(r.mode);
2519 if (!r.exceptionPackages.isEmpty()) {
2520 pw.println(" Exceptions:");
2521 for (int j=0; j<r.exceptionPackages.size(); j++) {
2522 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
2523 }
2524 }
2525 }
2526 }
2527 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002528 if (needSep) {
2529 pw.println();
2530 }
Svet Ganov2af57082015-07-30 08:44:20 -07002531 for (int i=0; i<mUidStates.size(); i++) {
2532 UidState uidState = mUidStates.valueAt(i);
2533
2534 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
Svet Ganovee438d42017-01-19 18:04:38 -08002535 needSep = true;
Svet Ganov2af57082015-07-30 08:44:20 -07002536
2537 SparseIntArray opModes = uidState.opModes;
2538 if (opModes != null) {
2539 final int opModeCount = opModes.size();
2540 for (int j = 0; j < opModeCount; j++) {
2541 final int code = opModes.keyAt(j);
2542 final int mode = opModes.valueAt(j);
2543 pw.print(" "); pw.print(AppOpsManager.opToName(code));
2544 pw.print(": mode="); pw.println(mode);
2545 }
2546 }
2547
2548 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
2549 if (pkgOps == null) {
2550 continue;
2551 }
2552
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002553 for (Ops ops : pkgOps.values()) {
2554 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
2555 for (int j=0; j<ops.size(); j++) {
2556 Op op = ops.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002557 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
2558 pw.print(": mode="); pw.print(op.mode);
2559 if (op.time != 0) {
2560 pw.print("; time="); TimeUtils.formatDuration(now-op.time, pw);
2561 pw.print(" ago");
2562 }
2563 if (op.rejectTime != 0) {
2564 pw.print("; rejectTime="); TimeUtils.formatDuration(now-op.rejectTime, pw);
2565 pw.print(" ago");
2566 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002567 if (op.duration == -1) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002568 pw.print(" (running)");
2569 } else if (op.duration != 0) {
2570 pw.print("; duration="); TimeUtils.formatDuration(op.duration, pw);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002571 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002572 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002573 }
2574 }
2575 }
Svet Ganovee438d42017-01-19 18:04:38 -08002576 if (needSep) {
2577 pw.println();
2578 }
2579
2580 final int userRestrictionCount = mOpUserRestrictions.size();
2581 for (int i = 0; i < userRestrictionCount; i++) {
2582 IBinder token = mOpUserRestrictions.keyAt(i);
2583 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
2584 pw.println(" User restrictions for token " + token + ":");
2585
2586 final int restrictionCount = restrictionState.perUserRestrictions != null
2587 ? restrictionState.perUserRestrictions.size() : 0;
2588 if (restrictionCount > 0) {
2589 pw.println(" Restricted ops:");
2590 for (int j = 0; j < restrictionCount; j++) {
2591 int userId = restrictionState.perUserRestrictions.keyAt(j);
2592 boolean[] restrictedOps = restrictionState.perUserRestrictions.valueAt(j);
2593 if (restrictedOps == null) {
2594 continue;
2595 }
2596 StringBuilder restrictedOpsValue = new StringBuilder();
2597 restrictedOpsValue.append("[");
2598 final int restrictedOpCount = restrictedOps.length;
2599 for (int k = 0; k < restrictedOpCount; k++) {
2600 if (restrictedOps[k]) {
2601 if (restrictedOpsValue.length() > 1) {
2602 restrictedOpsValue.append(", ");
2603 }
2604 restrictedOpsValue.append(AppOpsManager.opToName(k));
2605 }
2606 }
2607 restrictedOpsValue.append("]");
2608 pw.print(" "); pw.print("user: "); pw.print(userId);
2609 pw.print(" restricted ops: "); pw.println(restrictedOpsValue);
2610 }
2611 }
2612
2613 final int excludedPackageCount = restrictionState.perUserExcludedPackages != null
2614 ? restrictionState.perUserExcludedPackages.size() : 0;
2615 if (excludedPackageCount > 0) {
2616 pw.println(" Excluded packages:");
2617 for (int j = 0; j < excludedPackageCount; j++) {
2618 int userId = restrictionState.perUserExcludedPackages.keyAt(j);
2619 String[] packageNames = restrictionState.perUserExcludedPackages.valueAt(j);
2620 pw.print(" "); pw.print("user: "); pw.print(userId);
2621 pw.print(" packages: "); pw.println(Arrays.toString(packageNames));
2622 }
2623 }
2624 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002625 }
2626 }
John Spurlock1af30c72014-03-10 08:33:35 -04002627
2628 private static final class Restriction {
2629 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
2630 int mode;
2631 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
2632 }
Jason Monk62062992014-05-06 09:55:28 -04002633
2634 @Override
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002635 public void setUserRestrictions(Bundle restrictions, IBinder token, int userHandle) {
Jason Monk62062992014-05-06 09:55:28 -04002636 checkSystemUid("setUserRestrictions");
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002637 Preconditions.checkNotNull(restrictions);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002638 Preconditions.checkNotNull(token);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002639 for (int i = 0; i < AppOpsManager._NUM_OP; i++) {
Jason Monk62062992014-05-06 09:55:28 -04002640 String restriction = AppOpsManager.opToRestriction(i);
Suprabh Shukla64e0dcb2016-05-24 16:23:11 -07002641 if (restriction != null) {
2642 setUserRestrictionNoCheck(i, restrictions.getBoolean(restriction, false), token,
2643 userHandle, null);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002644 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002645 }
2646 }
2647
2648 @Override
Ruben Brunk29931bc2016-03-11 00:24:26 -08002649 public void setUserRestriction(int code, boolean restricted, IBinder token, int userHandle,
2650 String[] exceptionPackages) {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002651 if (Binder.getCallingPid() != Process.myPid()) {
2652 mContext.enforcePermission(Manifest.permission.MANAGE_APP_OPS_RESTRICTIONS,
2653 Binder.getCallingPid(), Binder.getCallingUid(), null);
2654 }
2655 if (userHandle != UserHandle.getCallingUserId()) {
2656 if (mContext.checkCallingOrSelfPermission(Manifest.permission
2657 .INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
2658 && mContext.checkCallingOrSelfPermission(Manifest.permission
2659 .INTERACT_ACROSS_USERS) != PackageManager.PERMISSION_GRANTED) {
2660 throw new SecurityException("Need INTERACT_ACROSS_USERS_FULL or"
2661 + " INTERACT_ACROSS_USERS to interact cross user ");
Jason Monk62062992014-05-06 09:55:28 -04002662 }
2663 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002664 verifyIncomingOp(code);
2665 Preconditions.checkNotNull(token);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002666 setUserRestrictionNoCheck(code, restricted, token, userHandle, exceptionPackages);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002667 }
2668
2669 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
Ruben Brunk29931bc2016-03-11 00:24:26 -08002670 int userHandle, String[] exceptionPackages) {
Svet Ganov442ed572016-08-17 17:29:43 -07002671 synchronized (AppOpsService.this) {
2672 ClientRestrictionState restrictionState = mOpUserRestrictions.get(token);
2673
2674 if (restrictionState == null) {
2675 try {
2676 restrictionState = new ClientRestrictionState(token);
2677 } catch (RemoteException e) {
2678 return;
2679 }
2680 mOpUserRestrictions.put(token, restrictionState);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002681 }
Svet Ganov442ed572016-08-17 17:29:43 -07002682
2683 if (restrictionState.setRestriction(code, restricted, exceptionPackages, userHandle)) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002684 mHandler.sendMessage(PooledLambda.obtainMessage(
2685 AppOpsService::notifyWatchersOfChange, this, code));
Svet Ganov442ed572016-08-17 17:29:43 -07002686 }
2687
2688 if (restrictionState.isDefault()) {
2689 mOpUserRestrictions.remove(token);
2690 restrictionState.destroy();
2691 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002692 }
Julia Reynoldsbb21c252016-04-05 16:01:49 -04002693 }
2694
2695 private void notifyWatchersOfChange(int code) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002696 final ArraySet<ModeCallback> clonedCallbacks;
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002697 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002698 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002699 if (callbacks == null) {
2700 return;
2701 }
Dianne Hackborn68d76552017-02-27 15:32:03 -08002702 clonedCallbacks = new ArraySet<>(callbacks);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002703 }
2704
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002705 notifyOpChanged(clonedCallbacks, code, -1, null);
Jason Monk62062992014-05-06 09:55:28 -04002706 }
2707
2708 @Override
2709 public void removeUser(int userHandle) throws RemoteException {
2710 checkSystemUid("removeUser");
Svet Ganov442ed572016-08-17 17:29:43 -07002711 synchronized (AppOpsService.this) {
2712 final int tokenCount = mOpUserRestrictions.size();
2713 for (int i = tokenCount - 1; i >= 0; i--) {
2714 ClientRestrictionState opRestrictions = mOpUserRestrictions.valueAt(i);
2715 opRestrictions.removeUser(userHandle);
2716 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002717 removeUidsForUserLocked(userHandle);
2718 }
2719 }
2720
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002721 @Override
2722 public boolean isOperationActive(int code, int uid, String packageName) {
Svet Ganovf7b47252018-02-26 11:11:27 -08002723 if (Binder.getCallingUid() != uid) {
2724 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
2725 != PackageManager.PERMISSION_GRANTED) {
2726 return false;
2727 }
2728 }
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002729 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002730 final String resolvedPackageName = resolvePackageName(uid, packageName);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002731 if (resolvedPackageName == null) {
2732 return false;
2733 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002734 synchronized (AppOpsService.this) {
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002735 for (int i = mClients.size() - 1; i >= 0; i--) {
2736 final ClientState client = mClients.valueAt(i);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002737 for (int j = client.mStartedOps.size() - 1; j >= 0; j--) {
2738 final Op op = client.mStartedOps.get(j);
2739 if (op.op == code && op.uid == uid) return true;
2740 }
2741 }
2742 }
2743 return false;
2744 }
2745
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002746 private void removeUidsForUserLocked(int userHandle) {
2747 for (int i = mUidStates.size() - 1; i >= 0; --i) {
2748 final int uid = mUidStates.keyAt(i);
2749 if (UserHandle.getUserId(uid) == userHandle) {
2750 mUidStates.removeAt(i);
2751 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002752 }
2753 }
2754
Jason Monk62062992014-05-06 09:55:28 -04002755 private void checkSystemUid(String function) {
2756 int uid = Binder.getCallingUid();
2757 if (uid != Process.SYSTEM_UID) {
2758 throw new SecurityException(function + " must by called by the system");
2759 }
2760 }
2761
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002762 private static String resolvePackageName(int uid, String packageName) {
Svet Ganov82f09bc2018-01-12 22:08:40 -08002763 if (uid == Process.ROOT_UID) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002764 return "root";
2765 } else if (uid == Process.SHELL_UID) {
2766 return "com.android.shell";
Svet Ganov82f09bc2018-01-12 22:08:40 -08002767 } else if (uid == Process.MEDIA_UID) {
2768 return "media";
2769 } else if (uid == Process.AUDIOSERVER_UID) {
2770 return "audioserver";
2771 } else if (uid == Process.CAMERASERVER_UID) {
2772 return "cameraserver";
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002773 } else if (uid == Process.SYSTEM_UID && packageName == null) {
2774 return "android";
2775 }
2776 return packageName;
2777 }
2778
Svet Ganov82f09bc2018-01-12 22:08:40 -08002779 private static int resolveUid(String packageName) {
2780 if (packageName == null) {
2781 return -1;
2782 }
2783 switch (packageName) {
2784 case "root":
2785 return Process.ROOT_UID;
2786 case "shell":
2787 return Process.SHELL_UID;
2788 case "media":
2789 return Process.MEDIA_UID;
2790 case "audioserver":
2791 return Process.AUDIOSERVER_UID;
2792 case "cameraserver":
2793 return Process.CAMERASERVER_UID;
2794 }
2795 return -1;
2796 }
2797
Svet Ganov2af57082015-07-30 08:44:20 -07002798 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07002799 String[] packageNames = null;
Svet Ganov2af57082015-07-30 08:44:20 -07002800 try {
riddle_hsu40b300f2015-11-23 13:22:03 +08002801 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -07002802 } catch (RemoteException e) {
2803 /* ignore - local call */
2804 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07002805 if (packageNames == null) {
2806 return EmptyArray.STRING;
2807 }
2808 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07002809 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002810
2811 private final class ClientRestrictionState implements DeathRecipient {
2812 private final IBinder token;
2813 SparseArray<boolean[]> perUserRestrictions;
2814 SparseArray<String[]> perUserExcludedPackages;
2815
2816 public ClientRestrictionState(IBinder token)
2817 throws RemoteException {
2818 token.linkToDeath(this, 0);
2819 this.token = token;
2820 }
2821
2822 public boolean setRestriction(int code, boolean restricted,
2823 String[] excludedPackages, int userId) {
2824 boolean changed = false;
2825
2826 if (perUserRestrictions == null && restricted) {
2827 perUserRestrictions = new SparseArray<>();
2828 }
2829
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002830 int[] users;
2831 if (userId == UserHandle.USER_ALL) {
2832 List<UserInfo> liveUsers = UserManager.get(mContext).getUsers(false);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002833
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002834 users = new int[liveUsers.size()];
2835 for (int i = 0; i < liveUsers.size(); i++) {
2836 users[i] = liveUsers.get(i).id;
2837 }
2838 } else {
2839 users = new int[]{userId};
2840 }
2841
2842 if (perUserRestrictions != null) {
2843 int numUsers = users.length;
2844
2845 for (int i = 0; i < numUsers; i++) {
2846 int thisUserId = users[i];
2847
2848 boolean[] userRestrictions = perUserRestrictions.get(thisUserId);
2849 if (userRestrictions == null && restricted) {
2850 userRestrictions = new boolean[AppOpsManager._NUM_OP];
2851 perUserRestrictions.put(thisUserId, userRestrictions);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002852 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002853 if (userRestrictions != null && userRestrictions[code] != restricted) {
2854 userRestrictions[code] = restricted;
2855 if (!restricted && isDefault(userRestrictions)) {
2856 perUserRestrictions.remove(thisUserId);
2857 userRestrictions = null;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002858 }
2859 changed = true;
2860 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002861
2862 if (userRestrictions != null) {
2863 final boolean noExcludedPackages = ArrayUtils.isEmpty(excludedPackages);
2864 if (perUserExcludedPackages == null && !noExcludedPackages) {
2865 perUserExcludedPackages = new SparseArray<>();
2866 }
2867 if (perUserExcludedPackages != null && !Arrays.equals(excludedPackages,
2868 perUserExcludedPackages.get(thisUserId))) {
2869 if (noExcludedPackages) {
2870 perUserExcludedPackages.remove(thisUserId);
2871 if (perUserExcludedPackages.size() <= 0) {
2872 perUserExcludedPackages = null;
2873 }
2874 } else {
2875 perUserExcludedPackages.put(thisUserId, excludedPackages);
2876 }
2877 changed = true;
2878 }
2879 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002880 }
2881 }
2882
2883 return changed;
2884 }
2885
2886 public boolean hasRestriction(int restriction, String packageName, int userId) {
2887 if (perUserRestrictions == null) {
2888 return false;
2889 }
2890 boolean[] restrictions = perUserRestrictions.get(userId);
2891 if (restrictions == null) {
2892 return false;
2893 }
2894 if (!restrictions[restriction]) {
2895 return false;
2896 }
2897 if (perUserExcludedPackages == null) {
2898 return true;
2899 }
2900 String[] perUserExclusions = perUserExcludedPackages.get(userId);
2901 if (perUserExclusions == null) {
2902 return true;
2903 }
2904 return !ArrayUtils.contains(perUserExclusions, packageName);
2905 }
2906
2907 public void removeUser(int userId) {
2908 if (perUserExcludedPackages != null) {
2909 perUserExcludedPackages.remove(userId);
2910 if (perUserExcludedPackages.size() <= 0) {
2911 perUserExcludedPackages = null;
2912 }
2913 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002914 if (perUserRestrictions != null) {
2915 perUserRestrictions.remove(userId);
2916 if (perUserRestrictions.size() <= 0) {
2917 perUserRestrictions = null;
2918 }
2919 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002920 }
2921
2922 public boolean isDefault() {
2923 return perUserRestrictions == null || perUserRestrictions.size() <= 0;
2924 }
2925
2926 @Override
2927 public void binderDied() {
2928 synchronized (AppOpsService.this) {
2929 mOpUserRestrictions.remove(token);
2930 if (perUserRestrictions == null) {
2931 return;
2932 }
2933 final int userCount = perUserRestrictions.size();
2934 for (int i = 0; i < userCount; i++) {
2935 final boolean[] restrictions = perUserRestrictions.valueAt(i);
2936 final int restrictionCount = restrictions.length;
2937 for (int j = 0; j < restrictionCount; j++) {
2938 if (restrictions[j]) {
2939 final int changedCode = j;
2940 mHandler.post(() -> notifyWatchersOfChange(changedCode));
2941 }
2942 }
2943 }
2944 destroy();
2945 }
2946 }
2947
2948 public void destroy() {
2949 token.unlinkToDeath(this, 0);
2950 }
2951
2952 private boolean isDefault(boolean[] array) {
2953 if (ArrayUtils.isEmpty(array)) {
2954 return true;
2955 }
2956 for (boolean value : array) {
2957 if (value) {
2958 return false;
2959 }
2960 }
2961 return true;
2962 }
2963 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002964}