blob: 4c0578d7aa0f30ab09ccefd41b2c3a51fafcddfb [file] [log] [blame]
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Philip P. Moltmanne683f192017-06-23 14:05:04 -070019import android.Manifest;
20import android.app.ActivityManager;
21import android.app.ActivityThread;
22import android.app.AppGlobals;
23import android.app.AppOpsManager;
24import android.content.Context;
25import android.content.pm.ApplicationInfo;
26import android.content.pm.IPackageManager;
27import android.content.pm.PackageManager;
28import android.content.pm.PackageManagerInternal;
29import android.content.pm.UserInfo;
30import android.media.AudioAttributes;
31import android.os.AsyncTask;
32import android.os.Binder;
33import android.os.Bundle;
34import android.os.Handler;
35import android.os.IBinder;
36import android.os.Process;
37import android.os.RemoteException;
38import android.os.ResultReceiver;
39import android.os.ServiceManager;
40import android.os.ShellCallback;
41import android.os.ShellCommand;
42import android.os.UserHandle;
43import android.os.UserManager;
44import android.os.storage.StorageManagerInternal;
45import android.util.ArrayMap;
46import android.util.ArraySet;
47import android.util.AtomicFile;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070048import android.util.Slog;
49import android.util.SparseArray;
50import android.util.SparseIntArray;
51import android.util.TimeUtils;
52import android.util.Xml;
53
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070054import com.android.internal.annotations.VisibleForTesting;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -080055import com.android.internal.app.IAppOpsActiveCallback;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070056import com.android.internal.app.IAppOpsCallback;
57import com.android.internal.app.IAppOpsService;
58import com.android.internal.os.Zygote;
59import com.android.internal.util.ArrayUtils;
60import com.android.internal.util.DumpUtils;
61import com.android.internal.util.FastXmlSerializer;
62import com.android.internal.util.Preconditions;
63import com.android.internal.util.XmlUtils;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -080064import com.android.internal.util.function.pooled.PooledLambda;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -050065
Philip P. Moltmanne683f192017-06-23 14:05:04 -070066import libcore.util.EmptyArray;
67
68import org.xmlpull.v1.XmlPullParser;
69import org.xmlpull.v1.XmlPullParserException;
70import org.xmlpull.v1.XmlSerializer;
71
Dianne Hackborna06de0f2012-12-11 16:34:47 -080072import java.io.File;
73import java.io.FileDescriptor;
Dianne Hackborn35654b62013-01-14 17:38:02 -080074import java.io.FileInputStream;
75import java.io.FileNotFoundException;
76import java.io.FileOutputStream;
77import java.io.IOException;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080078import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010079import java.nio.charset.StandardCharsets;
Dianne Hackborn35654b62013-01-14 17:38:02 -080080import java.util.ArrayList;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -070081import java.util.Arrays;
Svetoslav215b44a2015-08-04 19:03:40 -070082import java.util.Collections;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080083import java.util.HashMap;
Dianne Hackbornc2293022013-02-06 23:14:49 -080084import java.util.Iterator;
Dianne Hackborn35654b62013-01-14 17:38:02 -080085import java.util.List;
Dianne Hackborn607b4142013-08-02 18:10:10 -070086import java.util.Map;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080087
Dianne Hackborna06de0f2012-12-11 16:34:47 -080088public class AppOpsService extends IAppOpsService.Stub {
89 static final String TAG = "AppOps";
Dianne Hackborn35654b62013-01-14 17:38:02 -080090 static final boolean DEBUG = false;
91
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070092 private static final int NO_VERSION = -1;
93 /** Increment by one every time and add the corresponding upgrade logic in
94 * {@link #upgradeLocked(int)} below. The first version was 1 */
95 private static final int CURRENT_VERSION = 1;
96
Dianne Hackborn35654b62013-01-14 17:38:02 -080097 // Write at most every 30 minutes.
98 static final long WRITE_DELAY = DEBUG ? 1000 : 30*60*1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080099
Svet Ganov3a95f832018-03-23 17:44:30 -0700100 // Constant meaning that any UID should be matched when dispatching callbacks
101 private static final int UID_ANY = -2;
102
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800103 Context mContext;
104 final AtomicFile mFile;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800105 final Handler mHandler;
106
107 boolean mWriteScheduled;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800108 boolean mFastWriteScheduled;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800109 final Runnable mWriteRunner = new Runnable() {
110 public void run() {
111 synchronized (AppOpsService.this) {
112 mWriteScheduled = false;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800113 mFastWriteScheduled = false;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800114 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
115 @Override protected Void doInBackground(Void... params) {
116 writeState();
117 return null;
118 }
119 };
120 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
121 }
122 }
123 };
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800124
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700125 @VisibleForTesting
126 final SparseArray<UidState> mUidStates = new SparseArray<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800127
Ruben Brunk29931bc2016-03-11 00:24:26 -0800128 /*
129 * These are app op restrictions imposed per user from various parties.
Ruben Brunk29931bc2016-03-11 00:24:26 -0800130 */
Svetoslav Ganova8bbd762016-05-13 17:08:16 -0700131 private final ArrayMap<IBinder, ClientRestrictionState> mOpUserRestrictions = new ArrayMap<>();
Jason Monk62062992014-05-06 09:55:28 -0400132
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700133 @VisibleForTesting
134 static final class UidState {
Svet Ganov2af57082015-07-30 08:44:20 -0700135 public final int uid;
136 public ArrayMap<String, Ops> pkgOps;
137 public SparseIntArray opModes;
138
139 public UidState(int uid) {
140 this.uid = uid;
141 }
142
143 public void clear() {
144 pkgOps = null;
145 opModes = null;
146 }
147
148 public boolean isDefault() {
149 return (pkgOps == null || pkgOps.isEmpty())
150 && (opModes == null || opModes.size() <= 0);
151 }
152 }
153
Dianne Hackbornc2293022013-02-06 23:14:49 -0800154 public final static class Ops extends SparseArray<Op> {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800155 public final String packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700156 public final UidState uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400157 public final boolean isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800158
Svet Ganov2af57082015-07-30 08:44:20 -0700159 public Ops(String _packageName, UidState _uidState, boolean _isPrivileged) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800160 packageName = _packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700161 uidState = _uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400162 isPrivileged = _isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800163 }
164 }
165
Dianne Hackbornc2293022013-02-06 23:14:49 -0800166 public final static class Op {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700167 public final int uid;
168 public final String packageName;
Svet Ganov99b60432015-06-27 13:15:22 -0700169 public int proxyUid = -1;
170 public String proxyPackageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800171 public final int op;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800172 public int mode;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800173 public int duration;
174 public long time;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800175 public long rejectTime;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800176 public int nesting;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800177
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700178 public Op(int _uid, String _packageName, int _op) {
179 uid = _uid;
180 packageName = _packageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800181 op = _op;
David Braunf5d83192013-09-16 13:43:51 -0700182 mode = AppOpsManager.opToDefaultMode(op);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800183 }
184 }
185
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800186 final SparseArray<ArraySet<ModeCallback>> mOpModeWatchers = new SparseArray<>();
187 final ArrayMap<String, ArraySet<ModeCallback>> mPackageModeWatchers = new ArrayMap<>();
188 final ArrayMap<IBinder, ModeCallback> mModeWatchers = new ArrayMap<>();
189 final ArrayMap<IBinder, SparseArray<ActiveCallback>> mActiveWatchers = new ArrayMap<>();
Dianne Hackborn68d76552017-02-27 15:32:03 -0800190 final SparseArray<SparseArray<Restriction>> mAudioRestrictions = new SparseArray<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800191
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800192 public final class ModeCallback implements DeathRecipient {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800193 final IAppOpsCallback mCallback;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800194 final int mUid;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800195
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800196 public ModeCallback(IAppOpsCallback callback, int uid) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800197 mCallback = callback;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800198 mUid = uid;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800199 try {
200 mCallback.asBinder().linkToDeath(this, 0);
201 } catch (RemoteException e) {
202 }
203 }
204
205 public void unlinkToDeath() {
206 mCallback.asBinder().unlinkToDeath(this, 0);
207 }
208
209 @Override
210 public void binderDied() {
211 stopWatchingMode(mCallback);
212 }
213 }
214
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800215 public final class ActiveCallback implements DeathRecipient {
216 final IAppOpsActiveCallback mCallback;
Svet Ganovf7b47252018-02-26 11:11:27 -0800217 final int mUid;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800218
Svet Ganovf7b47252018-02-26 11:11:27 -0800219 public ActiveCallback(IAppOpsActiveCallback callback, int uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800220 mCallback = callback;
Svet Ganovf7b47252018-02-26 11:11:27 -0800221 mUid = uid;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800222 try {
223 mCallback.asBinder().linkToDeath(this, 0);
224 } catch (RemoteException e) {
225 }
226 }
227
228 public void destroy() {
229 mCallback.asBinder().unlinkToDeath(this, 0);
230 }
231
232 @Override
233 public void binderDied() {
234 stopWatchingActive(mCallback);
235 }
236 }
237
Svet Ganova7a0db62018-02-27 20:08:01 -0800238 final ArrayMap<IBinder, ClientState> mClients = new ArrayMap<>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700239
240 public final class ClientState extends Binder implements DeathRecipient {
Svet Ganovf7b47252018-02-26 11:11:27 -0800241 final ArrayList<Op> mStartedOps = new ArrayList<>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700242 final IBinder mAppToken;
243 final int mPid;
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700244
245 public ClientState(IBinder appToken) {
246 mAppToken = appToken;
247 mPid = Binder.getCallingPid();
Svet Ganovf7b47252018-02-26 11:11:27 -0800248 // Watch only for remote processes dying
249 if (!(appToken instanceof Binder)) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700250 try {
251 mAppToken.linkToDeath(this, 0);
252 } catch (RemoteException e) {
Svet Ganovf7b47252018-02-26 11:11:27 -0800253 /* do nothing */
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700254 }
255 }
256 }
257
258 @Override
259 public String toString() {
260 return "ClientState{" +
261 "mAppToken=" + mAppToken +
Svet Ganovf7b47252018-02-26 11:11:27 -0800262 ", " + "pid=" + mPid +
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700263 '}';
264 }
265
266 @Override
267 public void binderDied() {
268 synchronized (AppOpsService.this) {
269 for (int i=mStartedOps.size()-1; i>=0; i--) {
Svet Ganova7a0db62018-02-27 20:08:01 -0800270 finishOperationLocked(mStartedOps.get(i), /*finishNested*/ true);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700271 }
272 mClients.remove(mAppToken);
273 }
274 }
275 }
276
Jeff Brown6f357d32014-01-15 20:40:55 -0800277 public AppOpsService(File storagePath, Handler handler) {
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600278 LockGuard.installLock(this, LockGuard.INDEX_APP_OPS);
Dianne Hackborne17b4452018-01-10 13:15:40 -0800279 mFile = new AtomicFile(storagePath, "appops");
Jeff Brown6f357d32014-01-15 20:40:55 -0800280 mHandler = handler;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800281 readState();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800282 }
David Braunf5d83192013-09-16 13:43:51 -0700283
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800284 public void publish(Context context) {
285 mContext = context;
286 ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
287 }
288
Dianne Hackborn514074f2013-02-11 10:52:46 -0800289 public void systemReady() {
290 synchronized (this) {
291 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700292 for (int i = mUidStates.size() - 1; i >= 0; i--) {
293 UidState uidState = mUidStates.valueAt(i);
294
295 String[] packageNames = getPackagesForUid(uidState.uid);
296 if (ArrayUtils.isEmpty(packageNames)) {
297 uidState.clear();
298 mUidStates.removeAt(i);
299 changed = true;
300 continue;
301 }
302
303 ArrayMap<String, Ops> pkgs = uidState.pkgOps;
304 if (pkgs == null) {
305 continue;
306 }
307
Dianne Hackborn514074f2013-02-11 10:52:46 -0800308 Iterator<Ops> it = pkgs.values().iterator();
309 while (it.hasNext()) {
310 Ops ops = it.next();
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700311 int curUid = -1;
Dianne Hackborn514074f2013-02-11 10:52:46 -0800312 try {
Jeff Sharkeycd654482016-01-08 17:42:11 -0700313 curUid = AppGlobals.getPackageManager().getPackageUid(ops.packageName,
314 PackageManager.MATCH_UNINSTALLED_PACKAGES,
Svet Ganov2af57082015-07-30 08:44:20 -0700315 UserHandle.getUserId(ops.uidState.uid));
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700316 } catch (RemoteException ignored) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800317 }
Svet Ganov2af57082015-07-30 08:44:20 -0700318 if (curUid != ops.uidState.uid) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800319 Slog.i(TAG, "Pruning old package " + ops.packageName
Svet Ganov2af57082015-07-30 08:44:20 -0700320 + "/" + ops.uidState + ": new uid=" + curUid);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800321 it.remove();
322 changed = true;
323 }
324 }
Svet Ganov2af57082015-07-30 08:44:20 -0700325
326 if (uidState.isDefault()) {
327 mUidStates.removeAt(i);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800328 }
329 }
330 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800331 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800332 }
333 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700334
Suprabh Shuklaaef25132017-01-23 18:09:03 -0800335 PackageManagerInternal packageManagerInternal = LocalServices.getService(
336 PackageManagerInternal.class);
337 packageManagerInternal.setExternalSourcesPolicy(
338 new PackageManagerInternal.ExternalSourcesPolicy() {
339 @Override
340 public int getPackageTrustedToInstallApps(String packageName, int uid) {
341 int appOpMode = checkOperation(AppOpsManager.OP_REQUEST_INSTALL_PACKAGES,
342 uid, packageName);
343 switch (appOpMode) {
344 case AppOpsManager.MODE_ALLOWED:
345 return PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
346 case AppOpsManager.MODE_ERRORED:
347 return PackageManagerInternal.ExternalSourcesPolicy.USER_BLOCKED;
348 default:
349 return PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT;
350 }
351 }
352 });
353
Sudheer Shanka2250d562016-11-07 15:41:02 -0800354 StorageManagerInternal storageManagerInternal = LocalServices.getService(
355 StorageManagerInternal.class);
356 storageManagerInternal.addExternalStoragePolicy(
357 new StorageManagerInternal.ExternalStorageMountPolicy() {
Svet Ganov6ee871e2015-07-10 14:29:33 -0700358 @Override
359 public int getMountMode(int uid, String packageName) {
360 if (Process.isIsolated(uid)) {
361 return Zygote.MOUNT_EXTERNAL_NONE;
362 }
363 if (noteOperation(AppOpsManager.OP_READ_EXTERNAL_STORAGE, uid,
364 packageName) != AppOpsManager.MODE_ALLOWED) {
365 return Zygote.MOUNT_EXTERNAL_NONE;
366 }
367 if (noteOperation(AppOpsManager.OP_WRITE_EXTERNAL_STORAGE, uid,
368 packageName) != AppOpsManager.MODE_ALLOWED) {
369 return Zygote.MOUNT_EXTERNAL_READ;
370 }
371 return Zygote.MOUNT_EXTERNAL_WRITE;
372 }
373
374 @Override
375 public boolean hasExternalStorage(int uid, String packageName) {
376 final int mountMode = getMountMode(uid, packageName);
377 return mountMode == Zygote.MOUNT_EXTERNAL_READ
378 || mountMode == Zygote.MOUNT_EXTERNAL_WRITE;
379 }
380 });
Dianne Hackborn514074f2013-02-11 10:52:46 -0800381 }
382
383 public void packageRemoved(int uid, String packageName) {
384 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700385 UidState uidState = mUidStates.get(uid);
386 if (uidState == null) {
387 return;
388 }
389
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800390 Ops ops = null;
Svet Ganov2af57082015-07-30 08:44:20 -0700391
392 // Remove any package state if such.
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800393 if (uidState.pkgOps != null) {
394 ops = uidState.pkgOps.remove(packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700395 }
396
397 // If we just nuked the last package state check if the UID is valid.
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800398 if (ops != null && uidState.pkgOps.isEmpty()
Svet Ganov2af57082015-07-30 08:44:20 -0700399 && getPackagesForUid(uid).length <= 0) {
400 mUidStates.remove(uid);
401 }
402
Svet Ganova7a0db62018-02-27 20:08:01 -0800403 // Finish ops other packages started on behalf of the package.
404 final int clientCount = mClients.size();
405 for (int i = 0; i < clientCount; i++) {
406 final ClientState client = mClients.valueAt(i);
407 if (client.mStartedOps == null) {
408 continue;
409 }
410 final int opCount = client.mStartedOps.size();
411 for (int j = opCount - 1; j >= 0; j--) {
412 final Op op = client.mStartedOps.get(j);
413 if (uid == op.uid && packageName.equals(op.packageName)) {
414 finishOperationLocked(op, /*finishNested*/ true);
415 client.mStartedOps.remove(j);
416 if (op.nesting <= 0) {
417 scheduleOpActiveChangedIfNeededLocked(op.op,
418 uid, packageName, false);
419 }
420 }
421 }
422 }
423
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800424 if (ops != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700425 scheduleFastWriteLocked();
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800426
427 final int opCount = ops.size();
428 for (int i = 0; i < opCount; i++) {
429 final Op op = ops.valueAt(i);
430 if (op.duration == -1) {
431 scheduleOpActiveChangedIfNeededLocked(
432 op.op, op.uid, op.packageName, false);
433 }
434 }
Dianne Hackborn514074f2013-02-11 10:52:46 -0800435 }
436 }
437 }
438
439 public void uidRemoved(int uid) {
440 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700441 if (mUidStates.indexOfKey(uid) >= 0) {
442 mUidStates.remove(uid);
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800443 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800444 }
445 }
446 }
447
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800448 public void shutdown() {
449 Slog.w(TAG, "Writing app ops before shutdown...");
Dianne Hackborn35654b62013-01-14 17:38:02 -0800450 boolean doWrite = false;
451 synchronized (this) {
452 if (mWriteScheduled) {
453 mWriteScheduled = false;
454 doWrite = true;
455 }
456 }
457 if (doWrite) {
458 writeState();
459 }
460 }
461
Dianne Hackborn72e39832013-01-18 18:36:09 -0800462 private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
463 ArrayList<AppOpsManager.OpEntry> resOps = null;
464 if (ops == null) {
465 resOps = new ArrayList<AppOpsManager.OpEntry>();
466 for (int j=0; j<pkgOps.size(); j++) {
467 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800468 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Svet Ganov99b60432015-06-27 13:15:22 -0700469 curOp.rejectTime, curOp.duration, curOp.proxyUid,
470 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800471 }
472 } else {
473 for (int j=0; j<ops.length; j++) {
474 Op curOp = pkgOps.get(ops[j]);
475 if (curOp != null) {
476 if (resOps == null) {
477 resOps = new ArrayList<AppOpsManager.OpEntry>();
478 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800479 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Svet Ganov99b60432015-06-27 13:15:22 -0700480 curOp.rejectTime, curOp.duration, curOp.proxyUid,
481 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800482 }
483 }
484 }
485 return resOps;
486 }
487
Dianne Hackbornc7214a32017-04-11 13:32:47 -0700488 private ArrayList<AppOpsManager.OpEntry> collectOps(SparseIntArray uidOps, int[] ops) {
489 ArrayList<AppOpsManager.OpEntry> resOps = null;
490 if (ops == null) {
491 resOps = new ArrayList<>();
492 for (int j=0; j<uidOps.size(); j++) {
493 resOps.add(new AppOpsManager.OpEntry(uidOps.keyAt(j), uidOps.valueAt(j),
494 0, 0, 0, -1, null));
495 }
496 } else {
497 for (int j=0; j<ops.length; j++) {
498 int index = uidOps.indexOfKey(ops[j]);
499 if (index >= 0) {
500 if (resOps == null) {
501 resOps = new ArrayList<>();
502 }
503 resOps.add(new AppOpsManager.OpEntry(uidOps.keyAt(index), uidOps.valueAt(index),
504 0, 0, 0, -1, null));
505 }
506 }
507 }
508 return resOps;
509 }
510
Dianne Hackborn35654b62013-01-14 17:38:02 -0800511 @Override
512 public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
513 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
514 Binder.getCallingPid(), Binder.getCallingUid(), null);
515 ArrayList<AppOpsManager.PackageOps> res = null;
516 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700517 final int uidStateCount = mUidStates.size();
518 for (int i = 0; i < uidStateCount; i++) {
519 UidState uidState = mUidStates.valueAt(i);
520 if (uidState.pkgOps == null || uidState.pkgOps.isEmpty()) {
521 continue;
522 }
523 ArrayMap<String, Ops> packages = uidState.pkgOps;
524 final int packageCount = packages.size();
525 for (int j = 0; j < packageCount; j++) {
526 Ops pkgOps = packages.valueAt(j);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800527 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800528 if (resOps != null) {
529 if (res == null) {
530 res = new ArrayList<AppOpsManager.PackageOps>();
531 }
532 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700533 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800534 res.add(resPackage);
535 }
536 }
537 }
538 }
539 return res;
540 }
541
542 @Override
Dianne Hackborn72e39832013-01-18 18:36:09 -0800543 public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
544 int[] ops) {
545 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
546 Binder.getCallingPid(), Binder.getCallingUid(), null);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000547 String resolvedPackageName = resolvePackageName(uid, packageName);
548 if (resolvedPackageName == null) {
549 return Collections.emptyList();
550 }
Dianne Hackborn72e39832013-01-18 18:36:09 -0800551 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -0700552 Ops pkgOps = getOpsRawLocked(uid, resolvedPackageName, false /* edit */,
553 false /* uidMismatchExpected */);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800554 if (pkgOps == null) {
555 return null;
556 }
557 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
558 if (resOps == null) {
559 return null;
560 }
561 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
562 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700563 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800564 res.add(resPackage);
565 return res;
566 }
567 }
568
Dianne Hackbornc7214a32017-04-11 13:32:47 -0700569 @Override
570 public List<AppOpsManager.PackageOps> getUidOps(int uid, int[] ops) {
571 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
572 Binder.getCallingPid(), Binder.getCallingUid(), null);
573 synchronized (this) {
574 UidState uidState = getUidStateLocked(uid, false);
575 if (uidState == null) {
576 return null;
577 }
578 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(uidState.opModes, ops);
579 if (resOps == null) {
580 return null;
581 }
582 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
583 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
584 null, uidState.uid, resOps);
585 res.add(resPackage);
586 return res;
587 }
588 }
589
Dianne Hackborn607b4142013-08-02 18:10:10 -0700590 private void pruneOp(Op op, int uid, String packageName) {
591 if (op.time == 0 && op.rejectTime == 0) {
Yohei Yukawaa965d652017-10-12 15:02:26 -0700592 Ops ops = getOpsRawLocked(uid, packageName, false /* edit */,
593 false /* uidMismatchExpected */);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700594 if (ops != null) {
595 ops.remove(op.op);
596 if (ops.size() <= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -0700597 UidState uidState = ops.uidState;
598 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700599 if (pkgOps != null) {
600 pkgOps.remove(ops.packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700601 if (pkgOps.isEmpty()) {
602 uidState.pkgOps = null;
603 }
604 if (uidState.isDefault()) {
605 mUidStates.remove(uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700606 }
607 }
608 }
609 }
610 }
611 }
612
Dianne Hackborn72e39832013-01-18 18:36:09 -0800613 @Override
Svet Ganov2af57082015-07-30 08:44:20 -0700614 public void setUidMode(int code, int uid, int mode) {
615 if (Binder.getCallingPid() != Process.myPid()) {
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -0800616 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
Svet Ganov2af57082015-07-30 08:44:20 -0700617 Binder.getCallingPid(), Binder.getCallingUid(), null);
618 }
619 verifyIncomingOp(code);
620 code = AppOpsManager.opToSwitch(code);
621
622 synchronized (this) {
623 final int defaultMode = AppOpsManager.opToDefaultMode(code);
624
625 UidState uidState = getUidStateLocked(uid, false);
626 if (uidState == null) {
627 if (mode == defaultMode) {
628 return;
629 }
630 uidState = new UidState(uid);
631 uidState.opModes = new SparseIntArray();
632 uidState.opModes.put(code, mode);
633 mUidStates.put(uid, uidState);
634 scheduleWriteLocked();
635 } else if (uidState.opModes == null) {
636 if (mode != defaultMode) {
637 uidState.opModes = new SparseIntArray();
638 uidState.opModes.put(code, mode);
639 scheduleWriteLocked();
640 }
641 } else {
642 if (uidState.opModes.get(code) == mode) {
643 return;
644 }
645 if (mode == defaultMode) {
646 uidState.opModes.delete(code);
647 if (uidState.opModes.size() <= 0) {
648 uidState.opModes = null;
649 }
650 } else {
651 uidState.opModes.put(code, mode);
652 }
653 scheduleWriteLocked();
654 }
655 }
656
Svetoslav215b44a2015-08-04 19:03:40 -0700657 String[] uidPackageNames = getPackagesForUid(uid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800658 ArrayMap<ModeCallback, ArraySet<String>> callbackSpecs = null;
Svet Ganov2af57082015-07-30 08:44:20 -0700659
riddle_hsu40b300f2015-11-23 13:22:03 +0800660 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800661 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -0700662 if (callbacks != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700663 final int callbackCount = callbacks.size();
664 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800665 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +0800666 ArraySet<String> changedPackages = new ArraySet<>();
667 Collections.addAll(changedPackages, uidPackageNames);
668 callbackSpecs = new ArrayMap<>();
669 callbackSpecs.put(callback, changedPackages);
670 }
671 }
672
673 for (String uidPackageName : uidPackageNames) {
674 callbacks = mPackageModeWatchers.get(uidPackageName);
675 if (callbacks != null) {
676 if (callbackSpecs == null) {
677 callbackSpecs = new ArrayMap<>();
Svet Ganov2af57082015-07-30 08:44:20 -0700678 }
riddle_hsu40b300f2015-11-23 13:22:03 +0800679 final int callbackCount = callbacks.size();
680 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800681 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +0800682 ArraySet<String> changedPackages = callbackSpecs.get(callback);
683 if (changedPackages == null) {
684 changedPackages = new ArraySet<>();
685 callbackSpecs.put(callback, changedPackages);
686 }
687 changedPackages.add(uidPackageName);
688 }
Svet Ganov2af57082015-07-30 08:44:20 -0700689 }
690 }
691 }
692
693 if (callbackSpecs == null) {
694 return;
695 }
696
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800697 for (int i = 0; i < callbackSpecs.size(); i++) {
698 final ModeCallback callback = callbackSpecs.keyAt(i);
699 final ArraySet<String> reportedPackageNames = callbackSpecs.valueAt(i);
700 if (reportedPackageNames == null) {
701 mHandler.sendMessage(PooledLambda.obtainMessage(
702 AppOpsService::notifyOpChanged,
703 this, callback, code, uid, (String) null));
704
705 } else {
706 final int reportedPackageCount = reportedPackageNames.size();
707 for (int j = 0; j < reportedPackageCount; j++) {
708 final String reportedPackageName = reportedPackageNames.valueAt(j);
709 mHandler.sendMessage(PooledLambda.obtainMessage(
710 AppOpsService::notifyOpChanged,
711 this, callback, code, uid, reportedPackageName));
Svet Ganov2af57082015-07-30 08:44:20 -0700712 }
713 }
Svet Ganov2af57082015-07-30 08:44:20 -0700714 }
715 }
716
717 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800718 public void setMode(int code, int uid, String packageName, int mode) {
Dianne Hackbornb64afe12014-07-22 16:29:04 -0700719 if (Binder.getCallingPid() != Process.myPid()) {
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -0800720 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
Dianne Hackbornb64afe12014-07-22 16:29:04 -0700721 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborn133b9df2014-07-01 13:06:10 -0700722 }
Dianne Hackborn961321f2013-02-05 17:22:41 -0800723 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800724 ArraySet<ModeCallback> repCbs = null;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800725 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800726 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700727 UidState uidState = getUidStateLocked(uid, false);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800728 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800729 if (op != null) {
730 if (op.mode != mode) {
731 op.mode = mode;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800732 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800733 if (cbs != null) {
734 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800735 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800736 }
737 repCbs.addAll(cbs);
738 }
739 cbs = mPackageModeWatchers.get(packageName);
740 if (cbs != null) {
741 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800742 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800743 }
744 repCbs.addAll(cbs);
745 }
David Braunf5d83192013-09-16 13:43:51 -0700746 if (mode == AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800747 // If going into the default mode, prune this op
748 // if there is nothing else interesting in it.
Dianne Hackborn607b4142013-08-02 18:10:10 -0700749 pruneOp(op, uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800750 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800751 scheduleFastWriteLocked();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800752 }
753 }
754 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800755 if (repCbs != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800756 mHandler.sendMessage(PooledLambda.obtainMessage(
757 AppOpsService::notifyOpChanged,
758 this, repCbs, code, uid, packageName));
Dianne Hackbornc2293022013-02-06 23:14:49 -0800759 }
760 }
761
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800762 private void notifyOpChanged(ArraySet<ModeCallback> callbacks, int code,
763 int uid, String packageName) {
764 for (int i = 0; i < callbacks.size(); i++) {
765 final ModeCallback callback = callbacks.valueAt(i);
766 notifyOpChanged(callback, code, uid, packageName);
767 }
768 }
769
770 private void notifyOpChanged(ModeCallback callback, int code,
771 int uid, String packageName) {
Svet Ganov3a95f832018-03-23 17:44:30 -0700772 if (uid != UID_ANY && callback.mUid >= 0 && callback.mUid != uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800773 return;
774 }
775 // There are components watching for mode changes such as window manager
776 // and location manager which are in our process. The callbacks in these
777 // components may require permissions our remote caller does not have.
778 final long identity = Binder.clearCallingIdentity();
779 try {
780 callback.mCallback.opChanged(code, uid, packageName);
781 } catch (RemoteException e) {
782 /* ignore */
783 } finally {
784 Binder.restoreCallingIdentity(identity);
785 }
786 }
787
788 private static HashMap<ModeCallback, ArrayList<ChangeRec>> addCallbacks(
789 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks,
790 int op, int uid, String packageName, ArraySet<ModeCallback> cbs) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700791 if (cbs == null) {
792 return callbacks;
793 }
794 if (callbacks == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700795 callbacks = new HashMap<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700796 }
Svet Ganov2af57082015-07-30 08:44:20 -0700797 boolean duplicate = false;
Dianne Hackborn68d76552017-02-27 15:32:03 -0800798 final int N = cbs.size();
799 for (int i=0; i<N; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800800 ModeCallback cb = cbs.valueAt(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700801 ArrayList<ChangeRec> reports = callbacks.get(cb);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700802 if (reports == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700803 reports = new ArrayList<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700804 callbacks.put(cb, reports);
Svet Ganov2af57082015-07-30 08:44:20 -0700805 } else {
806 final int reportCount = reports.size();
807 for (int j = 0; j < reportCount; j++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700808 ChangeRec report = reports.get(j);
809 if (report.op == op && report.pkg.equals(packageName)) {
Svet Ganov2af57082015-07-30 08:44:20 -0700810 duplicate = true;
811 break;
812 }
813 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700814 }
Svet Ganov2af57082015-07-30 08:44:20 -0700815 if (!duplicate) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700816 reports.add(new ChangeRec(op, uid, packageName));
Svet Ganov2af57082015-07-30 08:44:20 -0700817 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700818 }
819 return callbacks;
820 }
821
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700822 static final class ChangeRec {
823 final int op;
824 final int uid;
825 final String pkg;
826
827 ChangeRec(int _op, int _uid, String _pkg) {
828 op = _op;
829 uid = _uid;
830 pkg = _pkg;
831 }
832 }
833
Dianne Hackborn607b4142013-08-02 18:10:10 -0700834 @Override
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800835 public void resetAllModes(int reqUserId, String reqPackageName) {
836 final int callingPid = Binder.getCallingPid();
837 final int callingUid = Binder.getCallingUid();
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -0800838 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800839 callingPid, callingUid, null);
840 reqUserId = ActivityManager.handleIncomingUser(callingPid, callingUid, reqUserId,
841 true, true, "resetAllModes", null);
Svet Ganov2af57082015-07-30 08:44:20 -0700842
843 int reqUid = -1;
844 if (reqPackageName != null) {
845 try {
846 reqUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -0700847 reqPackageName, PackageManager.MATCH_UNINSTALLED_PACKAGES, reqUserId);
Svet Ganov2af57082015-07-30 08:44:20 -0700848 } catch (RemoteException e) {
849 /* ignore - local call */
850 }
851 }
852
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800853 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks = null;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700854 synchronized (this) {
855 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700856 for (int i = mUidStates.size() - 1; i >= 0; i--) {
857 UidState uidState = mUidStates.valueAt(i);
858
859 SparseIntArray opModes = uidState.opModes;
860 if (opModes != null && (uidState.uid == reqUid || reqUid == -1)) {
861 final int uidOpCount = opModes.size();
862 for (int j = uidOpCount - 1; j >= 0; j--) {
863 final int code = opModes.keyAt(j);
864 if (AppOpsManager.opAllowsReset(code)) {
865 opModes.removeAt(j);
866 if (opModes.size() <= 0) {
867 uidState.opModes = null;
868 }
869 for (String packageName : getPackagesForUid(uidState.uid)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700870 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700871 mOpModeWatchers.get(code));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700872 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700873 mPackageModeWatchers.get(packageName));
874 }
875 }
876 }
877 }
878
879 if (uidState.pkgOps == null) {
880 continue;
881 }
882
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800883 if (reqUserId != UserHandle.USER_ALL
Svet Ganov2af57082015-07-30 08:44:20 -0700884 && reqUserId != UserHandle.getUserId(uidState.uid)) {
Alexandra Gherghinad6a98972014-08-04 17:05:34 +0100885 // Skip any ops for a different user
886 continue;
887 }
Svet Ganov2af57082015-07-30 08:44:20 -0700888
889 Map<String, Ops> packages = uidState.pkgOps;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700890 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
891 while (it.hasNext()) {
892 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700893 String packageName = ent.getKey();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800894 if (reqPackageName != null && !reqPackageName.equals(packageName)) {
895 // Skip any ops for a different package
896 continue;
897 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700898 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700899 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700900 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -0700901 if (AppOpsManager.opAllowsReset(curOp.op)
902 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -0700903 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700904 changed = true;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700905 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -0700906 mOpModeWatchers.get(curOp.op));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700907 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -0700908 mPackageModeWatchers.get(packageName));
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700909 if (curOp.time == 0 && curOp.rejectTime == 0) {
910 pkgOps.removeAt(j);
911 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700912 }
913 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700914 if (pkgOps.size() == 0) {
915 it.remove();
916 }
917 }
Svet Ganov2af57082015-07-30 08:44:20 -0700918 if (uidState.isDefault()) {
919 mUidStates.remove(uidState.uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700920 }
921 }
Svet Ganov2af57082015-07-30 08:44:20 -0700922
Dianne Hackborn607b4142013-08-02 18:10:10 -0700923 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800924 scheduleFastWriteLocked();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700925 }
926 }
927 if (callbacks != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800928 for (Map.Entry<ModeCallback, ArrayList<ChangeRec>> ent : callbacks.entrySet()) {
929 ModeCallback cb = ent.getKey();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700930 ArrayList<ChangeRec> reports = ent.getValue();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700931 for (int i=0; i<reports.size(); i++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700932 ChangeRec rep = reports.get(i);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800933 mHandler.sendMessage(PooledLambda.obtainMessage(
934 AppOpsService::notifyOpChanged,
935 this, cb, rep.op, rep.uid, rep.pkg));
Dianne Hackborn607b4142013-08-02 18:10:10 -0700936 }
937 }
938 }
939 }
940
Dianne Hackbornc2293022013-02-06 23:14:49 -0800941 @Override
942 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800943 int watchedUid = -1;
944 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
945 != PackageManager.PERMISSION_GRANTED) {
946 watchedUid = Binder.getCallingUid();
947 }
948 Preconditions.checkArgumentInRange(op, AppOpsManager.OP_NONE,
949 AppOpsManager._NUM_OP - 1, "Invalid op code: " + op);
Svetoslav Ganov8de59712015-12-09 18:25:13 -0800950 if (callback == null) {
951 return;
952 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800953 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700954 op = (op != AppOpsManager.OP_NONE) ? AppOpsManager.opToSwitch(op) : op;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800955 ModeCallback cb = mModeWatchers.get(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -0800956 if (cb == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800957 cb = new ModeCallback(callback, watchedUid);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800958 mModeWatchers.put(callback.asBinder(), cb);
959 }
960 if (op != AppOpsManager.OP_NONE) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800961 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(op);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800962 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800963 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800964 mOpModeWatchers.put(op, cbs);
965 }
966 cbs.add(cb);
967 }
968 if (packageName != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800969 ArraySet<ModeCallback> cbs = mPackageModeWatchers.get(packageName);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800970 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800971 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800972 mPackageModeWatchers.put(packageName, cbs);
973 }
974 cbs.add(cb);
975 }
976 }
977 }
978
979 @Override
980 public void stopWatchingMode(IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -0800981 if (callback == null) {
982 return;
983 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800984 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800985 ModeCallback cb = mModeWatchers.remove(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -0800986 if (cb != null) {
987 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700988 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800989 ArraySet<ModeCallback> cbs = mOpModeWatchers.valueAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800990 cbs.remove(cb);
991 if (cbs.size() <= 0) {
992 mOpModeWatchers.removeAt(i);
993 }
994 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700995 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800996 ArraySet<ModeCallback> cbs = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700997 cbs.remove(cb);
998 if (cbs.size() <= 0) {
999 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001000 }
1001 }
1002 }
1003 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001004 }
1005
1006 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001007 public IBinder getToken(IBinder clientToken) {
1008 synchronized (this) {
1009 ClientState cs = mClients.get(clientToken);
1010 if (cs == null) {
1011 cs = new ClientState(clientToken);
1012 mClients.put(clientToken, cs);
1013 }
1014 return cs;
1015 }
1016 }
1017
1018 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -08001019 public int checkOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001020 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001021 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001022 String resolvedPackageName = resolvePackageName(uid, packageName);
1023 if (resolvedPackageName == null) {
1024 return AppOpsManager.MODE_IGNORED;
1025 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001026 synchronized (this) {
Svet Ganov442ed572016-08-17 17:29:43 -07001027 if (isOpRestrictedLocked(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001028 return AppOpsManager.MODE_IGNORED;
1029 }
Svet Ganov2af57082015-07-30 08:44:20 -07001030 code = AppOpsManager.opToSwitch(code);
1031 UidState uidState = getUidStateLocked(uid, false);
Svet Ganovee438d42017-01-19 18:04:38 -08001032 if (uidState != null && uidState.opModes != null
1033 && uidState.opModes.indexOfKey(code) >= 0) {
1034 return uidState.opModes.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001035 }
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001036 Op op = getOpLocked(code, uid, resolvedPackageName, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001037 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -07001038 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001039 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001040 return op.mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001041 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001042 }
1043
1044 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001045 public int checkAudioOperation(int code, int usage, int uid, String packageName) {
Andrei Stingaceanuefc4a342016-03-22 14:43:01 +00001046 boolean suspended;
1047 try {
1048 suspended = isPackageSuspendedForUser(packageName, uid);
1049 } catch (IllegalArgumentException ex) {
1050 // Package not found.
1051 suspended = false;
1052 }
1053
1054 if (suspended) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001055 Slog.i(TAG, "Audio disabled for suspended package=" + packageName + " for uid=" + uid);
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001056 return AppOpsManager.MODE_IGNORED;
1057 }
1058
John Spurlock1af30c72014-03-10 08:33:35 -04001059 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001060 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -04001061 if (mode != AppOpsManager.MODE_ALLOWED) {
1062 return mode;
1063 }
1064 }
1065 return checkOperation(code, uid, packageName);
1066 }
1067
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001068 private boolean isPackageSuspendedForUser(String pkg, int uid) {
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001069 try {
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001070 return AppGlobals.getPackageManager().isPackageSuspendedForUser(
1071 pkg, UserHandle.getUserId(uid));
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001072 } catch (RemoteException re) {
1073 throw new SecurityException("Could not talk to package manager service");
1074 }
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001075 }
1076
John Spurlock7b414672014-07-18 13:02:39 -04001077 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
1078 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1079 if (usageRestrictions != null) {
1080 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001081 if (r != null && !r.exceptionPackages.contains(packageName)) {
1082 return r.mode;
1083 }
1084 }
1085 return AppOpsManager.MODE_ALLOWED;
1086 }
1087
1088 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001089 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -04001090 String[] exceptionPackages) {
1091 verifyIncomingUid(uid);
1092 verifyIncomingOp(code);
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -08001093 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
1094 Binder.getCallingPid(), Binder.getCallingUid(), null);
John Spurlock1af30c72014-03-10 08:33:35 -04001095 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001096 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1097 if (usageRestrictions == null) {
1098 usageRestrictions = new SparseArray<Restriction>();
1099 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -04001100 }
John Spurlock7b414672014-07-18 13:02:39 -04001101 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001102 if (mode != AppOpsManager.MODE_ALLOWED) {
1103 final Restriction r = new Restriction();
1104 r.mode = mode;
1105 if (exceptionPackages != null) {
1106 final int N = exceptionPackages.length;
1107 r.exceptionPackages = new ArraySet<String>(N);
1108 for (int i = 0; i < N; i++) {
1109 final String pkg = exceptionPackages[i];
1110 if (pkg != null) {
1111 r.exceptionPackages.add(pkg.trim());
1112 }
1113 }
1114 }
John Spurlock7b414672014-07-18 13:02:39 -04001115 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -04001116 }
1117 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001118
1119 mHandler.sendMessage(PooledLambda.obtainMessage(
Svet Ganov3a95f832018-03-23 17:44:30 -07001120 AppOpsService::notifyWatchersOfChange, this, code, UID_ANY));
John Spurlock1af30c72014-03-10 08:33:35 -04001121 }
1122
1123 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001124 public int checkPackage(int uid, String packageName) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001125 Preconditions.checkNotNull(packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001126 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001127 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1128 true /* uidMismatchExpected */);
1129 if (ops != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001130 return AppOpsManager.MODE_ALLOWED;
1131 } else {
1132 return AppOpsManager.MODE_ERRORED;
1133 }
1134 }
1135 }
1136
1137 @Override
Svet Ganov99b60432015-06-27 13:15:22 -07001138 public int noteProxyOperation(int code, String proxyPackageName,
1139 int proxiedUid, String proxiedPackageName) {
1140 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001141 final int proxyUid = Binder.getCallingUid();
1142 String resolveProxyPackageName = resolvePackageName(proxyUid, proxyPackageName);
1143 if (resolveProxyPackageName == null) {
1144 return AppOpsManager.MODE_IGNORED;
1145 }
1146 final int proxyMode = noteOperationUnchecked(code, proxyUid,
1147 resolveProxyPackageName, -1, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001148 if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
1149 return proxyMode;
1150 }
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001151 String resolveProxiedPackageName = resolvePackageName(proxiedUid, proxiedPackageName);
1152 if (resolveProxiedPackageName == null) {
1153 return AppOpsManager.MODE_IGNORED;
1154 }
1155 return noteOperationUnchecked(code, proxiedUid, resolveProxiedPackageName,
1156 proxyMode, resolveProxyPackageName);
Svet Ganov99b60432015-06-27 13:15:22 -07001157 }
1158
1159 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001160 public int noteOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001161 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001162 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001163 String resolvedPackageName = resolvePackageName(uid, packageName);
1164 if (resolvedPackageName == null) {
1165 return AppOpsManager.MODE_IGNORED;
1166 }
1167 return noteOperationUnchecked(code, uid, resolvedPackageName, 0, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001168 }
1169
1170 private int noteOperationUnchecked(int code, int uid, String packageName,
1171 int proxyUid, String proxyPackageName) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001172 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001173 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1174 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001175 if (ops == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001176 if (DEBUG) Slog.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001177 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001178 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001179 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001180 Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07001181 if (isOpRestrictedLocked(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001182 return AppOpsManager.MODE_IGNORED;
1183 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001184 if (op.duration == -1) {
1185 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
1186 + " code " + code + " time=" + op.time + " duration=" + op.duration);
1187 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001188 op.duration = 0;
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001189 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001190 UidState uidState = ops.uidState;
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001191 // If there is a non-default per UID policy (we set UID op mode only if
1192 // non-default) it takes over, otherwise use the per package policy.
1193 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -07001194 final int uidMode = uidState.opModes.get(switchCode);
1195 if (uidMode != AppOpsManager.MODE_ALLOWED) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001196 if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + op.mode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07001197 + switchCode + " (" + code + ") uid " + uid + " package "
1198 + packageName);
1199 op.rejectTime = System.currentTimeMillis();
1200 return uidMode;
1201 }
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001202 } else {
1203 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
1204 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001205 if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + op.mode + " for code "
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001206 + switchCode + " (" + code + ") uid " + uid + " package "
1207 + packageName);
1208 op.rejectTime = System.currentTimeMillis();
1209 return switchOp.mode;
1210 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001211 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001212 if (DEBUG) Slog.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001213 + " package " + packageName);
1214 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001215 op.rejectTime = 0;
Svet Ganov99b60432015-06-27 13:15:22 -07001216 op.proxyUid = proxyUid;
1217 op.proxyPackageName = proxyPackageName;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001218 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001219 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001220 }
1221
1222 @Override
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001223 public void startWatchingActive(int[] ops, IAppOpsActiveCallback callback) {
Svet Ganovf7b47252018-02-26 11:11:27 -08001224 int watchedUid = -1;
1225 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
1226 != PackageManager.PERMISSION_GRANTED) {
1227 watchedUid = Binder.getCallingUid();
1228 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001229 if (ops != null) {
1230 Preconditions.checkArrayElementsInRange(ops, 0,
1231 AppOpsManager._NUM_OP - 1, "Invalid op code in: " + Arrays.toString(ops));
1232 }
1233 if (callback == null) {
1234 return;
1235 }
1236 synchronized (this) {
1237 SparseArray<ActiveCallback> callbacks = mActiveWatchers.get(callback.asBinder());
1238 if (callbacks == null) {
1239 callbacks = new SparseArray<>();
1240 mActiveWatchers.put(callback.asBinder(), callbacks);
1241 }
Svet Ganovf7b47252018-02-26 11:11:27 -08001242 final ActiveCallback activeCallback = new ActiveCallback(callback, watchedUid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001243 for (int op : ops) {
1244 callbacks.put(op, activeCallback);
1245 }
1246 }
1247 }
1248
1249 @Override
1250 public void stopWatchingActive(IAppOpsActiveCallback callback) {
1251 if (callback == null) {
1252 return;
1253 }
1254 synchronized (this) {
1255 final SparseArray<ActiveCallback> activeCallbacks =
1256 mActiveWatchers.remove(callback.asBinder());
1257 if (activeCallbacks == null) {
1258 return;
1259 }
1260 final int callbackCount = activeCallbacks.size();
1261 for (int i = 0; i < callbackCount; i++) {
1262 // Apps ops are mapped to a singleton
1263 if (i == 0) {
1264 activeCallbacks.valueAt(i).destroy();
1265 }
1266 }
1267 }
1268 }
1269
1270 @Override
Svet Ganovf7b47252018-02-26 11:11:27 -08001271 public int startOperation(IBinder token, int code, int uid, String packageName,
1272 boolean startIfModeDefault) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001273 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001274 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001275 String resolvedPackageName = resolvePackageName(uid, packageName);
1276 if (resolvedPackageName == null) {
1277 return AppOpsManager.MODE_IGNORED;
1278 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001279 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001280 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001281 Ops ops = getOpsRawLocked(uid, resolvedPackageName, true /* edit */,
1282 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001283 if (ops == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001284 if (DEBUG) Slog.d(TAG, "startOperation: no op for code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001285 + " package " + resolvedPackageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001286 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001287 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001288 Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07001289 if (isOpRestrictedLocked(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001290 return AppOpsManager.MODE_IGNORED;
1291 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001292 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001293 UidState uidState = ops.uidState;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001294 // If there is a non-default per UID policy (we set UID op mode only if
1295 // non-default) it takes over, otherwise use the per package policy.
1296 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -07001297 final int uidMode = uidState.opModes.get(switchCode);
Svet Ganovf7b47252018-02-26 11:11:27 -08001298 if (uidMode != AppOpsManager.MODE_ALLOWED
1299 && (!startIfModeDefault || uidMode != AppOpsManager.MODE_DEFAULT)) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001300 if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + op.mode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07001301 + switchCode + " (" + code + ") uid " + uid + " package "
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001302 + resolvedPackageName);
Svet Ganov2af57082015-07-30 08:44:20 -07001303 op.rejectTime = System.currentTimeMillis();
1304 return uidMode;
1305 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001306 } else {
1307 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
Svet Ganovf7b47252018-02-26 11:11:27 -08001308 if (switchOp.mode != AppOpsManager.MODE_ALLOWED
1309 && (!startIfModeDefault || switchOp.mode != AppOpsManager.MODE_DEFAULT)) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001310 if (DEBUG) Slog.d(TAG, "startOperation: reject #" + op.mode + " for code "
1311 + switchCode + " (" + code + ") uid " + uid + " package "
1312 + resolvedPackageName);
1313 op.rejectTime = System.currentTimeMillis();
1314 return switchOp.mode;
1315 }
Svet Ganov2af57082015-07-30 08:44:20 -07001316 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001317 if (DEBUG) Slog.d(TAG, "startOperation: allowing code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001318 + " package " + resolvedPackageName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001319 if (op.nesting == 0) {
1320 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001321 op.rejectTime = 0;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001322 op.duration = -1;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001323 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001324 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001325 op.nesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001326 if (client.mStartedOps != null) {
1327 client.mStartedOps.add(op);
1328 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001329 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001330
1331 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001332 }
1333
1334 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001335 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001336 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001337 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001338 String resolvedPackageName = resolvePackageName(uid, packageName);
1339 if (resolvedPackageName == null) {
1340 return;
1341 }
1342 if (!(token instanceof ClientState)) {
1343 return;
1344 }
1345 ClientState client = (ClientState) token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001346 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001347 Op op = getOpLocked(code, uid, resolvedPackageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001348 if (op == null) {
1349 return;
1350 }
Svet Ganovf7b47252018-02-26 11:11:27 -08001351 if (!client.mStartedOps.remove(op)) {
Svet Ganovf5d5af12018-03-18 11:51:17 -07001352 // We finish ops when packages get removed to guarantee no dangling
1353 // started ops. However, some part of the system may asynchronously
1354 // finish ops for an already gone package. Hence, finishing an op
1355 // for a non existing package is fine and we don't log as a wtf.
1356 final long identity = Binder.clearCallingIdentity();
1357 try {
1358 if (LocalServices.getService(PackageManagerInternal.class).getPackageUid(
1359 resolvedPackageName, 0, UserHandle.getUserId(uid)) < 0) {
1360 Slog.i(TAG, "Finishing op=" + AppOpsManager.opToName(code)
1361 + " for non-existing package=" + resolvedPackageName
1362 + " in uid=" + uid);
1363 return;
1364 }
1365 } finally {
1366 Binder.restoreCallingIdentity(identity);
1367 }
1368 Slog.wtf(TAG, "Operation not started: uid=" + op.uid + " pkg="
1369 + op.packageName + " op=" + AppOpsManager.opToName(op.op));
Svet Ganov31d83ae2018-03-15 10:45:56 -07001370 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001371 }
Svet Ganova7a0db62018-02-27 20:08:01 -08001372 finishOperationLocked(op, /*finishNested*/ false);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001373 if (op.nesting <= 0) {
1374 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, false);
1375 }
1376 }
1377 }
1378
1379 private void scheduleOpActiveChangedIfNeededLocked(int code, int uid, String packageName,
1380 boolean active) {
1381 ArraySet<ActiveCallback> dispatchedCallbacks = null;
1382 final int callbackListCount = mActiveWatchers.size();
1383 for (int i = 0; i < callbackListCount; i++) {
1384 final SparseArray<ActiveCallback> callbacks = mActiveWatchers.valueAt(i);
1385 ActiveCallback callback = callbacks.get(code);
1386 if (callback != null) {
Svet Ganovf7b47252018-02-26 11:11:27 -08001387 if (callback.mUid >= 0 && callback.mUid != uid) {
1388 continue;
1389 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001390 if (dispatchedCallbacks == null) {
1391 dispatchedCallbacks = new ArraySet<>();
1392 }
1393 dispatchedCallbacks.add(callback);
1394 }
1395 }
1396 if (dispatchedCallbacks == null) {
1397 return;
1398 }
1399 mHandler.sendMessage(PooledLambda.obtainMessage(
1400 AppOpsService::notifyOpActiveChanged,
1401 this, dispatchedCallbacks, code, uid, packageName, active));
1402 }
1403
1404 private void notifyOpActiveChanged(ArraySet<ActiveCallback> callbacks,
1405 int code, int uid, String packageName, boolean active) {
1406 // There are components watching for mode changes such as window manager
1407 // and location manager which are in our process. The callbacks in these
1408 // components may require permissions our remote caller does not have.
1409 final long identity = Binder.clearCallingIdentity();
1410 try {
1411 final int callbackCount = callbacks.size();
1412 for (int i = 0; i < callbackCount; i++) {
1413 final ActiveCallback callback = callbacks.valueAt(i);
1414 try {
1415 callback.mCallback.opActiveChanged(code, uid, packageName, active);
1416 } catch (RemoteException e) {
1417 /* do nothing */
1418 }
1419 }
1420 } finally {
1421 Binder.restoreCallingIdentity(identity);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001422 }
1423 }
1424
Svet Ganovb9d71a62015-04-30 10:38:13 -07001425 @Override
1426 public int permissionToOpCode(String permission) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001427 if (permission == null) {
1428 return AppOpsManager.OP_NONE;
1429 }
Svet Ganovb9d71a62015-04-30 10:38:13 -07001430 return AppOpsManager.permissionToOpCode(permission);
1431 }
1432
Svet Ganova7a0db62018-02-27 20:08:01 -08001433 void finishOperationLocked(Op op, boolean finishNested) {
1434 if (op.nesting <= 1 || finishNested) {
1435 if (op.nesting == 1 || finishNested) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001436 op.duration = (int)(System.currentTimeMillis() - op.time);
1437 op.time += op.duration;
1438 } else {
1439 Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
1440 + op.packageName + " code " + op.op + " time=" + op.time
1441 + " duration=" + op.duration + " nesting=" + op.nesting);
1442 }
1443 op.nesting = 0;
1444 } else {
1445 op.nesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001446 }
1447 }
1448
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001449 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001450 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001451 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001452 }
1453 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001454 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001455 }
1456 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
1457 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001458 }
1459
Dianne Hackborn961321f2013-02-05 17:22:41 -08001460 private void verifyIncomingOp(int op) {
1461 if (op >= 0 && op < AppOpsManager._NUM_OP) {
1462 return;
1463 }
1464 throw new IllegalArgumentException("Bad operation #" + op);
1465 }
1466
Svet Ganov2af57082015-07-30 08:44:20 -07001467 private UidState getUidStateLocked(int uid, boolean edit) {
1468 UidState uidState = mUidStates.get(uid);
1469 if (uidState == null) {
1470 if (!edit) {
1471 return null;
1472 }
1473 uidState = new UidState(uid);
1474 mUidStates.put(uid, uidState);
1475 }
1476 return uidState;
1477 }
1478
Yohei Yukawaa965d652017-10-12 15:02:26 -07001479 private Ops getOpsRawLocked(int uid, String packageName, boolean edit,
1480 boolean uidMismatchExpected) {
Svet Ganov2af57082015-07-30 08:44:20 -07001481 UidState uidState = getUidStateLocked(uid, edit);
1482 if (uidState == null) {
1483 return null;
1484 }
1485
1486 if (uidState.pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001487 if (!edit) {
1488 return null;
1489 }
Svet Ganov2af57082015-07-30 08:44:20 -07001490 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001491 }
Svet Ganov2af57082015-07-30 08:44:20 -07001492
1493 Ops ops = uidState.pkgOps.get(packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001494 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001495 if (!edit) {
1496 return null;
1497 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001498 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001499 // This is the first time we have seen this package name under this uid,
1500 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -08001501 if (uid != 0) {
1502 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001503 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001504 int pkgUid = -1;
1505 try {
Jason Monk1c7c3192014-06-26 12:52:18 -04001506 ApplicationInfo appInfo = ActivityThread.getPackageManager()
Jeff Sharkeycd654482016-01-08 17:42:11 -07001507 .getApplicationInfo(packageName,
1508 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1509 UserHandle.getUserId(uid));
Jason Monk1c7c3192014-06-26 12:52:18 -04001510 if (appInfo != null) {
1511 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001512 isPrivileged = (appInfo.privateFlags
1513 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001514 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08001515 pkgUid = resolveUid(packageName);
1516 if (pkgUid >= 0) {
Chien-Yu Chen75cade02016-01-11 10:56:21 -08001517 isPrivileged = false;
Jason Monk1c7c3192014-06-26 12:52:18 -04001518 }
Dianne Hackborn713df152013-05-17 11:27:57 -07001519 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001520 } catch (RemoteException e) {
1521 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001522 }
1523 if (pkgUid != uid) {
1524 // Oops! The package name is not valid for the uid they are calling
1525 // under. Abort.
Yohei Yukawaa965d652017-10-12 15:02:26 -07001526 if (!uidMismatchExpected) {
1527 RuntimeException ex = new RuntimeException("here");
1528 ex.fillInStackTrace();
1529 Slog.w(TAG, "Bad call: specified package " + packageName
1530 + " under uid " + uid + " but it is really " + pkgUid, ex);
1531 }
Dianne Hackborn514074f2013-02-11 10:52:46 -08001532 return null;
1533 }
1534 } finally {
1535 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001536 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001537 }
Svet Ganov2af57082015-07-30 08:44:20 -07001538 ops = new Ops(packageName, uidState, isPrivileged);
1539 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001540 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08001541 return ops;
1542 }
1543
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001544 private void scheduleWriteLocked() {
1545 if (!mWriteScheduled) {
1546 mWriteScheduled = true;
1547 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
1548 }
1549 }
1550
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001551 private void scheduleFastWriteLocked() {
1552 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001553 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001554 mFastWriteScheduled = true;
1555 mHandler.removeCallbacks(mWriteRunner);
1556 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001557 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001558 }
1559
Dianne Hackborn72e39832013-01-18 18:36:09 -08001560 private Op getOpLocked(int code, int uid, String packageName, boolean edit) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001561 Ops ops = getOpsRawLocked(uid, packageName, edit,
1562 false /* uidMismatchExpected */);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001563 if (ops == null) {
1564 return null;
1565 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001566 return getOpLocked(ops, code, edit);
1567 }
1568
1569 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001570 Op op = ops.get(code);
1571 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001572 if (!edit) {
1573 return null;
1574 }
Svet Ganov2af57082015-07-30 08:44:20 -07001575 op = new Op(ops.uidState.uid, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001576 ops.put(code, op);
1577 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001578 if (edit) {
1579 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001580 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001581 return op;
1582 }
1583
Svet Ganov442ed572016-08-17 17:29:43 -07001584 private boolean isOpRestrictedLocked(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04001585 int userHandle = UserHandle.getUserId(uid);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001586 final int restrictionSetCount = mOpUserRestrictions.size();
Ruben Brunk29931bc2016-03-11 00:24:26 -08001587
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001588 for (int i = 0; i < restrictionSetCount; i++) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08001589 // For each client, check that the given op is not restricted, or that the given
1590 // package is exempt from the restriction.
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07001591 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07001592 if (restrictionState.hasRestriction(code, packageName, userHandle)) {
1593 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
1594 // If we are the system, bypass user restrictions for certain codes
1595 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001596 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1597 false /* uidMismatchExpected */);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07001598 if ((ops != null) && ops.isPrivileged) {
1599 return false;
1600 }
Ruben Brunk32f0fa42016-03-11 19:07:07 -08001601 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08001602 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001603 return true;
Jason Monk1c7c3192014-06-26 12:52:18 -04001604 }
Jason Monk62062992014-05-06 09:55:28 -04001605 }
1606 return false;
1607 }
1608
Dianne Hackborn35654b62013-01-14 17:38:02 -08001609 void readState() {
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001610 int oldVersion = NO_VERSION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001611 synchronized (mFile) {
1612 synchronized (this) {
1613 FileInputStream stream;
1614 try {
1615 stream = mFile.openRead();
1616 } catch (FileNotFoundException e) {
1617 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
1618 return;
1619 }
1620 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001621 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001622 try {
1623 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001624 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001625 int type;
1626 while ((type = parser.next()) != XmlPullParser.START_TAG
1627 && type != XmlPullParser.END_DOCUMENT) {
1628 ;
1629 }
1630
1631 if (type != XmlPullParser.START_TAG) {
1632 throw new IllegalStateException("no start tag found");
1633 }
1634
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001635 final String versionString = parser.getAttributeValue(null, "v");
1636 if (versionString != null) {
1637 oldVersion = Integer.parseInt(versionString);
1638 }
1639
Dianne Hackborn35654b62013-01-14 17:38:02 -08001640 int outerDepth = parser.getDepth();
1641 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1642 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1643 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1644 continue;
1645 }
1646
1647 String tagName = parser.getName();
1648 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001649 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07001650 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07001651 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001652 } else {
1653 Slog.w(TAG, "Unknown element under <app-ops>: "
1654 + parser.getName());
1655 XmlUtils.skipCurrentTag(parser);
1656 }
1657 }
1658 success = true;
1659 } catch (IllegalStateException e) {
1660 Slog.w(TAG, "Failed parsing " + e);
1661 } catch (NullPointerException e) {
1662 Slog.w(TAG, "Failed parsing " + e);
1663 } catch (NumberFormatException e) {
1664 Slog.w(TAG, "Failed parsing " + e);
1665 } catch (XmlPullParserException e) {
1666 Slog.w(TAG, "Failed parsing " + e);
1667 } catch (IOException e) {
1668 Slog.w(TAG, "Failed parsing " + e);
1669 } catch (IndexOutOfBoundsException e) {
1670 Slog.w(TAG, "Failed parsing " + e);
1671 } finally {
1672 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07001673 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001674 }
1675 try {
1676 stream.close();
1677 } catch (IOException e) {
1678 }
1679 }
1680 }
1681 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001682 synchronized (this) {
1683 upgradeLocked(oldVersion);
1684 }
1685 }
1686
1687 private void upgradeRunAnyInBackgroundLocked() {
1688 for (int i = 0; i < mUidStates.size(); i++) {
1689 final UidState uidState = mUidStates.valueAt(i);
1690 if (uidState == null) {
1691 continue;
1692 }
1693 if (uidState.opModes != null) {
1694 final int idx = uidState.opModes.indexOfKey(AppOpsManager.OP_RUN_IN_BACKGROUND);
1695 if (idx >= 0) {
1696 uidState.opModes.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND,
1697 uidState.opModes.valueAt(idx));
1698 }
1699 }
1700 if (uidState.pkgOps == null) {
1701 continue;
1702 }
1703 for (int j = 0; j < uidState.pkgOps.size(); j++) {
1704 Ops ops = uidState.pkgOps.valueAt(j);
1705 if (ops != null) {
1706 final Op op = ops.get(AppOpsManager.OP_RUN_IN_BACKGROUND);
1707 if (op != null && op.mode != AppOpsManager.opToDefaultMode(op.op)) {
1708 final Op copy = new Op(op.uid, op.packageName,
1709 AppOpsManager.OP_RUN_ANY_IN_BACKGROUND);
1710 copy.mode = op.mode;
1711 ops.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, copy);
1712 }
1713 }
1714 }
1715 }
1716 }
1717
1718 private void upgradeLocked(int oldVersion) {
1719 if (oldVersion >= CURRENT_VERSION) {
1720 return;
1721 }
1722 Slog.d(TAG, "Upgrading app-ops xml from version " + oldVersion + " to " + CURRENT_VERSION);
1723 switch (oldVersion) {
1724 case NO_VERSION:
1725 upgradeRunAnyInBackgroundLocked();
1726 // fall through
1727 case 1:
1728 // for future upgrades
1729 }
1730 scheduleFastWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001731 }
1732
Svet Ganov2af57082015-07-30 08:44:20 -07001733 void readUidOps(XmlPullParser parser) throws NumberFormatException,
1734 XmlPullParserException, IOException {
1735 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
1736 int outerDepth = parser.getDepth();
1737 int type;
1738 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1739 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1740 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1741 continue;
1742 }
1743
1744 String tagName = parser.getName();
1745 if (tagName.equals("op")) {
1746 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
1747 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
1748 UidState uidState = getUidStateLocked(uid, true);
1749 if (uidState.opModes == null) {
1750 uidState.opModes = new SparseIntArray();
1751 }
1752 uidState.opModes.put(code, mode);
1753 } else {
1754 Slog.w(TAG, "Unknown element under <uid-ops>: "
1755 + parser.getName());
1756 XmlUtils.skipCurrentTag(parser);
1757 }
1758 }
1759 }
1760
Dave Burke0997c5bd2013-08-02 20:25:02 +00001761 void readPackage(XmlPullParser parser) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001762 XmlPullParserException, IOException {
1763 String pkgName = parser.getAttributeValue(null, "n");
1764 int outerDepth = parser.getDepth();
1765 int type;
1766 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1767 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1768 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1769 continue;
1770 }
1771
1772 String tagName = parser.getName();
1773 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001774 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001775 } else {
1776 Slog.w(TAG, "Unknown element under <pkg>: "
1777 + parser.getName());
1778 XmlUtils.skipCurrentTag(parser);
1779 }
1780 }
1781 }
1782
Dave Burke0997c5bd2013-08-02 20:25:02 +00001783 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001784 XmlPullParserException, IOException {
1785 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Jason Monk1c7c3192014-06-26 12:52:18 -04001786 String isPrivilegedString = parser.getAttributeValue(null, "p");
1787 boolean isPrivileged = false;
1788 if (isPrivilegedString == null) {
1789 try {
1790 IPackageManager packageManager = ActivityThread.getPackageManager();
1791 if (packageManager != null) {
1792 ApplicationInfo appInfo = ActivityThread.getPackageManager()
1793 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
1794 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001795 isPrivileged = (appInfo.privateFlags
1796 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001797 }
1798 } else {
1799 // Could not load data, don't add to cache so it will be loaded later.
1800 return;
1801 }
1802 } catch (RemoteException e) {
1803 Slog.w(TAG, "Could not contact PackageManager", e);
1804 }
1805 } else {
1806 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
1807 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001808 int outerDepth = parser.getDepth();
1809 int type;
1810 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1811 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1812 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1813 continue;
1814 }
1815
1816 String tagName = parser.getName();
1817 if (tagName.equals("op")) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001818 Op op = new Op(uid, pkgName, Integer.parseInt(parser.getAttributeValue(null, "n")));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001819 String mode = parser.getAttributeValue(null, "m");
1820 if (mode != null) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001821 op.mode = Integer.parseInt(mode);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001822 }
1823 String time = parser.getAttributeValue(null, "t");
1824 if (time != null) {
1825 op.time = Long.parseLong(time);
1826 }
1827 time = parser.getAttributeValue(null, "r");
1828 if (time != null) {
1829 op.rejectTime = Long.parseLong(time);
1830 }
1831 String dur = parser.getAttributeValue(null, "d");
1832 if (dur != null) {
1833 op.duration = Integer.parseInt(dur);
1834 }
Svet Ganov99b60432015-06-27 13:15:22 -07001835 String proxyUid = parser.getAttributeValue(null, "pu");
1836 if (proxyUid != null) {
1837 op.proxyUid = Integer.parseInt(proxyUid);
1838 }
1839 String proxyPackageName = parser.getAttributeValue(null, "pp");
1840 if (proxyPackageName != null) {
1841 op.proxyPackageName = proxyPackageName;
1842 }
Svet Ganov2af57082015-07-30 08:44:20 -07001843
1844 UidState uidState = getUidStateLocked(uid, true);
1845 if (uidState.pkgOps == null) {
1846 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001847 }
Svet Ganov2af57082015-07-30 08:44:20 -07001848
1849 Ops ops = uidState.pkgOps.get(pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001850 if (ops == null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001851 ops = new Ops(pkgName, uidState, isPrivileged);
1852 uidState.pkgOps.put(pkgName, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001853 }
1854 ops.put(op.op, op);
1855 } else {
1856 Slog.w(TAG, "Unknown element under <pkg>: "
1857 + parser.getName());
1858 XmlUtils.skipCurrentTag(parser);
1859 }
1860 }
1861 }
1862
1863 void writeState() {
1864 synchronized (mFile) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001865 FileOutputStream stream;
1866 try {
1867 stream = mFile.startWrite();
1868 } catch (IOException e) {
1869 Slog.w(TAG, "Failed to write state: " + e);
1870 return;
1871 }
1872
Dianne Hackborne17b4452018-01-10 13:15:40 -08001873 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
1874
Dianne Hackborn35654b62013-01-14 17:38:02 -08001875 try {
1876 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001877 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001878 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001879 out.startTag(null, "app-ops");
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001880 out.attribute(null, "v", String.valueOf(CURRENT_VERSION));
Svet Ganov2af57082015-07-30 08:44:20 -07001881
1882 final int uidStateCount = mUidStates.size();
1883 for (int i = 0; i < uidStateCount; i++) {
1884 UidState uidState = mUidStates.valueAt(i);
1885 if (uidState.opModes != null && uidState.opModes.size() > 0) {
1886 out.startTag(null, "uid");
1887 out.attribute(null, "n", Integer.toString(uidState.uid));
1888 SparseIntArray uidOpModes = uidState.opModes;
1889 final int opCount = uidOpModes.size();
1890 for (int j = 0; j < opCount; j++) {
1891 final int op = uidOpModes.keyAt(j);
1892 final int mode = uidOpModes.valueAt(j);
1893 out.startTag(null, "op");
1894 out.attribute(null, "n", Integer.toString(op));
1895 out.attribute(null, "m", Integer.toString(mode));
1896 out.endTag(null, "op");
1897 }
1898 out.endTag(null, "uid");
1899 }
1900 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001901
1902 if (allOps != null) {
1903 String lastPkg = null;
1904 for (int i=0; i<allOps.size(); i++) {
1905 AppOpsManager.PackageOps pkg = allOps.get(i);
1906 if (!pkg.getPackageName().equals(lastPkg)) {
1907 if (lastPkg != null) {
1908 out.endTag(null, "pkg");
1909 }
1910 lastPkg = pkg.getPackageName();
1911 out.startTag(null, "pkg");
1912 out.attribute(null, "n", lastPkg);
1913 }
1914 out.startTag(null, "uid");
1915 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04001916 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001917 Ops ops = getOpsRawLocked(pkg.getUid(), pkg.getPackageName(),
1918 false /* edit */, false /* uidMismatchExpected */);
Jason Monk1c7c3192014-06-26 12:52:18 -04001919 // Should always be present as the list of PackageOps is generated
1920 // from Ops.
1921 if (ops != null) {
1922 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
1923 } else {
1924 out.attribute(null, "p", Boolean.toString(false));
1925 }
1926 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001927 List<AppOpsManager.OpEntry> ops = pkg.getOps();
1928 for (int j=0; j<ops.size(); j++) {
1929 AppOpsManager.OpEntry op = ops.get(j);
1930 out.startTag(null, "op");
1931 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07001932 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001933 out.attribute(null, "m", Integer.toString(op.getMode()));
1934 }
1935 long time = op.getTime();
1936 if (time != 0) {
1937 out.attribute(null, "t", Long.toString(time));
1938 }
1939 time = op.getRejectTime();
1940 if (time != 0) {
1941 out.attribute(null, "r", Long.toString(time));
1942 }
1943 int dur = op.getDuration();
1944 if (dur != 0) {
1945 out.attribute(null, "d", Integer.toString(dur));
1946 }
Svet Ganov99b60432015-06-27 13:15:22 -07001947 int proxyUid = op.getProxyUid();
1948 if (proxyUid != -1) {
1949 out.attribute(null, "pu", Integer.toString(proxyUid));
1950 }
1951 String proxyPackageName = op.getProxyPackageName();
1952 if (proxyPackageName != null) {
1953 out.attribute(null, "pp", proxyPackageName);
1954 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001955 out.endTag(null, "op");
1956 }
1957 out.endTag(null, "uid");
1958 }
1959 if (lastPkg != null) {
1960 out.endTag(null, "pkg");
1961 }
1962 }
1963
1964 out.endTag(null, "app-ops");
1965 out.endDocument();
1966 mFile.finishWrite(stream);
1967 } catch (IOException e) {
1968 Slog.w(TAG, "Failed to write state, restoring backup.", e);
1969 mFile.failWrite(stream);
1970 }
1971 }
1972 }
1973
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001974 static class Shell extends ShellCommand {
1975 final IAppOpsService mInterface;
1976 final AppOpsService mInternal;
1977
1978 int userId = UserHandle.USER_SYSTEM;
1979 String packageName;
1980 String opStr;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001981 String modeStr;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001982 int op;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001983 int mode;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001984 int packageUid;
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001985 int nonpackageUid;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05001986 final static Binder sBinder = new Binder();
1987 IBinder mToken;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001988
1989 Shell(IAppOpsService iface, AppOpsService internal) {
1990 mInterface = iface;
1991 mInternal = internal;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05001992 try {
1993 mToken = mInterface.getToken(sBinder);
1994 } catch (RemoteException e) {
1995 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001996 }
1997
1998 @Override
1999 public int onCommand(String cmd) {
2000 return onShellCommand(this, cmd);
2001 }
2002
2003 @Override
2004 public void onHelp() {
2005 PrintWriter pw = getOutPrintWriter();
2006 dumpCommandHelp(pw);
2007 }
2008
2009 private int strOpToOp(String op, PrintWriter err) {
2010 try {
2011 return AppOpsManager.strOpToOp(op);
2012 } catch (IllegalArgumentException e) {
2013 }
2014 try {
2015 return Integer.parseInt(op);
2016 } catch (NumberFormatException e) {
2017 }
2018 try {
2019 return AppOpsManager.strDebugOpToOp(op);
2020 } catch (IllegalArgumentException e) {
2021 err.println("Error: " + e.getMessage());
2022 return -1;
2023 }
2024 }
2025
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002026 int strModeToMode(String modeStr, PrintWriter err) {
2027 switch (modeStr) {
2028 case "allow":
2029 return AppOpsManager.MODE_ALLOWED;
2030 case "deny":
2031 return AppOpsManager.MODE_ERRORED;
2032 case "ignore":
2033 return AppOpsManager.MODE_IGNORED;
2034 case "default":
2035 return AppOpsManager.MODE_DEFAULT;
2036 }
2037 try {
2038 return Integer.parseInt(modeStr);
2039 } catch (NumberFormatException e) {
2040 }
2041 err.println("Error: Mode " + modeStr + " is not valid");
2042 return -1;
2043 }
2044
2045 int parseUserOpMode(int defMode, PrintWriter err) throws RemoteException {
2046 userId = UserHandle.USER_CURRENT;
2047 opStr = null;
2048 modeStr = null;
2049 for (String argument; (argument = getNextArg()) != null;) {
2050 if ("--user".equals(argument)) {
2051 userId = UserHandle.parseUserArg(getNextArgRequired());
2052 } else {
2053 if (opStr == null) {
2054 opStr = argument;
2055 } else if (modeStr == null) {
2056 modeStr = argument;
2057 break;
2058 }
2059 }
2060 }
2061 if (opStr == null) {
2062 err.println("Error: Operation not specified.");
2063 return -1;
2064 }
2065 op = strOpToOp(opStr, err);
2066 if (op < 0) {
2067 return -1;
2068 }
2069 if (modeStr != null) {
2070 if ((mode=strModeToMode(modeStr, err)) < 0) {
2071 return -1;
2072 }
2073 } else {
2074 mode = defMode;
2075 }
2076 return 0;
2077 }
2078
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002079 int parseUserPackageOp(boolean reqOp, PrintWriter err) throws RemoteException {
2080 userId = UserHandle.USER_CURRENT;
2081 packageName = null;
2082 opStr = null;
2083 for (String argument; (argument = getNextArg()) != null;) {
2084 if ("--user".equals(argument)) {
2085 userId = UserHandle.parseUserArg(getNextArgRequired());
2086 } else {
2087 if (packageName == null) {
2088 packageName = argument;
2089 } else if (opStr == null) {
2090 opStr = argument;
2091 break;
2092 }
2093 }
2094 }
2095 if (packageName == null) {
2096 err.println("Error: Package name not specified.");
2097 return -1;
2098 } else if (opStr == null && reqOp) {
2099 err.println("Error: Operation not specified.");
2100 return -1;
2101 }
2102 if (opStr != null) {
2103 op = strOpToOp(opStr, err);
2104 if (op < 0) {
2105 return -1;
2106 }
2107 } else {
2108 op = AppOpsManager.OP_NONE;
2109 }
2110 if (userId == UserHandle.USER_CURRENT) {
2111 userId = ActivityManager.getCurrentUser();
2112 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002113 nonpackageUid = -1;
2114 try {
2115 nonpackageUid = Integer.parseInt(packageName);
2116 } catch (NumberFormatException e) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002117 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002118 if (nonpackageUid == -1 && packageName.length() > 1 && packageName.charAt(0) == 'u'
2119 && packageName.indexOf('.') < 0) {
2120 int i = 1;
2121 while (i < packageName.length() && packageName.charAt(i) >= '0'
2122 && packageName.charAt(i) <= '9') {
2123 i++;
2124 }
2125 if (i > 1 && i < packageName.length()) {
2126 String userStr = packageName.substring(1, i);
2127 try {
2128 int user = Integer.parseInt(userStr);
2129 char type = packageName.charAt(i);
2130 i++;
2131 int startTypeVal = i;
2132 while (i < packageName.length() && packageName.charAt(i) >= '0'
2133 && packageName.charAt(i) <= '9') {
2134 i++;
2135 }
2136 if (i > startTypeVal) {
2137 String typeValStr = packageName.substring(startTypeVal, i);
2138 try {
2139 int typeVal = Integer.parseInt(typeValStr);
2140 if (type == 'a') {
2141 nonpackageUid = UserHandle.getUid(user,
2142 typeVal + Process.FIRST_APPLICATION_UID);
2143 } else if (type == 's') {
2144 nonpackageUid = UserHandle.getUid(user, typeVal);
2145 }
2146 } catch (NumberFormatException e) {
2147 }
2148 }
2149 } catch (NumberFormatException e) {
2150 }
2151 }
2152 }
2153 if (nonpackageUid != -1) {
2154 packageName = null;
2155 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08002156 packageUid = resolveUid(packageName);
2157 if (packageUid < 0) {
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002158 packageUid = AppGlobals.getPackageManager().getPackageUid(packageName,
2159 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
2160 }
2161 if (packageUid < 0) {
2162 err.println("Error: No UID for " + packageName + " in user " + userId);
2163 return -1;
2164 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002165 }
2166 return 0;
2167 }
2168 }
2169
2170 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002171 FileDescriptor err, String[] args, ShellCallback callback,
2172 ResultReceiver resultReceiver) {
2173 (new Shell(this, this)).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002174 }
2175
2176 static void dumpCommandHelp(PrintWriter pw) {
2177 pw.println("AppOps service (appops) commands:");
2178 pw.println(" help");
2179 pw.println(" Print this help text.");
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05002180 pw.println(" start [--user <USER_ID>] <PACKAGE | UID> <OP> ");
2181 pw.println(" Starts a given operation for a particular application.");
2182 pw.println(" stop [--user <USER_ID>] <PACKAGE | UID> <OP> ");
2183 pw.println(" Stops a given operation for a particular application.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002184 pw.println(" set [--user <USER_ID>] <PACKAGE | UID> <OP> <MODE>");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002185 pw.println(" Set the mode for a particular application and operation.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002186 pw.println(" get [--user <USER_ID>] <PACKAGE | UID> [<OP>]");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002187 pw.println(" Return the mode for a particular application and optional operation.");
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002188 pw.println(" query-op [--user <USER_ID>] <OP> [<MODE>]");
2189 pw.println(" Print all packages that currently have the given op in the given mode.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002190 pw.println(" reset [--user <USER_ID>] [<PACKAGE>]");
2191 pw.println(" Reset the given application or all applications to default modes.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002192 pw.println(" write-settings");
2193 pw.println(" Immediately write pending changes to storage.");
2194 pw.println(" read-settings");
2195 pw.println(" Read the last written settings, replacing current state in RAM.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002196 pw.println(" options:");
2197 pw.println(" <PACKAGE> an Android package name.");
2198 pw.println(" <OP> an AppOps operation.");
2199 pw.println(" <MODE> one of allow, ignore, deny, or default");
2200 pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
2201 pw.println(" specified, the current user is assumed.");
2202 }
2203
2204 static int onShellCommand(Shell shell, String cmd) {
2205 if (cmd == null) {
2206 return shell.handleDefaultCommands(cmd);
2207 }
2208 PrintWriter pw = shell.getOutPrintWriter();
2209 PrintWriter err = shell.getErrPrintWriter();
2210 try {
2211 switch (cmd) {
2212 case "set": {
2213 int res = shell.parseUserPackageOp(true, err);
2214 if (res < 0) {
2215 return res;
2216 }
2217 String modeStr = shell.getNextArg();
2218 if (modeStr == null) {
2219 err.println("Error: Mode not specified.");
2220 return -1;
2221 }
2222
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002223 final int mode = shell.strModeToMode(modeStr, err);
2224 if (mode < 0) {
2225 return -1;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002226 }
2227
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002228 if (shell.packageName != null) {
2229 shell.mInterface.setMode(shell.op, shell.packageUid, shell.packageName,
2230 mode);
2231 } else {
2232 shell.mInterface.setUidMode(shell.op, shell.nonpackageUid, mode);
2233 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002234 return 0;
2235 }
2236 case "get": {
2237 int res = shell.parseUserPackageOp(false, err);
2238 if (res < 0) {
2239 return res;
2240 }
2241
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002242 List<AppOpsManager.PackageOps> ops;
2243 if (shell.packageName != null) {
2244 ops = shell.mInterface.getOpsForPackage(
2245 shell.packageUid, shell.packageName,
2246 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
2247 } else {
2248 ops = shell.mInterface.getUidOps(
2249 shell.nonpackageUid,
2250 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
2251 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002252 if (ops == null || ops.size() <= 0) {
2253 pw.println("No operations.");
Svet Ganov82f09bc2018-01-12 22:08:40 -08002254 if (shell.op > AppOpsManager.OP_NONE && shell.op < AppOpsManager._NUM_OP) {
2255 pw.println("Default mode: " + AppOpsManager.modeToString(
2256 AppOpsManager.opToDefaultMode(shell.op)));
2257 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002258 return 0;
2259 }
2260 final long now = System.currentTimeMillis();
2261 for (int i=0; i<ops.size(); i++) {
2262 List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
2263 for (int j=0; j<entries.size(); j++) {
2264 AppOpsManager.OpEntry ent = entries.get(j);
2265 pw.print(AppOpsManager.opToName(ent.getOp()));
2266 pw.print(": ");
Svet Ganov82f09bc2018-01-12 22:08:40 -08002267 pw.print(AppOpsManager.modeToString(ent.getMode()));
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002268 if (ent.getTime() != 0) {
2269 pw.print("; time=");
2270 TimeUtils.formatDuration(now - ent.getTime(), pw);
2271 pw.print(" ago");
2272 }
2273 if (ent.getRejectTime() != 0) {
2274 pw.print("; rejectTime=");
2275 TimeUtils.formatDuration(now - ent.getRejectTime(), pw);
2276 pw.print(" ago");
2277 }
2278 if (ent.getDuration() == -1) {
2279 pw.print(" (running)");
2280 } else if (ent.getDuration() != 0) {
2281 pw.print("; duration=");
2282 TimeUtils.formatDuration(ent.getDuration(), pw);
2283 }
2284 pw.println();
2285 }
2286 }
2287 return 0;
2288 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002289 case "query-op": {
2290 int res = shell.parseUserOpMode(AppOpsManager.MODE_IGNORED, err);
2291 if (res < 0) {
2292 return res;
2293 }
2294 List<AppOpsManager.PackageOps> ops = shell.mInterface.getPackagesForOps(
2295 new int[] {shell.op});
2296 if (ops == null || ops.size() <= 0) {
2297 pw.println("No operations.");
2298 return 0;
2299 }
2300 for (int i=0; i<ops.size(); i++) {
2301 final AppOpsManager.PackageOps pkg = ops.get(i);
2302 boolean hasMatch = false;
2303 final List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
2304 for (int j=0; j<entries.size(); j++) {
2305 AppOpsManager.OpEntry ent = entries.get(j);
2306 if (ent.getOp() == shell.op && ent.getMode() == shell.mode) {
2307 hasMatch = true;
2308 break;
2309 }
2310 }
2311 if (hasMatch) {
2312 pw.println(pkg.getPackageName());
2313 }
2314 }
2315 return 0;
2316 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002317 case "reset": {
2318 String packageName = null;
2319 int userId = UserHandle.USER_CURRENT;
2320 for (String argument; (argument = shell.getNextArg()) != null;) {
2321 if ("--user".equals(argument)) {
2322 String userStr = shell.getNextArgRequired();
2323 userId = UserHandle.parseUserArg(userStr);
2324 } else {
2325 if (packageName == null) {
2326 packageName = argument;
2327 } else {
2328 err.println("Error: Unsupported argument: " + argument);
2329 return -1;
2330 }
2331 }
2332 }
2333
2334 if (userId == UserHandle.USER_CURRENT) {
2335 userId = ActivityManager.getCurrentUser();
2336 }
2337
2338 shell.mInterface.resetAllModes(userId, packageName);
2339 pw.print("Reset all modes for: ");
2340 if (userId == UserHandle.USER_ALL) {
2341 pw.print("all users");
2342 } else {
2343 pw.print("user "); pw.print(userId);
2344 }
2345 pw.print(", ");
2346 if (packageName == null) {
2347 pw.println("all packages");
2348 } else {
2349 pw.print("package "); pw.println(packageName);
2350 }
2351 return 0;
2352 }
2353 case "write-settings": {
2354 shell.mInternal.mContext.enforcePermission(
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -08002355 android.Manifest.permission.MANAGE_APP_OPS_MODES,
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002356 Binder.getCallingPid(), Binder.getCallingUid(), null);
2357 long token = Binder.clearCallingIdentity();
2358 try {
2359 synchronized (shell.mInternal) {
2360 shell.mInternal.mHandler.removeCallbacks(shell.mInternal.mWriteRunner);
2361 }
2362 shell.mInternal.writeState();
2363 pw.println("Current settings written.");
2364 } finally {
2365 Binder.restoreCallingIdentity(token);
2366 }
2367 return 0;
2368 }
2369 case "read-settings": {
2370 shell.mInternal.mContext.enforcePermission(
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -08002371 android.Manifest.permission.MANAGE_APP_OPS_MODES,
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002372 Binder.getCallingPid(), Binder.getCallingUid(), null);
2373 long token = Binder.clearCallingIdentity();
2374 try {
2375 shell.mInternal.readState();
2376 pw.println("Last settings read.");
2377 } finally {
2378 Binder.restoreCallingIdentity(token);
2379 }
2380 return 0;
2381 }
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05002382 case "start": {
2383 int res = shell.parseUserPackageOp(true, err);
2384 if (res < 0) {
2385 return res;
2386 }
2387
2388 if (shell.packageName != null) {
2389 shell.mInterface.startOperation(shell.mToken,
2390 shell.op, shell.packageUid, shell.packageName, true);
2391 } else {
2392 return -1;
2393 }
2394 return 0;
2395 }
2396 case "stop": {
2397 int res = shell.parseUserPackageOp(true, err);
2398 if (res < 0) {
2399 return res;
2400 }
2401
2402 if (shell.packageName != null) {
2403 shell.mInterface.finishOperation(shell.mToken,
2404 shell.op, shell.packageUid, shell.packageName);
2405 } else {
2406 return -1;
2407 }
2408 return 0;
2409 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002410 default:
2411 return shell.handleDefaultCommands(cmd);
2412 }
2413 } catch (RemoteException e) {
2414 pw.println("Remote exception: " + e);
2415 }
2416 return -1;
2417 }
2418
2419 private void dumpHelp(PrintWriter pw) {
2420 pw.println("AppOps service (appops) dump options:");
2421 pw.println(" none");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002422 }
2423
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002424 @Override
2425 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002426 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002427
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002428 if (args != null) {
2429 for (int i=0; i<args.length; i++) {
2430 String arg = args[i];
2431 if ("-h".equals(arg)) {
2432 dumpHelp(pw);
2433 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07002434 } else if ("-a".equals(arg)) {
2435 // dump all data
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002436 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
2437 pw.println("Unknown option: " + arg);
2438 return;
2439 } else {
2440 pw.println("Unknown command: " + arg);
2441 return;
2442 }
2443 }
2444 }
2445
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002446 synchronized (this) {
2447 pw.println("Current AppOps Service state:");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002448 final long now = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002449 boolean needSep = false;
2450 if (mOpModeWatchers.size() > 0) {
2451 needSep = true;
2452 pw.println(" Op mode watchers:");
2453 for (int i=0; i<mOpModeWatchers.size(); i++) {
2454 pw.print(" Op "); pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
2455 pw.println(":");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002456 ArraySet<ModeCallback> callbacks = mOpModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002457 for (int j=0; j<callbacks.size(); j++) {
2458 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08002459 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002460 }
2461 }
2462 }
2463 if (mPackageModeWatchers.size() > 0) {
2464 needSep = true;
2465 pw.println(" Package mode watchers:");
2466 for (int i=0; i<mPackageModeWatchers.size(); i++) {
2467 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
2468 pw.println(":");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002469 ArraySet<ModeCallback> callbacks = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002470 for (int j=0; j<callbacks.size(); j++) {
2471 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08002472 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002473 }
2474 }
2475 }
2476 if (mModeWatchers.size() > 0) {
2477 needSep = true;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002478 pw.println(" All op mode watchers:");
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002479 for (int i=0; i<mModeWatchers.size(); i++) {
2480 pw.print(" "); pw.print(mModeWatchers.keyAt(i));
2481 pw.print(" -> "); pw.println(mModeWatchers.valueAt(i));
2482 }
2483 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002484 if (mActiveWatchers.size() > 0) {
2485 needSep = true;
2486 pw.println(" All op active watchers:");
2487 for (int i = 0; i < mActiveWatchers.size(); i++) {
2488 final SparseArray<ActiveCallback> activeWatchers = mActiveWatchers.valueAt(i);
2489 if (activeWatchers.size() <= 0) {
2490 continue;
2491 }
2492 pw.print(" "); pw.print(mActiveWatchers.keyAt(i));
2493 pw.print(" -> [");
2494 final int opCount = activeWatchers.size();
2495 for (i = 0; i < opCount; i++) {
2496 pw.print(AppOpsManager.opToName(activeWatchers.keyAt(i)));
2497 if (i < opCount - 1) {
2498 pw.print(',');
2499 }
2500 }
2501 pw.print("]" ); pw.println(activeWatchers.valueAt(0));
2502 }
2503 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002504 if (mClients.size() > 0) {
2505 needSep = true;
2506 pw.println(" Clients:");
2507 for (int i=0; i<mClients.size(); i++) {
2508 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
2509 ClientState cs = mClients.valueAt(i);
2510 pw.print(" "); pw.println(cs);
Svet Ganovf7b47252018-02-26 11:11:27 -08002511 if (cs.mStartedOps.size() > 0) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002512 pw.println(" Started ops:");
2513 for (int j=0; j<cs.mStartedOps.size(); j++) {
2514 Op op = cs.mStartedOps.get(j);
2515 pw.print(" "); pw.print("uid="); pw.print(op.uid);
2516 pw.print(" pkg="); pw.print(op.packageName);
2517 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
2518 }
2519 }
2520 }
2521 }
John Spurlock1af30c72014-03-10 08:33:35 -04002522 if (mAudioRestrictions.size() > 0) {
2523 boolean printedHeader = false;
2524 for (int o=0; o<mAudioRestrictions.size(); o++) {
2525 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
2526 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
2527 for (int i=0; i<restrictions.size(); i++) {
2528 if (!printedHeader){
2529 pw.println(" Audio Restrictions:");
2530 printedHeader = true;
2531 needSep = true;
2532 }
John Spurlock7b414672014-07-18 13:02:39 -04002533 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04002534 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04002535 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04002536 Restriction r = restrictions.valueAt(i);
2537 pw.print(": mode="); pw.println(r.mode);
2538 if (!r.exceptionPackages.isEmpty()) {
2539 pw.println(" Exceptions:");
2540 for (int j=0; j<r.exceptionPackages.size(); j++) {
2541 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
2542 }
2543 }
2544 }
2545 }
2546 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002547 if (needSep) {
2548 pw.println();
2549 }
Svet Ganov2af57082015-07-30 08:44:20 -07002550 for (int i=0; i<mUidStates.size(); i++) {
2551 UidState uidState = mUidStates.valueAt(i);
2552
2553 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
Svet Ganovee438d42017-01-19 18:04:38 -08002554 needSep = true;
Svet Ganov2af57082015-07-30 08:44:20 -07002555
2556 SparseIntArray opModes = uidState.opModes;
2557 if (opModes != null) {
2558 final int opModeCount = opModes.size();
2559 for (int j = 0; j < opModeCount; j++) {
2560 final int code = opModes.keyAt(j);
2561 final int mode = opModes.valueAt(j);
2562 pw.print(" "); pw.print(AppOpsManager.opToName(code));
2563 pw.print(": mode="); pw.println(mode);
2564 }
2565 }
2566
2567 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
2568 if (pkgOps == null) {
2569 continue;
2570 }
2571
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002572 for (Ops ops : pkgOps.values()) {
2573 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
2574 for (int j=0; j<ops.size(); j++) {
2575 Op op = ops.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002576 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
2577 pw.print(": mode="); pw.print(op.mode);
2578 if (op.time != 0) {
2579 pw.print("; time="); TimeUtils.formatDuration(now-op.time, pw);
2580 pw.print(" ago");
2581 }
2582 if (op.rejectTime != 0) {
2583 pw.print("; rejectTime="); TimeUtils.formatDuration(now-op.rejectTime, pw);
2584 pw.print(" ago");
2585 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002586 if (op.duration == -1) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002587 pw.print(" (running)");
2588 } else if (op.duration != 0) {
2589 pw.print("; duration="); TimeUtils.formatDuration(op.duration, pw);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002590 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002591 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002592 }
2593 }
2594 }
Svet Ganovee438d42017-01-19 18:04:38 -08002595 if (needSep) {
2596 pw.println();
2597 }
2598
2599 final int userRestrictionCount = mOpUserRestrictions.size();
2600 for (int i = 0; i < userRestrictionCount; i++) {
2601 IBinder token = mOpUserRestrictions.keyAt(i);
2602 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
2603 pw.println(" User restrictions for token " + token + ":");
2604
2605 final int restrictionCount = restrictionState.perUserRestrictions != null
2606 ? restrictionState.perUserRestrictions.size() : 0;
2607 if (restrictionCount > 0) {
2608 pw.println(" Restricted ops:");
2609 for (int j = 0; j < restrictionCount; j++) {
2610 int userId = restrictionState.perUserRestrictions.keyAt(j);
2611 boolean[] restrictedOps = restrictionState.perUserRestrictions.valueAt(j);
2612 if (restrictedOps == null) {
2613 continue;
2614 }
2615 StringBuilder restrictedOpsValue = new StringBuilder();
2616 restrictedOpsValue.append("[");
2617 final int restrictedOpCount = restrictedOps.length;
2618 for (int k = 0; k < restrictedOpCount; k++) {
2619 if (restrictedOps[k]) {
2620 if (restrictedOpsValue.length() > 1) {
2621 restrictedOpsValue.append(", ");
2622 }
2623 restrictedOpsValue.append(AppOpsManager.opToName(k));
2624 }
2625 }
2626 restrictedOpsValue.append("]");
2627 pw.print(" "); pw.print("user: "); pw.print(userId);
2628 pw.print(" restricted ops: "); pw.println(restrictedOpsValue);
2629 }
2630 }
2631
2632 final int excludedPackageCount = restrictionState.perUserExcludedPackages != null
2633 ? restrictionState.perUserExcludedPackages.size() : 0;
2634 if (excludedPackageCount > 0) {
2635 pw.println(" Excluded packages:");
2636 for (int j = 0; j < excludedPackageCount; j++) {
2637 int userId = restrictionState.perUserExcludedPackages.keyAt(j);
2638 String[] packageNames = restrictionState.perUserExcludedPackages.valueAt(j);
2639 pw.print(" "); pw.print("user: "); pw.print(userId);
2640 pw.print(" packages: "); pw.println(Arrays.toString(packageNames));
2641 }
2642 }
2643 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002644 }
2645 }
John Spurlock1af30c72014-03-10 08:33:35 -04002646
2647 private static final class Restriction {
2648 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
2649 int mode;
2650 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
2651 }
Jason Monk62062992014-05-06 09:55:28 -04002652
2653 @Override
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002654 public void setUserRestrictions(Bundle restrictions, IBinder token, int userHandle) {
Jason Monk62062992014-05-06 09:55:28 -04002655 checkSystemUid("setUserRestrictions");
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002656 Preconditions.checkNotNull(restrictions);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002657 Preconditions.checkNotNull(token);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002658 for (int i = 0; i < AppOpsManager._NUM_OP; i++) {
Jason Monk62062992014-05-06 09:55:28 -04002659 String restriction = AppOpsManager.opToRestriction(i);
Suprabh Shukla64e0dcb2016-05-24 16:23:11 -07002660 if (restriction != null) {
2661 setUserRestrictionNoCheck(i, restrictions.getBoolean(restriction, false), token,
2662 userHandle, null);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002663 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002664 }
2665 }
2666
2667 @Override
Ruben Brunk29931bc2016-03-11 00:24:26 -08002668 public void setUserRestriction(int code, boolean restricted, IBinder token, int userHandle,
2669 String[] exceptionPackages) {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002670 if (Binder.getCallingPid() != Process.myPid()) {
2671 mContext.enforcePermission(Manifest.permission.MANAGE_APP_OPS_RESTRICTIONS,
2672 Binder.getCallingPid(), Binder.getCallingUid(), null);
2673 }
2674 if (userHandle != UserHandle.getCallingUserId()) {
2675 if (mContext.checkCallingOrSelfPermission(Manifest.permission
2676 .INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
2677 && mContext.checkCallingOrSelfPermission(Manifest.permission
2678 .INTERACT_ACROSS_USERS) != PackageManager.PERMISSION_GRANTED) {
2679 throw new SecurityException("Need INTERACT_ACROSS_USERS_FULL or"
2680 + " INTERACT_ACROSS_USERS to interact cross user ");
Jason Monk62062992014-05-06 09:55:28 -04002681 }
2682 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002683 verifyIncomingOp(code);
2684 Preconditions.checkNotNull(token);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002685 setUserRestrictionNoCheck(code, restricted, token, userHandle, exceptionPackages);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002686 }
2687
2688 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
Ruben Brunk29931bc2016-03-11 00:24:26 -08002689 int userHandle, String[] exceptionPackages) {
Svet Ganov442ed572016-08-17 17:29:43 -07002690 synchronized (AppOpsService.this) {
2691 ClientRestrictionState restrictionState = mOpUserRestrictions.get(token);
2692
2693 if (restrictionState == null) {
2694 try {
2695 restrictionState = new ClientRestrictionState(token);
2696 } catch (RemoteException e) {
2697 return;
2698 }
2699 mOpUserRestrictions.put(token, restrictionState);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002700 }
Svet Ganov442ed572016-08-17 17:29:43 -07002701
2702 if (restrictionState.setRestriction(code, restricted, exceptionPackages, userHandle)) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002703 mHandler.sendMessage(PooledLambda.obtainMessage(
Svet Ganov3a95f832018-03-23 17:44:30 -07002704 AppOpsService::notifyWatchersOfChange, this, code, UID_ANY));
Svet Ganov442ed572016-08-17 17:29:43 -07002705 }
2706
2707 if (restrictionState.isDefault()) {
2708 mOpUserRestrictions.remove(token);
2709 restrictionState.destroy();
2710 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002711 }
Julia Reynoldsbb21c252016-04-05 16:01:49 -04002712 }
2713
Svet Ganov3a95f832018-03-23 17:44:30 -07002714 private void notifyWatchersOfChange(int code, int uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002715 final ArraySet<ModeCallback> clonedCallbacks;
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002716 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002717 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002718 if (callbacks == null) {
2719 return;
2720 }
Dianne Hackborn68d76552017-02-27 15:32:03 -08002721 clonedCallbacks = new ArraySet<>(callbacks);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002722 }
2723
Svet Ganov3a95f832018-03-23 17:44:30 -07002724 notifyOpChanged(clonedCallbacks, code, uid, null);
Jason Monk62062992014-05-06 09:55:28 -04002725 }
2726
2727 @Override
2728 public void removeUser(int userHandle) throws RemoteException {
2729 checkSystemUid("removeUser");
Svet Ganov442ed572016-08-17 17:29:43 -07002730 synchronized (AppOpsService.this) {
2731 final int tokenCount = mOpUserRestrictions.size();
2732 for (int i = tokenCount - 1; i >= 0; i--) {
2733 ClientRestrictionState opRestrictions = mOpUserRestrictions.valueAt(i);
2734 opRestrictions.removeUser(userHandle);
2735 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002736 removeUidsForUserLocked(userHandle);
2737 }
2738 }
2739
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002740 @Override
2741 public boolean isOperationActive(int code, int uid, String packageName) {
Svet Ganovf7b47252018-02-26 11:11:27 -08002742 if (Binder.getCallingUid() != uid) {
2743 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
2744 != PackageManager.PERMISSION_GRANTED) {
2745 return false;
2746 }
2747 }
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002748 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002749 final String resolvedPackageName = resolvePackageName(uid, packageName);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002750 if (resolvedPackageName == null) {
2751 return false;
2752 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002753 synchronized (AppOpsService.this) {
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002754 for (int i = mClients.size() - 1; i >= 0; i--) {
2755 final ClientState client = mClients.valueAt(i);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002756 for (int j = client.mStartedOps.size() - 1; j >= 0; j--) {
2757 final Op op = client.mStartedOps.get(j);
2758 if (op.op == code && op.uid == uid) return true;
2759 }
2760 }
2761 }
2762 return false;
2763 }
2764
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002765 private void removeUidsForUserLocked(int userHandle) {
2766 for (int i = mUidStates.size() - 1; i >= 0; --i) {
2767 final int uid = mUidStates.keyAt(i);
2768 if (UserHandle.getUserId(uid) == userHandle) {
2769 mUidStates.removeAt(i);
2770 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002771 }
2772 }
2773
Jason Monk62062992014-05-06 09:55:28 -04002774 private void checkSystemUid(String function) {
2775 int uid = Binder.getCallingUid();
2776 if (uid != Process.SYSTEM_UID) {
2777 throw new SecurityException(function + " must by called by the system");
2778 }
2779 }
2780
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002781 private static String resolvePackageName(int uid, String packageName) {
Svet Ganov82f09bc2018-01-12 22:08:40 -08002782 if (uid == Process.ROOT_UID) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002783 return "root";
2784 } else if (uid == Process.SHELL_UID) {
2785 return "com.android.shell";
Svet Ganov82f09bc2018-01-12 22:08:40 -08002786 } else if (uid == Process.MEDIA_UID) {
2787 return "media";
2788 } else if (uid == Process.AUDIOSERVER_UID) {
2789 return "audioserver";
2790 } else if (uid == Process.CAMERASERVER_UID) {
2791 return "cameraserver";
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002792 } else if (uid == Process.SYSTEM_UID && packageName == null) {
2793 return "android";
2794 }
2795 return packageName;
2796 }
2797
Svet Ganov82f09bc2018-01-12 22:08:40 -08002798 private static int resolveUid(String packageName) {
2799 if (packageName == null) {
2800 return -1;
2801 }
2802 switch (packageName) {
2803 case "root":
2804 return Process.ROOT_UID;
2805 case "shell":
2806 return Process.SHELL_UID;
2807 case "media":
2808 return Process.MEDIA_UID;
2809 case "audioserver":
2810 return Process.AUDIOSERVER_UID;
2811 case "cameraserver":
2812 return Process.CAMERASERVER_UID;
2813 }
2814 return -1;
2815 }
2816
Svet Ganov2af57082015-07-30 08:44:20 -07002817 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07002818 String[] packageNames = null;
Svet Ganov2af57082015-07-30 08:44:20 -07002819 try {
riddle_hsu40b300f2015-11-23 13:22:03 +08002820 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -07002821 } catch (RemoteException e) {
2822 /* ignore - local call */
2823 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07002824 if (packageNames == null) {
2825 return EmptyArray.STRING;
2826 }
2827 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07002828 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002829
2830 private final class ClientRestrictionState implements DeathRecipient {
2831 private final IBinder token;
2832 SparseArray<boolean[]> perUserRestrictions;
2833 SparseArray<String[]> perUserExcludedPackages;
2834
2835 public ClientRestrictionState(IBinder token)
2836 throws RemoteException {
2837 token.linkToDeath(this, 0);
2838 this.token = token;
2839 }
2840
2841 public boolean setRestriction(int code, boolean restricted,
2842 String[] excludedPackages, int userId) {
2843 boolean changed = false;
2844
2845 if (perUserRestrictions == null && restricted) {
2846 perUserRestrictions = new SparseArray<>();
2847 }
2848
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002849 int[] users;
2850 if (userId == UserHandle.USER_ALL) {
2851 List<UserInfo> liveUsers = UserManager.get(mContext).getUsers(false);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002852
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002853 users = new int[liveUsers.size()];
2854 for (int i = 0; i < liveUsers.size(); i++) {
2855 users[i] = liveUsers.get(i).id;
2856 }
2857 } else {
2858 users = new int[]{userId};
2859 }
2860
2861 if (perUserRestrictions != null) {
2862 int numUsers = users.length;
2863
2864 for (int i = 0; i < numUsers; i++) {
2865 int thisUserId = users[i];
2866
2867 boolean[] userRestrictions = perUserRestrictions.get(thisUserId);
2868 if (userRestrictions == null && restricted) {
2869 userRestrictions = new boolean[AppOpsManager._NUM_OP];
2870 perUserRestrictions.put(thisUserId, userRestrictions);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002871 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002872 if (userRestrictions != null && userRestrictions[code] != restricted) {
2873 userRestrictions[code] = restricted;
2874 if (!restricted && isDefault(userRestrictions)) {
2875 perUserRestrictions.remove(thisUserId);
2876 userRestrictions = null;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002877 }
2878 changed = true;
2879 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002880
2881 if (userRestrictions != null) {
2882 final boolean noExcludedPackages = ArrayUtils.isEmpty(excludedPackages);
2883 if (perUserExcludedPackages == null && !noExcludedPackages) {
2884 perUserExcludedPackages = new SparseArray<>();
2885 }
2886 if (perUserExcludedPackages != null && !Arrays.equals(excludedPackages,
2887 perUserExcludedPackages.get(thisUserId))) {
2888 if (noExcludedPackages) {
2889 perUserExcludedPackages.remove(thisUserId);
2890 if (perUserExcludedPackages.size() <= 0) {
2891 perUserExcludedPackages = null;
2892 }
2893 } else {
2894 perUserExcludedPackages.put(thisUserId, excludedPackages);
2895 }
2896 changed = true;
2897 }
2898 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002899 }
2900 }
2901
2902 return changed;
2903 }
2904
2905 public boolean hasRestriction(int restriction, String packageName, int userId) {
2906 if (perUserRestrictions == null) {
2907 return false;
2908 }
2909 boolean[] restrictions = perUserRestrictions.get(userId);
2910 if (restrictions == null) {
2911 return false;
2912 }
2913 if (!restrictions[restriction]) {
2914 return false;
2915 }
2916 if (perUserExcludedPackages == null) {
2917 return true;
2918 }
2919 String[] perUserExclusions = perUserExcludedPackages.get(userId);
2920 if (perUserExclusions == null) {
2921 return true;
2922 }
2923 return !ArrayUtils.contains(perUserExclusions, packageName);
2924 }
2925
2926 public void removeUser(int userId) {
2927 if (perUserExcludedPackages != null) {
2928 perUserExcludedPackages.remove(userId);
2929 if (perUserExcludedPackages.size() <= 0) {
2930 perUserExcludedPackages = null;
2931 }
2932 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002933 if (perUserRestrictions != null) {
2934 perUserRestrictions.remove(userId);
2935 if (perUserRestrictions.size() <= 0) {
2936 perUserRestrictions = null;
2937 }
2938 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002939 }
2940
2941 public boolean isDefault() {
2942 return perUserRestrictions == null || perUserRestrictions.size() <= 0;
2943 }
2944
2945 @Override
2946 public void binderDied() {
2947 synchronized (AppOpsService.this) {
2948 mOpUserRestrictions.remove(token);
2949 if (perUserRestrictions == null) {
2950 return;
2951 }
2952 final int userCount = perUserRestrictions.size();
2953 for (int i = 0; i < userCount; i++) {
2954 final boolean[] restrictions = perUserRestrictions.valueAt(i);
2955 final int restrictionCount = restrictions.length;
2956 for (int j = 0; j < restrictionCount; j++) {
2957 if (restrictions[j]) {
2958 final int changedCode = j;
Svet Ganov3a95f832018-03-23 17:44:30 -07002959 mHandler.post(() -> notifyWatchersOfChange(changedCode, UID_ANY));
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002960 }
2961 }
2962 }
2963 destroy();
2964 }
2965 }
2966
2967 public void destroy() {
2968 token.unlinkToDeath(this, 0);
2969 }
2970
2971 private boolean isDefault(boolean[] array) {
2972 if (ArrayUtils.isEmpty(array)) {
2973 return true;
2974 }
2975 for (boolean value : array) {
2976 if (value) {
2977 return false;
2978 }
2979 }
2980 return true;
2981 }
2982 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002983}