blob: 53c9ecb81ad8a930d24e0d6447b08b65e76d2023 [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;
64
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -080065import com.android.internal.util.function.pooled.PooledLambda;
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()) {
613 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
614 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()) {
717 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
718 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 Hackborn607b4142013-08-02 18:10:10 -0700835 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
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);
1090 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001091 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1092 if (usageRestrictions == null) {
1093 usageRestrictions = new SparseArray<Restriction>();
1094 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -04001095 }
John Spurlock7b414672014-07-18 13:02:39 -04001096 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001097 if (mode != AppOpsManager.MODE_ALLOWED) {
1098 final Restriction r = new Restriction();
1099 r.mode = mode;
1100 if (exceptionPackages != null) {
1101 final int N = exceptionPackages.length;
1102 r.exceptionPackages = new ArraySet<String>(N);
1103 for (int i = 0; i < N; i++) {
1104 final String pkg = exceptionPackages[i];
1105 if (pkg != null) {
1106 r.exceptionPackages.add(pkg.trim());
1107 }
1108 }
1109 }
John Spurlock7b414672014-07-18 13:02:39 -04001110 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -04001111 }
1112 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001113
1114 mHandler.sendMessage(PooledLambda.obtainMessage(
1115 AppOpsService::notifyWatchersOfChange, this, code));
John Spurlock1af30c72014-03-10 08:33:35 -04001116 }
1117
1118 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001119 public int checkPackage(int uid, String packageName) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001120 Preconditions.checkNotNull(packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001121 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001122 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1123 true /* uidMismatchExpected */);
1124 if (ops != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001125 return AppOpsManager.MODE_ALLOWED;
1126 } else {
1127 return AppOpsManager.MODE_ERRORED;
1128 }
1129 }
1130 }
1131
1132 @Override
Svet Ganov99b60432015-06-27 13:15:22 -07001133 public int noteProxyOperation(int code, String proxyPackageName,
1134 int proxiedUid, String proxiedPackageName) {
1135 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001136 final int proxyUid = Binder.getCallingUid();
1137 String resolveProxyPackageName = resolvePackageName(proxyUid, proxyPackageName);
1138 if (resolveProxyPackageName == null) {
1139 return AppOpsManager.MODE_IGNORED;
1140 }
1141 final int proxyMode = noteOperationUnchecked(code, proxyUid,
1142 resolveProxyPackageName, -1, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001143 if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
1144 return proxyMode;
1145 }
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001146 String resolveProxiedPackageName = resolvePackageName(proxiedUid, proxiedPackageName);
1147 if (resolveProxiedPackageName == null) {
1148 return AppOpsManager.MODE_IGNORED;
1149 }
1150 return noteOperationUnchecked(code, proxiedUid, resolveProxiedPackageName,
1151 proxyMode, resolveProxyPackageName);
Svet Ganov99b60432015-06-27 13:15:22 -07001152 }
1153
1154 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001155 public int noteOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001156 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001157 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001158 String resolvedPackageName = resolvePackageName(uid, packageName);
1159 if (resolvedPackageName == null) {
1160 return AppOpsManager.MODE_IGNORED;
1161 }
1162 return noteOperationUnchecked(code, uid, resolvedPackageName, 0, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001163 }
1164
1165 private int noteOperationUnchecked(int code, int uid, String packageName,
1166 int proxyUid, String proxyPackageName) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001167 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001168 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1169 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001170 if (ops == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001171 if (DEBUG) Slog.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001172 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001173 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001174 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001175 Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07001176 if (isOpRestrictedLocked(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001177 return AppOpsManager.MODE_IGNORED;
1178 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001179 if (op.duration == -1) {
1180 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
1181 + " code " + code + " time=" + op.time + " duration=" + op.duration);
1182 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001183 op.duration = 0;
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001184 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001185 UidState uidState = ops.uidState;
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001186 // If there is a non-default per UID policy (we set UID op mode only if
1187 // non-default) it takes over, otherwise use the per package policy.
1188 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -07001189 final int uidMode = uidState.opModes.get(switchCode);
1190 if (uidMode != AppOpsManager.MODE_ALLOWED) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001191 if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + op.mode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07001192 + switchCode + " (" + code + ") uid " + uid + " package "
1193 + packageName);
1194 op.rejectTime = System.currentTimeMillis();
1195 return uidMode;
1196 }
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001197 } else {
1198 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
1199 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001200 if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + op.mode + " for code "
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001201 + switchCode + " (" + code + ") uid " + uid + " package "
1202 + packageName);
1203 op.rejectTime = System.currentTimeMillis();
1204 return switchOp.mode;
1205 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001206 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001207 if (DEBUG) Slog.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001208 + " package " + packageName);
1209 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001210 op.rejectTime = 0;
Svet Ganov99b60432015-06-27 13:15:22 -07001211 op.proxyUid = proxyUid;
1212 op.proxyPackageName = proxyPackageName;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001213 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001214 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001215 }
1216
1217 @Override
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001218 public void startWatchingActive(int[] ops, IAppOpsActiveCallback callback) {
Svet Ganovf7b47252018-02-26 11:11:27 -08001219 int watchedUid = -1;
1220 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
1221 != PackageManager.PERMISSION_GRANTED) {
1222 watchedUid = Binder.getCallingUid();
1223 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001224 if (ops != null) {
1225 Preconditions.checkArrayElementsInRange(ops, 0,
1226 AppOpsManager._NUM_OP - 1, "Invalid op code in: " + Arrays.toString(ops));
1227 }
1228 if (callback == null) {
1229 return;
1230 }
1231 synchronized (this) {
1232 SparseArray<ActiveCallback> callbacks = mActiveWatchers.get(callback.asBinder());
1233 if (callbacks == null) {
1234 callbacks = new SparseArray<>();
1235 mActiveWatchers.put(callback.asBinder(), callbacks);
1236 }
Svet Ganovf7b47252018-02-26 11:11:27 -08001237 final ActiveCallback activeCallback = new ActiveCallback(callback, watchedUid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001238 for (int op : ops) {
1239 callbacks.put(op, activeCallback);
1240 }
1241 }
1242 }
1243
1244 @Override
1245 public void stopWatchingActive(IAppOpsActiveCallback callback) {
1246 if (callback == null) {
1247 return;
1248 }
1249 synchronized (this) {
1250 final SparseArray<ActiveCallback> activeCallbacks =
1251 mActiveWatchers.remove(callback.asBinder());
1252 if (activeCallbacks == null) {
1253 return;
1254 }
1255 final int callbackCount = activeCallbacks.size();
1256 for (int i = 0; i < callbackCount; i++) {
1257 // Apps ops are mapped to a singleton
1258 if (i == 0) {
1259 activeCallbacks.valueAt(i).destroy();
1260 }
1261 }
1262 }
1263 }
1264
1265 @Override
Svet Ganovf7b47252018-02-26 11:11:27 -08001266 public int startOperation(IBinder token, int code, int uid, String packageName,
1267 boolean startIfModeDefault) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001268 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001269 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001270 String resolvedPackageName = resolvePackageName(uid, packageName);
1271 if (resolvedPackageName == null) {
1272 return AppOpsManager.MODE_IGNORED;
1273 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001274 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001275 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001276 Ops ops = getOpsRawLocked(uid, resolvedPackageName, true /* edit */,
1277 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001278 if (ops == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001279 if (DEBUG) Slog.d(TAG, "startOperation: no op for code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001280 + " package " + resolvedPackageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001281 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001282 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001283 Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07001284 if (isOpRestrictedLocked(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001285 return AppOpsManager.MODE_IGNORED;
1286 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001287 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001288 UidState uidState = ops.uidState;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001289 // If there is a non-default per UID policy (we set UID op mode only if
1290 // non-default) it takes over, otherwise use the per package policy.
1291 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -07001292 final int uidMode = uidState.opModes.get(switchCode);
Svet Ganovf7b47252018-02-26 11:11:27 -08001293 if (uidMode != AppOpsManager.MODE_ALLOWED
1294 && (!startIfModeDefault || uidMode != AppOpsManager.MODE_DEFAULT)) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001295 if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + op.mode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07001296 + switchCode + " (" + code + ") uid " + uid + " package "
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001297 + resolvedPackageName);
Svet Ganov2af57082015-07-30 08:44:20 -07001298 op.rejectTime = System.currentTimeMillis();
1299 return uidMode;
1300 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001301 } else {
1302 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
Svet Ganovf7b47252018-02-26 11:11:27 -08001303 if (switchOp.mode != AppOpsManager.MODE_ALLOWED
1304 && (!startIfModeDefault || switchOp.mode != AppOpsManager.MODE_DEFAULT)) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001305 if (DEBUG) Slog.d(TAG, "startOperation: reject #" + op.mode + " for code "
1306 + switchCode + " (" + code + ") uid " + uid + " package "
1307 + resolvedPackageName);
1308 op.rejectTime = System.currentTimeMillis();
1309 return switchOp.mode;
1310 }
Svet Ganov2af57082015-07-30 08:44:20 -07001311 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001312 if (DEBUG) Slog.d(TAG, "startOperation: allowing code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001313 + " package " + resolvedPackageName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001314 if (op.nesting == 0) {
1315 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001316 op.rejectTime = 0;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001317 op.duration = -1;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001318 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001319 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001320 op.nesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001321 if (client.mStartedOps != null) {
1322 client.mStartedOps.add(op);
1323 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001324 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001325
1326 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001327 }
1328
1329 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001330 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001331 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001332 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001333 String resolvedPackageName = resolvePackageName(uid, packageName);
1334 if (resolvedPackageName == null) {
1335 return;
1336 }
1337 if (!(token instanceof ClientState)) {
1338 return;
1339 }
1340 ClientState client = (ClientState) token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001341 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001342 Op op = getOpLocked(code, uid, resolvedPackageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001343 if (op == null) {
1344 return;
1345 }
Svet Ganovf7b47252018-02-26 11:11:27 -08001346 if (!client.mStartedOps.remove(op)) {
1347 throw new IllegalStateException("Operation not started: uid" + op.uid
1348 + " pkg=" + op.packageName + " op=" + op.op);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001349 }
Svet Ganova7a0db62018-02-27 20:08:01 -08001350 finishOperationLocked(op, /*finishNested*/ false);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001351 if (op.nesting <= 0) {
1352 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, false);
1353 }
1354 }
1355 }
1356
1357 private void scheduleOpActiveChangedIfNeededLocked(int code, int uid, String packageName,
1358 boolean active) {
1359 ArraySet<ActiveCallback> dispatchedCallbacks = null;
1360 final int callbackListCount = mActiveWatchers.size();
1361 for (int i = 0; i < callbackListCount; i++) {
1362 final SparseArray<ActiveCallback> callbacks = mActiveWatchers.valueAt(i);
1363 ActiveCallback callback = callbacks.get(code);
1364 if (callback != null) {
Svet Ganovf7b47252018-02-26 11:11:27 -08001365 if (callback.mUid >= 0 && callback.mUid != uid) {
1366 continue;
1367 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001368 if (dispatchedCallbacks == null) {
1369 dispatchedCallbacks = new ArraySet<>();
1370 }
1371 dispatchedCallbacks.add(callback);
1372 }
1373 }
1374 if (dispatchedCallbacks == null) {
1375 return;
1376 }
1377 mHandler.sendMessage(PooledLambda.obtainMessage(
1378 AppOpsService::notifyOpActiveChanged,
1379 this, dispatchedCallbacks, code, uid, packageName, active));
1380 }
1381
1382 private void notifyOpActiveChanged(ArraySet<ActiveCallback> callbacks,
1383 int code, int uid, String packageName, boolean active) {
1384 // There are components watching for mode changes such as window manager
1385 // and location manager which are in our process. The callbacks in these
1386 // components may require permissions our remote caller does not have.
1387 final long identity = Binder.clearCallingIdentity();
1388 try {
1389 final int callbackCount = callbacks.size();
1390 for (int i = 0; i < callbackCount; i++) {
1391 final ActiveCallback callback = callbacks.valueAt(i);
1392 try {
1393 callback.mCallback.opActiveChanged(code, uid, packageName, active);
1394 } catch (RemoteException e) {
1395 /* do nothing */
1396 }
1397 }
1398 } finally {
1399 Binder.restoreCallingIdentity(identity);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001400 }
1401 }
1402
Svet Ganovb9d71a62015-04-30 10:38:13 -07001403 @Override
1404 public int permissionToOpCode(String permission) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001405 if (permission == null) {
1406 return AppOpsManager.OP_NONE;
1407 }
Svet Ganovb9d71a62015-04-30 10:38:13 -07001408 return AppOpsManager.permissionToOpCode(permission);
1409 }
1410
Svet Ganova7a0db62018-02-27 20:08:01 -08001411 void finishOperationLocked(Op op, boolean finishNested) {
1412 if (op.nesting <= 1 || finishNested) {
1413 if (op.nesting == 1 || finishNested) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001414 op.duration = (int)(System.currentTimeMillis() - op.time);
1415 op.time += op.duration;
1416 } else {
1417 Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
1418 + op.packageName + " code " + op.op + " time=" + op.time
1419 + " duration=" + op.duration + " nesting=" + op.nesting);
1420 }
1421 op.nesting = 0;
1422 } else {
1423 op.nesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001424 }
1425 }
1426
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001427 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001428 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001429 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001430 }
1431 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001432 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001433 }
1434 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
1435 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001436 }
1437
Dianne Hackborn961321f2013-02-05 17:22:41 -08001438 private void verifyIncomingOp(int op) {
1439 if (op >= 0 && op < AppOpsManager._NUM_OP) {
1440 return;
1441 }
1442 throw new IllegalArgumentException("Bad operation #" + op);
1443 }
1444
Svet Ganov2af57082015-07-30 08:44:20 -07001445 private UidState getUidStateLocked(int uid, boolean edit) {
1446 UidState uidState = mUidStates.get(uid);
1447 if (uidState == null) {
1448 if (!edit) {
1449 return null;
1450 }
1451 uidState = new UidState(uid);
1452 mUidStates.put(uid, uidState);
1453 }
1454 return uidState;
1455 }
1456
Yohei Yukawaa965d652017-10-12 15:02:26 -07001457 private Ops getOpsRawLocked(int uid, String packageName, boolean edit,
1458 boolean uidMismatchExpected) {
Svet Ganov2af57082015-07-30 08:44:20 -07001459 UidState uidState = getUidStateLocked(uid, edit);
1460 if (uidState == null) {
1461 return null;
1462 }
1463
1464 if (uidState.pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001465 if (!edit) {
1466 return null;
1467 }
Svet Ganov2af57082015-07-30 08:44:20 -07001468 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001469 }
Svet Ganov2af57082015-07-30 08:44:20 -07001470
1471 Ops ops = uidState.pkgOps.get(packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001472 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001473 if (!edit) {
1474 return null;
1475 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001476 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001477 // This is the first time we have seen this package name under this uid,
1478 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -08001479 if (uid != 0) {
1480 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001481 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001482 int pkgUid = -1;
1483 try {
Jason Monk1c7c3192014-06-26 12:52:18 -04001484 ApplicationInfo appInfo = ActivityThread.getPackageManager()
Jeff Sharkeycd654482016-01-08 17:42:11 -07001485 .getApplicationInfo(packageName,
1486 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1487 UserHandle.getUserId(uid));
Jason Monk1c7c3192014-06-26 12:52:18 -04001488 if (appInfo != null) {
1489 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001490 isPrivileged = (appInfo.privateFlags
1491 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001492 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08001493 pkgUid = resolveUid(packageName);
1494 if (pkgUid >= 0) {
Chien-Yu Chen75cade02016-01-11 10:56:21 -08001495 isPrivileged = false;
Jason Monk1c7c3192014-06-26 12:52:18 -04001496 }
Dianne Hackborn713df152013-05-17 11:27:57 -07001497 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001498 } catch (RemoteException e) {
1499 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001500 }
1501 if (pkgUid != uid) {
1502 // Oops! The package name is not valid for the uid they are calling
1503 // under. Abort.
Yohei Yukawaa965d652017-10-12 15:02:26 -07001504 if (!uidMismatchExpected) {
1505 RuntimeException ex = new RuntimeException("here");
1506 ex.fillInStackTrace();
1507 Slog.w(TAG, "Bad call: specified package " + packageName
1508 + " under uid " + uid + " but it is really " + pkgUid, ex);
1509 }
Dianne Hackborn514074f2013-02-11 10:52:46 -08001510 return null;
1511 }
1512 } finally {
1513 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001514 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001515 }
Svet Ganov2af57082015-07-30 08:44:20 -07001516 ops = new Ops(packageName, uidState, isPrivileged);
1517 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001518 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08001519 return ops;
1520 }
1521
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001522 private void scheduleWriteLocked() {
1523 if (!mWriteScheduled) {
1524 mWriteScheduled = true;
1525 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
1526 }
1527 }
1528
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001529 private void scheduleFastWriteLocked() {
1530 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001531 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001532 mFastWriteScheduled = true;
1533 mHandler.removeCallbacks(mWriteRunner);
1534 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001535 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001536 }
1537
Dianne Hackborn72e39832013-01-18 18:36:09 -08001538 private Op getOpLocked(int code, int uid, String packageName, boolean edit) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001539 Ops ops = getOpsRawLocked(uid, packageName, edit,
1540 false /* uidMismatchExpected */);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001541 if (ops == null) {
1542 return null;
1543 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001544 return getOpLocked(ops, code, edit);
1545 }
1546
1547 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001548 Op op = ops.get(code);
1549 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001550 if (!edit) {
1551 return null;
1552 }
Svet Ganov2af57082015-07-30 08:44:20 -07001553 op = new Op(ops.uidState.uid, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001554 ops.put(code, op);
1555 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001556 if (edit) {
1557 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001558 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001559 return op;
1560 }
1561
Svet Ganov442ed572016-08-17 17:29:43 -07001562 private boolean isOpRestrictedLocked(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04001563 int userHandle = UserHandle.getUserId(uid);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001564 final int restrictionSetCount = mOpUserRestrictions.size();
Ruben Brunk29931bc2016-03-11 00:24:26 -08001565
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001566 for (int i = 0; i < restrictionSetCount; i++) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08001567 // For each client, check that the given op is not restricted, or that the given
1568 // package is exempt from the restriction.
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07001569 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07001570 if (restrictionState.hasRestriction(code, packageName, userHandle)) {
1571 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
1572 // If we are the system, bypass user restrictions for certain codes
1573 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001574 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1575 false /* uidMismatchExpected */);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07001576 if ((ops != null) && ops.isPrivileged) {
1577 return false;
1578 }
Ruben Brunk32f0fa42016-03-11 19:07:07 -08001579 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08001580 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001581 return true;
Jason Monk1c7c3192014-06-26 12:52:18 -04001582 }
Jason Monk62062992014-05-06 09:55:28 -04001583 }
1584 return false;
1585 }
1586
Dianne Hackborn35654b62013-01-14 17:38:02 -08001587 void readState() {
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001588 int oldVersion = NO_VERSION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001589 synchronized (mFile) {
1590 synchronized (this) {
1591 FileInputStream stream;
1592 try {
1593 stream = mFile.openRead();
1594 } catch (FileNotFoundException e) {
1595 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
1596 return;
1597 }
1598 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001599 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001600 try {
1601 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001602 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001603 int type;
1604 while ((type = parser.next()) != XmlPullParser.START_TAG
1605 && type != XmlPullParser.END_DOCUMENT) {
1606 ;
1607 }
1608
1609 if (type != XmlPullParser.START_TAG) {
1610 throw new IllegalStateException("no start tag found");
1611 }
1612
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001613 final String versionString = parser.getAttributeValue(null, "v");
1614 if (versionString != null) {
1615 oldVersion = Integer.parseInt(versionString);
1616 }
1617
Dianne Hackborn35654b62013-01-14 17:38:02 -08001618 int outerDepth = parser.getDepth();
1619 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1620 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1621 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1622 continue;
1623 }
1624
1625 String tagName = parser.getName();
1626 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001627 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07001628 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07001629 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001630 } else {
1631 Slog.w(TAG, "Unknown element under <app-ops>: "
1632 + parser.getName());
1633 XmlUtils.skipCurrentTag(parser);
1634 }
1635 }
1636 success = true;
1637 } catch (IllegalStateException e) {
1638 Slog.w(TAG, "Failed parsing " + e);
1639 } catch (NullPointerException e) {
1640 Slog.w(TAG, "Failed parsing " + e);
1641 } catch (NumberFormatException e) {
1642 Slog.w(TAG, "Failed parsing " + e);
1643 } catch (XmlPullParserException e) {
1644 Slog.w(TAG, "Failed parsing " + e);
1645 } catch (IOException e) {
1646 Slog.w(TAG, "Failed parsing " + e);
1647 } catch (IndexOutOfBoundsException e) {
1648 Slog.w(TAG, "Failed parsing " + e);
1649 } finally {
1650 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07001651 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001652 }
1653 try {
1654 stream.close();
1655 } catch (IOException e) {
1656 }
1657 }
1658 }
1659 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001660 synchronized (this) {
1661 upgradeLocked(oldVersion);
1662 }
1663 }
1664
1665 private void upgradeRunAnyInBackgroundLocked() {
1666 for (int i = 0; i < mUidStates.size(); i++) {
1667 final UidState uidState = mUidStates.valueAt(i);
1668 if (uidState == null) {
1669 continue;
1670 }
1671 if (uidState.opModes != null) {
1672 final int idx = uidState.opModes.indexOfKey(AppOpsManager.OP_RUN_IN_BACKGROUND);
1673 if (idx >= 0) {
1674 uidState.opModes.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND,
1675 uidState.opModes.valueAt(idx));
1676 }
1677 }
1678 if (uidState.pkgOps == null) {
1679 continue;
1680 }
1681 for (int j = 0; j < uidState.pkgOps.size(); j++) {
1682 Ops ops = uidState.pkgOps.valueAt(j);
1683 if (ops != null) {
1684 final Op op = ops.get(AppOpsManager.OP_RUN_IN_BACKGROUND);
1685 if (op != null && op.mode != AppOpsManager.opToDefaultMode(op.op)) {
1686 final Op copy = new Op(op.uid, op.packageName,
1687 AppOpsManager.OP_RUN_ANY_IN_BACKGROUND);
1688 copy.mode = op.mode;
1689 ops.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, copy);
1690 }
1691 }
1692 }
1693 }
1694 }
1695
1696 private void upgradeLocked(int oldVersion) {
1697 if (oldVersion >= CURRENT_VERSION) {
1698 return;
1699 }
1700 Slog.d(TAG, "Upgrading app-ops xml from version " + oldVersion + " to " + CURRENT_VERSION);
1701 switch (oldVersion) {
1702 case NO_VERSION:
1703 upgradeRunAnyInBackgroundLocked();
1704 // fall through
1705 case 1:
1706 // for future upgrades
1707 }
1708 scheduleFastWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001709 }
1710
Svet Ganov2af57082015-07-30 08:44:20 -07001711 void readUidOps(XmlPullParser parser) throws NumberFormatException,
1712 XmlPullParserException, IOException {
1713 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
1714 int outerDepth = parser.getDepth();
1715 int type;
1716 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1717 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1718 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1719 continue;
1720 }
1721
1722 String tagName = parser.getName();
1723 if (tagName.equals("op")) {
1724 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
1725 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
1726 UidState uidState = getUidStateLocked(uid, true);
1727 if (uidState.opModes == null) {
1728 uidState.opModes = new SparseIntArray();
1729 }
1730 uidState.opModes.put(code, mode);
1731 } else {
1732 Slog.w(TAG, "Unknown element under <uid-ops>: "
1733 + parser.getName());
1734 XmlUtils.skipCurrentTag(parser);
1735 }
1736 }
1737 }
1738
Dave Burke0997c5bd2013-08-02 20:25:02 +00001739 void readPackage(XmlPullParser parser) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001740 XmlPullParserException, IOException {
1741 String pkgName = parser.getAttributeValue(null, "n");
1742 int outerDepth = parser.getDepth();
1743 int type;
1744 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1745 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1746 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1747 continue;
1748 }
1749
1750 String tagName = parser.getName();
1751 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001752 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001753 } else {
1754 Slog.w(TAG, "Unknown element under <pkg>: "
1755 + parser.getName());
1756 XmlUtils.skipCurrentTag(parser);
1757 }
1758 }
1759 }
1760
Dave Burke0997c5bd2013-08-02 20:25:02 +00001761 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001762 XmlPullParserException, IOException {
1763 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Jason Monk1c7c3192014-06-26 12:52:18 -04001764 String isPrivilegedString = parser.getAttributeValue(null, "p");
1765 boolean isPrivileged = false;
1766 if (isPrivilegedString == null) {
1767 try {
1768 IPackageManager packageManager = ActivityThread.getPackageManager();
1769 if (packageManager != null) {
1770 ApplicationInfo appInfo = ActivityThread.getPackageManager()
1771 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
1772 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001773 isPrivileged = (appInfo.privateFlags
1774 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001775 }
1776 } else {
1777 // Could not load data, don't add to cache so it will be loaded later.
1778 return;
1779 }
1780 } catch (RemoteException e) {
1781 Slog.w(TAG, "Could not contact PackageManager", e);
1782 }
1783 } else {
1784 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
1785 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001786 int outerDepth = parser.getDepth();
1787 int type;
1788 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1789 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1790 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1791 continue;
1792 }
1793
1794 String tagName = parser.getName();
1795 if (tagName.equals("op")) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001796 Op op = new Op(uid, pkgName, Integer.parseInt(parser.getAttributeValue(null, "n")));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001797 String mode = parser.getAttributeValue(null, "m");
1798 if (mode != null) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001799 op.mode = Integer.parseInt(mode);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001800 }
1801 String time = parser.getAttributeValue(null, "t");
1802 if (time != null) {
1803 op.time = Long.parseLong(time);
1804 }
1805 time = parser.getAttributeValue(null, "r");
1806 if (time != null) {
1807 op.rejectTime = Long.parseLong(time);
1808 }
1809 String dur = parser.getAttributeValue(null, "d");
1810 if (dur != null) {
1811 op.duration = Integer.parseInt(dur);
1812 }
Svet Ganov99b60432015-06-27 13:15:22 -07001813 String proxyUid = parser.getAttributeValue(null, "pu");
1814 if (proxyUid != null) {
1815 op.proxyUid = Integer.parseInt(proxyUid);
1816 }
1817 String proxyPackageName = parser.getAttributeValue(null, "pp");
1818 if (proxyPackageName != null) {
1819 op.proxyPackageName = proxyPackageName;
1820 }
Svet Ganov2af57082015-07-30 08:44:20 -07001821
1822 UidState uidState = getUidStateLocked(uid, true);
1823 if (uidState.pkgOps == null) {
1824 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001825 }
Svet Ganov2af57082015-07-30 08:44:20 -07001826
1827 Ops ops = uidState.pkgOps.get(pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001828 if (ops == null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001829 ops = new Ops(pkgName, uidState, isPrivileged);
1830 uidState.pkgOps.put(pkgName, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001831 }
1832 ops.put(op.op, op);
1833 } else {
1834 Slog.w(TAG, "Unknown element under <pkg>: "
1835 + parser.getName());
1836 XmlUtils.skipCurrentTag(parser);
1837 }
1838 }
1839 }
1840
1841 void writeState() {
1842 synchronized (mFile) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001843 FileOutputStream stream;
1844 try {
1845 stream = mFile.startWrite();
1846 } catch (IOException e) {
1847 Slog.w(TAG, "Failed to write state: " + e);
1848 return;
1849 }
1850
Dianne Hackborne17b4452018-01-10 13:15:40 -08001851 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
1852
Dianne Hackborn35654b62013-01-14 17:38:02 -08001853 try {
1854 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001855 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001856 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001857 out.startTag(null, "app-ops");
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001858 out.attribute(null, "v", String.valueOf(CURRENT_VERSION));
Svet Ganov2af57082015-07-30 08:44:20 -07001859
1860 final int uidStateCount = mUidStates.size();
1861 for (int i = 0; i < uidStateCount; i++) {
1862 UidState uidState = mUidStates.valueAt(i);
1863 if (uidState.opModes != null && uidState.opModes.size() > 0) {
1864 out.startTag(null, "uid");
1865 out.attribute(null, "n", Integer.toString(uidState.uid));
1866 SparseIntArray uidOpModes = uidState.opModes;
1867 final int opCount = uidOpModes.size();
1868 for (int j = 0; j < opCount; j++) {
1869 final int op = uidOpModes.keyAt(j);
1870 final int mode = uidOpModes.valueAt(j);
1871 out.startTag(null, "op");
1872 out.attribute(null, "n", Integer.toString(op));
1873 out.attribute(null, "m", Integer.toString(mode));
1874 out.endTag(null, "op");
1875 }
1876 out.endTag(null, "uid");
1877 }
1878 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001879
1880 if (allOps != null) {
1881 String lastPkg = null;
1882 for (int i=0; i<allOps.size(); i++) {
1883 AppOpsManager.PackageOps pkg = allOps.get(i);
1884 if (!pkg.getPackageName().equals(lastPkg)) {
1885 if (lastPkg != null) {
1886 out.endTag(null, "pkg");
1887 }
1888 lastPkg = pkg.getPackageName();
1889 out.startTag(null, "pkg");
1890 out.attribute(null, "n", lastPkg);
1891 }
1892 out.startTag(null, "uid");
1893 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04001894 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001895 Ops ops = getOpsRawLocked(pkg.getUid(), pkg.getPackageName(),
1896 false /* edit */, false /* uidMismatchExpected */);
Jason Monk1c7c3192014-06-26 12:52:18 -04001897 // Should always be present as the list of PackageOps is generated
1898 // from Ops.
1899 if (ops != null) {
1900 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
1901 } else {
1902 out.attribute(null, "p", Boolean.toString(false));
1903 }
1904 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001905 List<AppOpsManager.OpEntry> ops = pkg.getOps();
1906 for (int j=0; j<ops.size(); j++) {
1907 AppOpsManager.OpEntry op = ops.get(j);
1908 out.startTag(null, "op");
1909 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07001910 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001911 out.attribute(null, "m", Integer.toString(op.getMode()));
1912 }
1913 long time = op.getTime();
1914 if (time != 0) {
1915 out.attribute(null, "t", Long.toString(time));
1916 }
1917 time = op.getRejectTime();
1918 if (time != 0) {
1919 out.attribute(null, "r", Long.toString(time));
1920 }
1921 int dur = op.getDuration();
1922 if (dur != 0) {
1923 out.attribute(null, "d", Integer.toString(dur));
1924 }
Svet Ganov99b60432015-06-27 13:15:22 -07001925 int proxyUid = op.getProxyUid();
1926 if (proxyUid != -1) {
1927 out.attribute(null, "pu", Integer.toString(proxyUid));
1928 }
1929 String proxyPackageName = op.getProxyPackageName();
1930 if (proxyPackageName != null) {
1931 out.attribute(null, "pp", proxyPackageName);
1932 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001933 out.endTag(null, "op");
1934 }
1935 out.endTag(null, "uid");
1936 }
1937 if (lastPkg != null) {
1938 out.endTag(null, "pkg");
1939 }
1940 }
1941
1942 out.endTag(null, "app-ops");
1943 out.endDocument();
1944 mFile.finishWrite(stream);
1945 } catch (IOException e) {
1946 Slog.w(TAG, "Failed to write state, restoring backup.", e);
1947 mFile.failWrite(stream);
1948 }
1949 }
1950 }
1951
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001952 static class Shell extends ShellCommand {
1953 final IAppOpsService mInterface;
1954 final AppOpsService mInternal;
1955
1956 int userId = UserHandle.USER_SYSTEM;
1957 String packageName;
1958 String opStr;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001959 String modeStr;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001960 int op;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001961 int mode;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001962 int packageUid;
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001963 int nonpackageUid;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001964
1965 Shell(IAppOpsService iface, AppOpsService internal) {
1966 mInterface = iface;
1967 mInternal = internal;
1968 }
1969
1970 @Override
1971 public int onCommand(String cmd) {
1972 return onShellCommand(this, cmd);
1973 }
1974
1975 @Override
1976 public void onHelp() {
1977 PrintWriter pw = getOutPrintWriter();
1978 dumpCommandHelp(pw);
1979 }
1980
1981 private int strOpToOp(String op, PrintWriter err) {
1982 try {
1983 return AppOpsManager.strOpToOp(op);
1984 } catch (IllegalArgumentException e) {
1985 }
1986 try {
1987 return Integer.parseInt(op);
1988 } catch (NumberFormatException e) {
1989 }
1990 try {
1991 return AppOpsManager.strDebugOpToOp(op);
1992 } catch (IllegalArgumentException e) {
1993 err.println("Error: " + e.getMessage());
1994 return -1;
1995 }
1996 }
1997
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001998 int strModeToMode(String modeStr, PrintWriter err) {
1999 switch (modeStr) {
2000 case "allow":
2001 return AppOpsManager.MODE_ALLOWED;
2002 case "deny":
2003 return AppOpsManager.MODE_ERRORED;
2004 case "ignore":
2005 return AppOpsManager.MODE_IGNORED;
2006 case "default":
2007 return AppOpsManager.MODE_DEFAULT;
2008 }
2009 try {
2010 return Integer.parseInt(modeStr);
2011 } catch (NumberFormatException e) {
2012 }
2013 err.println("Error: Mode " + modeStr + " is not valid");
2014 return -1;
2015 }
2016
2017 int parseUserOpMode(int defMode, PrintWriter err) throws RemoteException {
2018 userId = UserHandle.USER_CURRENT;
2019 opStr = null;
2020 modeStr = null;
2021 for (String argument; (argument = getNextArg()) != null;) {
2022 if ("--user".equals(argument)) {
2023 userId = UserHandle.parseUserArg(getNextArgRequired());
2024 } else {
2025 if (opStr == null) {
2026 opStr = argument;
2027 } else if (modeStr == null) {
2028 modeStr = argument;
2029 break;
2030 }
2031 }
2032 }
2033 if (opStr == null) {
2034 err.println("Error: Operation not specified.");
2035 return -1;
2036 }
2037 op = strOpToOp(opStr, err);
2038 if (op < 0) {
2039 return -1;
2040 }
2041 if (modeStr != null) {
2042 if ((mode=strModeToMode(modeStr, err)) < 0) {
2043 return -1;
2044 }
2045 } else {
2046 mode = defMode;
2047 }
2048 return 0;
2049 }
2050
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002051 int parseUserPackageOp(boolean reqOp, PrintWriter err) throws RemoteException {
2052 userId = UserHandle.USER_CURRENT;
2053 packageName = null;
2054 opStr = null;
2055 for (String argument; (argument = getNextArg()) != null;) {
2056 if ("--user".equals(argument)) {
2057 userId = UserHandle.parseUserArg(getNextArgRequired());
2058 } else {
2059 if (packageName == null) {
2060 packageName = argument;
2061 } else if (opStr == null) {
2062 opStr = argument;
2063 break;
2064 }
2065 }
2066 }
2067 if (packageName == null) {
2068 err.println("Error: Package name not specified.");
2069 return -1;
2070 } else if (opStr == null && reqOp) {
2071 err.println("Error: Operation not specified.");
2072 return -1;
2073 }
2074 if (opStr != null) {
2075 op = strOpToOp(opStr, err);
2076 if (op < 0) {
2077 return -1;
2078 }
2079 } else {
2080 op = AppOpsManager.OP_NONE;
2081 }
2082 if (userId == UserHandle.USER_CURRENT) {
2083 userId = ActivityManager.getCurrentUser();
2084 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002085 nonpackageUid = -1;
2086 try {
2087 nonpackageUid = Integer.parseInt(packageName);
2088 } catch (NumberFormatException e) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002089 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002090 if (nonpackageUid == -1 && packageName.length() > 1 && packageName.charAt(0) == 'u'
2091 && packageName.indexOf('.') < 0) {
2092 int i = 1;
2093 while (i < packageName.length() && packageName.charAt(i) >= '0'
2094 && packageName.charAt(i) <= '9') {
2095 i++;
2096 }
2097 if (i > 1 && i < packageName.length()) {
2098 String userStr = packageName.substring(1, i);
2099 try {
2100 int user = Integer.parseInt(userStr);
2101 char type = packageName.charAt(i);
2102 i++;
2103 int startTypeVal = i;
2104 while (i < packageName.length() && packageName.charAt(i) >= '0'
2105 && packageName.charAt(i) <= '9') {
2106 i++;
2107 }
2108 if (i > startTypeVal) {
2109 String typeValStr = packageName.substring(startTypeVal, i);
2110 try {
2111 int typeVal = Integer.parseInt(typeValStr);
2112 if (type == 'a') {
2113 nonpackageUid = UserHandle.getUid(user,
2114 typeVal + Process.FIRST_APPLICATION_UID);
2115 } else if (type == 's') {
2116 nonpackageUid = UserHandle.getUid(user, typeVal);
2117 }
2118 } catch (NumberFormatException e) {
2119 }
2120 }
2121 } catch (NumberFormatException e) {
2122 }
2123 }
2124 }
2125 if (nonpackageUid != -1) {
2126 packageName = null;
2127 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08002128 packageUid = resolveUid(packageName);
2129 if (packageUid < 0) {
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002130 packageUid = AppGlobals.getPackageManager().getPackageUid(packageName,
2131 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
2132 }
2133 if (packageUid < 0) {
2134 err.println("Error: No UID for " + packageName + " in user " + userId);
2135 return -1;
2136 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002137 }
2138 return 0;
2139 }
2140 }
2141
2142 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002143 FileDescriptor err, String[] args, ShellCallback callback,
2144 ResultReceiver resultReceiver) {
2145 (new Shell(this, this)).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002146 }
2147
2148 static void dumpCommandHelp(PrintWriter pw) {
2149 pw.println("AppOps service (appops) commands:");
2150 pw.println(" help");
2151 pw.println(" Print this help text.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002152 pw.println(" set [--user <USER_ID>] <PACKAGE | UID> <OP> <MODE>");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002153 pw.println(" Set the mode for a particular application and operation.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002154 pw.println(" get [--user <USER_ID>] <PACKAGE | UID> [<OP>]");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002155 pw.println(" Return the mode for a particular application and optional operation.");
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002156 pw.println(" query-op [--user <USER_ID>] <OP> [<MODE>]");
2157 pw.println(" Print all packages that currently have the given op in the given mode.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002158 pw.println(" reset [--user <USER_ID>] [<PACKAGE>]");
2159 pw.println(" Reset the given application or all applications to default modes.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002160 pw.println(" write-settings");
2161 pw.println(" Immediately write pending changes to storage.");
2162 pw.println(" read-settings");
2163 pw.println(" Read the last written settings, replacing current state in RAM.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002164 pw.println(" options:");
2165 pw.println(" <PACKAGE> an Android package name.");
2166 pw.println(" <OP> an AppOps operation.");
2167 pw.println(" <MODE> one of allow, ignore, deny, or default");
2168 pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
2169 pw.println(" specified, the current user is assumed.");
2170 }
2171
2172 static int onShellCommand(Shell shell, String cmd) {
2173 if (cmd == null) {
2174 return shell.handleDefaultCommands(cmd);
2175 }
2176 PrintWriter pw = shell.getOutPrintWriter();
2177 PrintWriter err = shell.getErrPrintWriter();
2178 try {
2179 switch (cmd) {
2180 case "set": {
2181 int res = shell.parseUserPackageOp(true, err);
2182 if (res < 0) {
2183 return res;
2184 }
2185 String modeStr = shell.getNextArg();
2186 if (modeStr == null) {
2187 err.println("Error: Mode not specified.");
2188 return -1;
2189 }
2190
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002191 final int mode = shell.strModeToMode(modeStr, err);
2192 if (mode < 0) {
2193 return -1;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002194 }
2195
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002196 if (shell.packageName != null) {
2197 shell.mInterface.setMode(shell.op, shell.packageUid, shell.packageName,
2198 mode);
2199 } else {
2200 shell.mInterface.setUidMode(shell.op, shell.nonpackageUid, mode);
2201 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002202 return 0;
2203 }
2204 case "get": {
2205 int res = shell.parseUserPackageOp(false, err);
2206 if (res < 0) {
2207 return res;
2208 }
2209
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002210 List<AppOpsManager.PackageOps> ops;
2211 if (shell.packageName != null) {
2212 ops = shell.mInterface.getOpsForPackage(
2213 shell.packageUid, shell.packageName,
2214 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
2215 } else {
2216 ops = shell.mInterface.getUidOps(
2217 shell.nonpackageUid,
2218 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
2219 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002220 if (ops == null || ops.size() <= 0) {
2221 pw.println("No operations.");
Svet Ganov82f09bc2018-01-12 22:08:40 -08002222 if (shell.op > AppOpsManager.OP_NONE && shell.op < AppOpsManager._NUM_OP) {
2223 pw.println("Default mode: " + AppOpsManager.modeToString(
2224 AppOpsManager.opToDefaultMode(shell.op)));
2225 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002226 return 0;
2227 }
2228 final long now = System.currentTimeMillis();
2229 for (int i=0; i<ops.size(); i++) {
2230 List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
2231 for (int j=0; j<entries.size(); j++) {
2232 AppOpsManager.OpEntry ent = entries.get(j);
2233 pw.print(AppOpsManager.opToName(ent.getOp()));
2234 pw.print(": ");
Svet Ganov82f09bc2018-01-12 22:08:40 -08002235 pw.print(AppOpsManager.modeToString(ent.getMode()));
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002236 if (ent.getTime() != 0) {
2237 pw.print("; time=");
2238 TimeUtils.formatDuration(now - ent.getTime(), pw);
2239 pw.print(" ago");
2240 }
2241 if (ent.getRejectTime() != 0) {
2242 pw.print("; rejectTime=");
2243 TimeUtils.formatDuration(now - ent.getRejectTime(), pw);
2244 pw.print(" ago");
2245 }
2246 if (ent.getDuration() == -1) {
2247 pw.print(" (running)");
2248 } else if (ent.getDuration() != 0) {
2249 pw.print("; duration=");
2250 TimeUtils.formatDuration(ent.getDuration(), pw);
2251 }
2252 pw.println();
2253 }
2254 }
2255 return 0;
2256 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002257 case "query-op": {
2258 int res = shell.parseUserOpMode(AppOpsManager.MODE_IGNORED, err);
2259 if (res < 0) {
2260 return res;
2261 }
2262 List<AppOpsManager.PackageOps> ops = shell.mInterface.getPackagesForOps(
2263 new int[] {shell.op});
2264 if (ops == null || ops.size() <= 0) {
2265 pw.println("No operations.");
2266 return 0;
2267 }
2268 for (int i=0; i<ops.size(); i++) {
2269 final AppOpsManager.PackageOps pkg = ops.get(i);
2270 boolean hasMatch = false;
2271 final List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
2272 for (int j=0; j<entries.size(); j++) {
2273 AppOpsManager.OpEntry ent = entries.get(j);
2274 if (ent.getOp() == shell.op && ent.getMode() == shell.mode) {
2275 hasMatch = true;
2276 break;
2277 }
2278 }
2279 if (hasMatch) {
2280 pw.println(pkg.getPackageName());
2281 }
2282 }
2283 return 0;
2284 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002285 case "reset": {
2286 String packageName = null;
2287 int userId = UserHandle.USER_CURRENT;
2288 for (String argument; (argument = shell.getNextArg()) != null;) {
2289 if ("--user".equals(argument)) {
2290 String userStr = shell.getNextArgRequired();
2291 userId = UserHandle.parseUserArg(userStr);
2292 } else {
2293 if (packageName == null) {
2294 packageName = argument;
2295 } else {
2296 err.println("Error: Unsupported argument: " + argument);
2297 return -1;
2298 }
2299 }
2300 }
2301
2302 if (userId == UserHandle.USER_CURRENT) {
2303 userId = ActivityManager.getCurrentUser();
2304 }
2305
2306 shell.mInterface.resetAllModes(userId, packageName);
2307 pw.print("Reset all modes for: ");
2308 if (userId == UserHandle.USER_ALL) {
2309 pw.print("all users");
2310 } else {
2311 pw.print("user "); pw.print(userId);
2312 }
2313 pw.print(", ");
2314 if (packageName == null) {
2315 pw.println("all packages");
2316 } else {
2317 pw.print("package "); pw.println(packageName);
2318 }
2319 return 0;
2320 }
2321 case "write-settings": {
2322 shell.mInternal.mContext.enforcePermission(
2323 android.Manifest.permission.UPDATE_APP_OPS_STATS,
2324 Binder.getCallingPid(), Binder.getCallingUid(), null);
2325 long token = Binder.clearCallingIdentity();
2326 try {
2327 synchronized (shell.mInternal) {
2328 shell.mInternal.mHandler.removeCallbacks(shell.mInternal.mWriteRunner);
2329 }
2330 shell.mInternal.writeState();
2331 pw.println("Current settings written.");
2332 } finally {
2333 Binder.restoreCallingIdentity(token);
2334 }
2335 return 0;
2336 }
2337 case "read-settings": {
2338 shell.mInternal.mContext.enforcePermission(
2339 android.Manifest.permission.UPDATE_APP_OPS_STATS,
2340 Binder.getCallingPid(), Binder.getCallingUid(), null);
2341 long token = Binder.clearCallingIdentity();
2342 try {
2343 shell.mInternal.readState();
2344 pw.println("Last settings read.");
2345 } finally {
2346 Binder.restoreCallingIdentity(token);
2347 }
2348 return 0;
2349 }
2350 default:
2351 return shell.handleDefaultCommands(cmd);
2352 }
2353 } catch (RemoteException e) {
2354 pw.println("Remote exception: " + e);
2355 }
2356 return -1;
2357 }
2358
2359 private void dumpHelp(PrintWriter pw) {
2360 pw.println("AppOps service (appops) dump options:");
2361 pw.println(" none");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002362 }
2363
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002364 @Override
2365 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002366 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002367
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002368 if (args != null) {
2369 for (int i=0; i<args.length; i++) {
2370 String arg = args[i];
2371 if ("-h".equals(arg)) {
2372 dumpHelp(pw);
2373 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07002374 } else if ("-a".equals(arg)) {
2375 // dump all data
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002376 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
2377 pw.println("Unknown option: " + arg);
2378 return;
2379 } else {
2380 pw.println("Unknown command: " + arg);
2381 return;
2382 }
2383 }
2384 }
2385
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002386 synchronized (this) {
2387 pw.println("Current AppOps Service state:");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002388 final long now = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002389 boolean needSep = false;
2390 if (mOpModeWatchers.size() > 0) {
2391 needSep = true;
2392 pw.println(" Op mode watchers:");
2393 for (int i=0; i<mOpModeWatchers.size(); i++) {
2394 pw.print(" Op "); pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
2395 pw.println(":");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002396 ArraySet<ModeCallback> callbacks = mOpModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002397 for (int j=0; j<callbacks.size(); j++) {
2398 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08002399 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002400 }
2401 }
2402 }
2403 if (mPackageModeWatchers.size() > 0) {
2404 needSep = true;
2405 pw.println(" Package mode watchers:");
2406 for (int i=0; i<mPackageModeWatchers.size(); i++) {
2407 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
2408 pw.println(":");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002409 ArraySet<ModeCallback> callbacks = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002410 for (int j=0; j<callbacks.size(); j++) {
2411 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08002412 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002413 }
2414 }
2415 }
2416 if (mModeWatchers.size() > 0) {
2417 needSep = true;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002418 pw.println(" All op mode watchers:");
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002419 for (int i=0; i<mModeWatchers.size(); i++) {
2420 pw.print(" "); pw.print(mModeWatchers.keyAt(i));
2421 pw.print(" -> "); pw.println(mModeWatchers.valueAt(i));
2422 }
2423 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002424 if (mActiveWatchers.size() > 0) {
2425 needSep = true;
2426 pw.println(" All op active watchers:");
2427 for (int i = 0; i < mActiveWatchers.size(); i++) {
2428 final SparseArray<ActiveCallback> activeWatchers = mActiveWatchers.valueAt(i);
2429 if (activeWatchers.size() <= 0) {
2430 continue;
2431 }
2432 pw.print(" "); pw.print(mActiveWatchers.keyAt(i));
2433 pw.print(" -> [");
2434 final int opCount = activeWatchers.size();
2435 for (i = 0; i < opCount; i++) {
2436 pw.print(AppOpsManager.opToName(activeWatchers.keyAt(i)));
2437 if (i < opCount - 1) {
2438 pw.print(',');
2439 }
2440 }
2441 pw.print("]" ); pw.println(activeWatchers.valueAt(0));
2442 }
2443 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002444 if (mClients.size() > 0) {
2445 needSep = true;
2446 pw.println(" Clients:");
2447 for (int i=0; i<mClients.size(); i++) {
2448 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
2449 ClientState cs = mClients.valueAt(i);
2450 pw.print(" "); pw.println(cs);
Svet Ganovf7b47252018-02-26 11:11:27 -08002451 if (cs.mStartedOps.size() > 0) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002452 pw.println(" Started ops:");
2453 for (int j=0; j<cs.mStartedOps.size(); j++) {
2454 Op op = cs.mStartedOps.get(j);
2455 pw.print(" "); pw.print("uid="); pw.print(op.uid);
2456 pw.print(" pkg="); pw.print(op.packageName);
2457 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
2458 }
2459 }
2460 }
2461 }
John Spurlock1af30c72014-03-10 08:33:35 -04002462 if (mAudioRestrictions.size() > 0) {
2463 boolean printedHeader = false;
2464 for (int o=0; o<mAudioRestrictions.size(); o++) {
2465 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
2466 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
2467 for (int i=0; i<restrictions.size(); i++) {
2468 if (!printedHeader){
2469 pw.println(" Audio Restrictions:");
2470 printedHeader = true;
2471 needSep = true;
2472 }
John Spurlock7b414672014-07-18 13:02:39 -04002473 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04002474 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04002475 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04002476 Restriction r = restrictions.valueAt(i);
2477 pw.print(": mode="); pw.println(r.mode);
2478 if (!r.exceptionPackages.isEmpty()) {
2479 pw.println(" Exceptions:");
2480 for (int j=0; j<r.exceptionPackages.size(); j++) {
2481 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
2482 }
2483 }
2484 }
2485 }
2486 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002487 if (needSep) {
2488 pw.println();
2489 }
Svet Ganov2af57082015-07-30 08:44:20 -07002490 for (int i=0; i<mUidStates.size(); i++) {
2491 UidState uidState = mUidStates.valueAt(i);
2492
2493 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
Svet Ganovee438d42017-01-19 18:04:38 -08002494 needSep = true;
Svet Ganov2af57082015-07-30 08:44:20 -07002495
2496 SparseIntArray opModes = uidState.opModes;
2497 if (opModes != null) {
2498 final int opModeCount = opModes.size();
2499 for (int j = 0; j < opModeCount; j++) {
2500 final int code = opModes.keyAt(j);
2501 final int mode = opModes.valueAt(j);
2502 pw.print(" "); pw.print(AppOpsManager.opToName(code));
2503 pw.print(": mode="); pw.println(mode);
2504 }
2505 }
2506
2507 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
2508 if (pkgOps == null) {
2509 continue;
2510 }
2511
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002512 for (Ops ops : pkgOps.values()) {
2513 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
2514 for (int j=0; j<ops.size(); j++) {
2515 Op op = ops.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002516 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
2517 pw.print(": mode="); pw.print(op.mode);
2518 if (op.time != 0) {
2519 pw.print("; time="); TimeUtils.formatDuration(now-op.time, pw);
2520 pw.print(" ago");
2521 }
2522 if (op.rejectTime != 0) {
2523 pw.print("; rejectTime="); TimeUtils.formatDuration(now-op.rejectTime, pw);
2524 pw.print(" ago");
2525 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002526 if (op.duration == -1) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002527 pw.print(" (running)");
2528 } else if (op.duration != 0) {
2529 pw.print("; duration="); TimeUtils.formatDuration(op.duration, pw);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002530 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002531 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002532 }
2533 }
2534 }
Svet Ganovee438d42017-01-19 18:04:38 -08002535 if (needSep) {
2536 pw.println();
2537 }
2538
2539 final int userRestrictionCount = mOpUserRestrictions.size();
2540 for (int i = 0; i < userRestrictionCount; i++) {
2541 IBinder token = mOpUserRestrictions.keyAt(i);
2542 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
2543 pw.println(" User restrictions for token " + token + ":");
2544
2545 final int restrictionCount = restrictionState.perUserRestrictions != null
2546 ? restrictionState.perUserRestrictions.size() : 0;
2547 if (restrictionCount > 0) {
2548 pw.println(" Restricted ops:");
2549 for (int j = 0; j < restrictionCount; j++) {
2550 int userId = restrictionState.perUserRestrictions.keyAt(j);
2551 boolean[] restrictedOps = restrictionState.perUserRestrictions.valueAt(j);
2552 if (restrictedOps == null) {
2553 continue;
2554 }
2555 StringBuilder restrictedOpsValue = new StringBuilder();
2556 restrictedOpsValue.append("[");
2557 final int restrictedOpCount = restrictedOps.length;
2558 for (int k = 0; k < restrictedOpCount; k++) {
2559 if (restrictedOps[k]) {
2560 if (restrictedOpsValue.length() > 1) {
2561 restrictedOpsValue.append(", ");
2562 }
2563 restrictedOpsValue.append(AppOpsManager.opToName(k));
2564 }
2565 }
2566 restrictedOpsValue.append("]");
2567 pw.print(" "); pw.print("user: "); pw.print(userId);
2568 pw.print(" restricted ops: "); pw.println(restrictedOpsValue);
2569 }
2570 }
2571
2572 final int excludedPackageCount = restrictionState.perUserExcludedPackages != null
2573 ? restrictionState.perUserExcludedPackages.size() : 0;
2574 if (excludedPackageCount > 0) {
2575 pw.println(" Excluded packages:");
2576 for (int j = 0; j < excludedPackageCount; j++) {
2577 int userId = restrictionState.perUserExcludedPackages.keyAt(j);
2578 String[] packageNames = restrictionState.perUserExcludedPackages.valueAt(j);
2579 pw.print(" "); pw.print("user: "); pw.print(userId);
2580 pw.print(" packages: "); pw.println(Arrays.toString(packageNames));
2581 }
2582 }
2583 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002584 }
2585 }
John Spurlock1af30c72014-03-10 08:33:35 -04002586
2587 private static final class Restriction {
2588 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
2589 int mode;
2590 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
2591 }
Jason Monk62062992014-05-06 09:55:28 -04002592
2593 @Override
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002594 public void setUserRestrictions(Bundle restrictions, IBinder token, int userHandle) {
Jason Monk62062992014-05-06 09:55:28 -04002595 checkSystemUid("setUserRestrictions");
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002596 Preconditions.checkNotNull(restrictions);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002597 Preconditions.checkNotNull(token);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002598 for (int i = 0; i < AppOpsManager._NUM_OP; i++) {
Jason Monk62062992014-05-06 09:55:28 -04002599 String restriction = AppOpsManager.opToRestriction(i);
Suprabh Shukla64e0dcb2016-05-24 16:23:11 -07002600 if (restriction != null) {
2601 setUserRestrictionNoCheck(i, restrictions.getBoolean(restriction, false), token,
2602 userHandle, null);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002603 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002604 }
2605 }
2606
2607 @Override
Ruben Brunk29931bc2016-03-11 00:24:26 -08002608 public void setUserRestriction(int code, boolean restricted, IBinder token, int userHandle,
2609 String[] exceptionPackages) {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002610 if (Binder.getCallingPid() != Process.myPid()) {
2611 mContext.enforcePermission(Manifest.permission.MANAGE_APP_OPS_RESTRICTIONS,
2612 Binder.getCallingPid(), Binder.getCallingUid(), null);
2613 }
2614 if (userHandle != UserHandle.getCallingUserId()) {
2615 if (mContext.checkCallingOrSelfPermission(Manifest.permission
2616 .INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
2617 && mContext.checkCallingOrSelfPermission(Manifest.permission
2618 .INTERACT_ACROSS_USERS) != PackageManager.PERMISSION_GRANTED) {
2619 throw new SecurityException("Need INTERACT_ACROSS_USERS_FULL or"
2620 + " INTERACT_ACROSS_USERS to interact cross user ");
Jason Monk62062992014-05-06 09:55:28 -04002621 }
2622 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002623 verifyIncomingOp(code);
2624 Preconditions.checkNotNull(token);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002625 setUserRestrictionNoCheck(code, restricted, token, userHandle, exceptionPackages);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002626 }
2627
2628 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
Ruben Brunk29931bc2016-03-11 00:24:26 -08002629 int userHandle, String[] exceptionPackages) {
Svet Ganov442ed572016-08-17 17:29:43 -07002630 synchronized (AppOpsService.this) {
2631 ClientRestrictionState restrictionState = mOpUserRestrictions.get(token);
2632
2633 if (restrictionState == null) {
2634 try {
2635 restrictionState = new ClientRestrictionState(token);
2636 } catch (RemoteException e) {
2637 return;
2638 }
2639 mOpUserRestrictions.put(token, restrictionState);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002640 }
Svet Ganov442ed572016-08-17 17:29:43 -07002641
2642 if (restrictionState.setRestriction(code, restricted, exceptionPackages, userHandle)) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002643 mHandler.sendMessage(PooledLambda.obtainMessage(
2644 AppOpsService::notifyWatchersOfChange, this, code));
Svet Ganov442ed572016-08-17 17:29:43 -07002645 }
2646
2647 if (restrictionState.isDefault()) {
2648 mOpUserRestrictions.remove(token);
2649 restrictionState.destroy();
2650 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002651 }
Julia Reynoldsbb21c252016-04-05 16:01:49 -04002652 }
2653
2654 private void notifyWatchersOfChange(int code) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002655 final ArraySet<ModeCallback> clonedCallbacks;
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002656 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002657 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002658 if (callbacks == null) {
2659 return;
2660 }
Dianne Hackborn68d76552017-02-27 15:32:03 -08002661 clonedCallbacks = new ArraySet<>(callbacks);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002662 }
2663
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002664 notifyOpChanged(clonedCallbacks, code, -1, null);
Jason Monk62062992014-05-06 09:55:28 -04002665 }
2666
2667 @Override
2668 public void removeUser(int userHandle) throws RemoteException {
2669 checkSystemUid("removeUser");
Svet Ganov442ed572016-08-17 17:29:43 -07002670 synchronized (AppOpsService.this) {
2671 final int tokenCount = mOpUserRestrictions.size();
2672 for (int i = tokenCount - 1; i >= 0; i--) {
2673 ClientRestrictionState opRestrictions = mOpUserRestrictions.valueAt(i);
2674 opRestrictions.removeUser(userHandle);
2675 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002676 removeUidsForUserLocked(userHandle);
2677 }
2678 }
2679
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002680 @Override
2681 public boolean isOperationActive(int code, int uid, String packageName) {
Svet Ganovf7b47252018-02-26 11:11:27 -08002682 if (Binder.getCallingUid() != uid) {
2683 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
2684 != PackageManager.PERMISSION_GRANTED) {
2685 return false;
2686 }
2687 }
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002688 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002689 final String resolvedPackageName = resolvePackageName(uid, packageName);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002690 if (resolvedPackageName == null) {
2691 return false;
2692 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002693 synchronized (AppOpsService.this) {
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002694 for (int i = mClients.size() - 1; i >= 0; i--) {
2695 final ClientState client = mClients.valueAt(i);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002696 for (int j = client.mStartedOps.size() - 1; j >= 0; j--) {
2697 final Op op = client.mStartedOps.get(j);
2698 if (op.op == code && op.uid == uid) return true;
2699 }
2700 }
2701 }
2702 return false;
2703 }
2704
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002705 private void removeUidsForUserLocked(int userHandle) {
2706 for (int i = mUidStates.size() - 1; i >= 0; --i) {
2707 final int uid = mUidStates.keyAt(i);
2708 if (UserHandle.getUserId(uid) == userHandle) {
2709 mUidStates.removeAt(i);
2710 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002711 }
2712 }
2713
Jason Monk62062992014-05-06 09:55:28 -04002714 private void checkSystemUid(String function) {
2715 int uid = Binder.getCallingUid();
2716 if (uid != Process.SYSTEM_UID) {
2717 throw new SecurityException(function + " must by called by the system");
2718 }
2719 }
2720
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002721 private static String resolvePackageName(int uid, String packageName) {
Svet Ganov82f09bc2018-01-12 22:08:40 -08002722 if (uid == Process.ROOT_UID) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002723 return "root";
2724 } else if (uid == Process.SHELL_UID) {
2725 return "com.android.shell";
Svet Ganov82f09bc2018-01-12 22:08:40 -08002726 } else if (uid == Process.MEDIA_UID) {
2727 return "media";
2728 } else if (uid == Process.AUDIOSERVER_UID) {
2729 return "audioserver";
2730 } else if (uid == Process.CAMERASERVER_UID) {
2731 return "cameraserver";
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002732 } else if (uid == Process.SYSTEM_UID && packageName == null) {
2733 return "android";
2734 }
2735 return packageName;
2736 }
2737
Svet Ganov82f09bc2018-01-12 22:08:40 -08002738 private static int resolveUid(String packageName) {
2739 if (packageName == null) {
2740 return -1;
2741 }
2742 switch (packageName) {
2743 case "root":
2744 return Process.ROOT_UID;
2745 case "shell":
2746 return Process.SHELL_UID;
2747 case "media":
2748 return Process.MEDIA_UID;
2749 case "audioserver":
2750 return Process.AUDIOSERVER_UID;
2751 case "cameraserver":
2752 return Process.CAMERASERVER_UID;
2753 }
2754 return -1;
2755 }
2756
Svet Ganov2af57082015-07-30 08:44:20 -07002757 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07002758 String[] packageNames = null;
Svet Ganov2af57082015-07-30 08:44:20 -07002759 try {
riddle_hsu40b300f2015-11-23 13:22:03 +08002760 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -07002761 } catch (RemoteException e) {
2762 /* ignore - local call */
2763 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07002764 if (packageNames == null) {
2765 return EmptyArray.STRING;
2766 }
2767 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07002768 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002769
2770 private final class ClientRestrictionState implements DeathRecipient {
2771 private final IBinder token;
2772 SparseArray<boolean[]> perUserRestrictions;
2773 SparseArray<String[]> perUserExcludedPackages;
2774
2775 public ClientRestrictionState(IBinder token)
2776 throws RemoteException {
2777 token.linkToDeath(this, 0);
2778 this.token = token;
2779 }
2780
2781 public boolean setRestriction(int code, boolean restricted,
2782 String[] excludedPackages, int userId) {
2783 boolean changed = false;
2784
2785 if (perUserRestrictions == null && restricted) {
2786 perUserRestrictions = new SparseArray<>();
2787 }
2788
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002789 int[] users;
2790 if (userId == UserHandle.USER_ALL) {
2791 List<UserInfo> liveUsers = UserManager.get(mContext).getUsers(false);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002792
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002793 users = new int[liveUsers.size()];
2794 for (int i = 0; i < liveUsers.size(); i++) {
2795 users[i] = liveUsers.get(i).id;
2796 }
2797 } else {
2798 users = new int[]{userId};
2799 }
2800
2801 if (perUserRestrictions != null) {
2802 int numUsers = users.length;
2803
2804 for (int i = 0; i < numUsers; i++) {
2805 int thisUserId = users[i];
2806
2807 boolean[] userRestrictions = perUserRestrictions.get(thisUserId);
2808 if (userRestrictions == null && restricted) {
2809 userRestrictions = new boolean[AppOpsManager._NUM_OP];
2810 perUserRestrictions.put(thisUserId, userRestrictions);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002811 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002812 if (userRestrictions != null && userRestrictions[code] != restricted) {
2813 userRestrictions[code] = restricted;
2814 if (!restricted && isDefault(userRestrictions)) {
2815 perUserRestrictions.remove(thisUserId);
2816 userRestrictions = null;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002817 }
2818 changed = true;
2819 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002820
2821 if (userRestrictions != null) {
2822 final boolean noExcludedPackages = ArrayUtils.isEmpty(excludedPackages);
2823 if (perUserExcludedPackages == null && !noExcludedPackages) {
2824 perUserExcludedPackages = new SparseArray<>();
2825 }
2826 if (perUserExcludedPackages != null && !Arrays.equals(excludedPackages,
2827 perUserExcludedPackages.get(thisUserId))) {
2828 if (noExcludedPackages) {
2829 perUserExcludedPackages.remove(thisUserId);
2830 if (perUserExcludedPackages.size() <= 0) {
2831 perUserExcludedPackages = null;
2832 }
2833 } else {
2834 perUserExcludedPackages.put(thisUserId, excludedPackages);
2835 }
2836 changed = true;
2837 }
2838 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002839 }
2840 }
2841
2842 return changed;
2843 }
2844
2845 public boolean hasRestriction(int restriction, String packageName, int userId) {
2846 if (perUserRestrictions == null) {
2847 return false;
2848 }
2849 boolean[] restrictions = perUserRestrictions.get(userId);
2850 if (restrictions == null) {
2851 return false;
2852 }
2853 if (!restrictions[restriction]) {
2854 return false;
2855 }
2856 if (perUserExcludedPackages == null) {
2857 return true;
2858 }
2859 String[] perUserExclusions = perUserExcludedPackages.get(userId);
2860 if (perUserExclusions == null) {
2861 return true;
2862 }
2863 return !ArrayUtils.contains(perUserExclusions, packageName);
2864 }
2865
2866 public void removeUser(int userId) {
2867 if (perUserExcludedPackages != null) {
2868 perUserExcludedPackages.remove(userId);
2869 if (perUserExcludedPackages.size() <= 0) {
2870 perUserExcludedPackages = null;
2871 }
2872 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002873 if (perUserRestrictions != null) {
2874 perUserRestrictions.remove(userId);
2875 if (perUserRestrictions.size() <= 0) {
2876 perUserRestrictions = null;
2877 }
2878 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002879 }
2880
2881 public boolean isDefault() {
2882 return perUserRestrictions == null || perUserRestrictions.size() <= 0;
2883 }
2884
2885 @Override
2886 public void binderDied() {
2887 synchronized (AppOpsService.this) {
2888 mOpUserRestrictions.remove(token);
2889 if (perUserRestrictions == null) {
2890 return;
2891 }
2892 final int userCount = perUserRestrictions.size();
2893 for (int i = 0; i < userCount; i++) {
2894 final boolean[] restrictions = perUserRestrictions.valueAt(i);
2895 final int restrictionCount = restrictions.length;
2896 for (int j = 0; j < restrictionCount; j++) {
2897 if (restrictions[j]) {
2898 final int changedCode = j;
2899 mHandler.post(() -> notifyWatchersOfChange(changedCode));
2900 }
2901 }
2902 }
2903 destroy();
2904 }
2905 }
2906
2907 public void destroy() {
2908 token.unlinkToDeath(this, 0);
2909 }
2910
2911 private boolean isDefault(boolean[] array) {
2912 if (ArrayUtils.isEmpty(array)) {
2913 return true;
2914 }
2915 for (boolean value : array) {
2916 if (value) {
2917 return false;
2918 }
2919 }
2920 return true;
2921 }
2922 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002923}