blob: b8601910497a04719e9a644316d479e085478327 [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;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700194 final int mWatchingUid;
195 final int mCallingUid;
196 final int mCallingPid;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800197
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700198 public ModeCallback(IAppOpsCallback callback, int watchingUid, int callingUid,
199 int callingPid) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800200 mCallback = callback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700201 mWatchingUid = watchingUid;
202 mCallingUid = callingUid;
203 mCallingPid = callingPid;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800204 try {
205 mCallback.asBinder().linkToDeath(this, 0);
206 } catch (RemoteException e) {
207 }
208 }
209
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700210 @Override
211 public String toString() {
212 StringBuilder sb = new StringBuilder(128);
213 sb.append("ModeCallback{");
214 sb.append(Integer.toHexString(System.identityHashCode(this)));
215 sb.append(" watchinguid=");
216 UserHandle.formatUid(sb, mWatchingUid);
217 sb.append(" from uid=");
218 UserHandle.formatUid(sb, mCallingUid);
219 sb.append(" pid=");
220 sb.append(mCallingPid);
221 sb.append('}');
222 return sb.toString();
223 }
224
Dianne Hackbornc2293022013-02-06 23:14:49 -0800225 public void unlinkToDeath() {
226 mCallback.asBinder().unlinkToDeath(this, 0);
227 }
228
229 @Override
230 public void binderDied() {
231 stopWatchingMode(mCallback);
232 }
233 }
234
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800235 public final class ActiveCallback implements DeathRecipient {
236 final IAppOpsActiveCallback mCallback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700237 final int mWatchingUid;
238 final int mCallingUid;
239 final int mCallingPid;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800240
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700241 public ActiveCallback(IAppOpsActiveCallback callback, int watchingUid, int callingUid,
242 int callingPid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800243 mCallback = callback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700244 mWatchingUid = watchingUid;
245 mCallingUid = callingUid;
246 mCallingPid = callingPid;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800247 try {
248 mCallback.asBinder().linkToDeath(this, 0);
249 } catch (RemoteException e) {
250 }
251 }
252
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700253 @Override
254 public String toString() {
255 StringBuilder sb = new StringBuilder(128);
256 sb.append("ActiveCallback{");
257 sb.append(Integer.toHexString(System.identityHashCode(this)));
258 sb.append(" watchinguid=");
259 UserHandle.formatUid(sb, mWatchingUid);
260 sb.append(" from uid=");
261 UserHandle.formatUid(sb, mCallingUid);
262 sb.append(" pid=");
263 sb.append(mCallingPid);
264 sb.append('}');
265 return sb.toString();
266 }
267
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800268 public void destroy() {
269 mCallback.asBinder().unlinkToDeath(this, 0);
270 }
271
272 @Override
273 public void binderDied() {
274 stopWatchingActive(mCallback);
275 }
276 }
277
Svet Ganova7a0db62018-02-27 20:08:01 -0800278 final ArrayMap<IBinder, ClientState> mClients = new ArrayMap<>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700279
280 public final class ClientState extends Binder implements DeathRecipient {
Svet Ganovf7b47252018-02-26 11:11:27 -0800281 final ArrayList<Op> mStartedOps = new ArrayList<>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700282 final IBinder mAppToken;
283 final int mPid;
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700284
285 public ClientState(IBinder appToken) {
286 mAppToken = appToken;
287 mPid = Binder.getCallingPid();
Svet Ganovf7b47252018-02-26 11:11:27 -0800288 // Watch only for remote processes dying
289 if (!(appToken instanceof Binder)) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700290 try {
291 mAppToken.linkToDeath(this, 0);
292 } catch (RemoteException e) {
Svet Ganovf7b47252018-02-26 11:11:27 -0800293 /* do nothing */
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700294 }
295 }
296 }
297
298 @Override
299 public String toString() {
300 return "ClientState{" +
301 "mAppToken=" + mAppToken +
Svet Ganovf7b47252018-02-26 11:11:27 -0800302 ", " + "pid=" + mPid +
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700303 '}';
304 }
305
306 @Override
307 public void binderDied() {
308 synchronized (AppOpsService.this) {
309 for (int i=mStartedOps.size()-1; i>=0; i--) {
Svet Ganova7a0db62018-02-27 20:08:01 -0800310 finishOperationLocked(mStartedOps.get(i), /*finishNested*/ true);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700311 }
312 mClients.remove(mAppToken);
313 }
314 }
315 }
316
Jeff Brown6f357d32014-01-15 20:40:55 -0800317 public AppOpsService(File storagePath, Handler handler) {
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600318 LockGuard.installLock(this, LockGuard.INDEX_APP_OPS);
Dianne Hackborne17b4452018-01-10 13:15:40 -0800319 mFile = new AtomicFile(storagePath, "appops");
Jeff Brown6f357d32014-01-15 20:40:55 -0800320 mHandler = handler;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800321 readState();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800322 }
David Braunf5d83192013-09-16 13:43:51 -0700323
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800324 public void publish(Context context) {
325 mContext = context;
326 ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
327 }
328
Dianne Hackborn514074f2013-02-11 10:52:46 -0800329 public void systemReady() {
330 synchronized (this) {
331 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700332 for (int i = mUidStates.size() - 1; i >= 0; i--) {
333 UidState uidState = mUidStates.valueAt(i);
334
335 String[] packageNames = getPackagesForUid(uidState.uid);
336 if (ArrayUtils.isEmpty(packageNames)) {
337 uidState.clear();
338 mUidStates.removeAt(i);
339 changed = true;
340 continue;
341 }
342
343 ArrayMap<String, Ops> pkgs = uidState.pkgOps;
344 if (pkgs == null) {
345 continue;
346 }
347
Dianne Hackborn514074f2013-02-11 10:52:46 -0800348 Iterator<Ops> it = pkgs.values().iterator();
349 while (it.hasNext()) {
350 Ops ops = it.next();
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700351 int curUid = -1;
Dianne Hackborn514074f2013-02-11 10:52:46 -0800352 try {
Jeff Sharkeycd654482016-01-08 17:42:11 -0700353 curUid = AppGlobals.getPackageManager().getPackageUid(ops.packageName,
354 PackageManager.MATCH_UNINSTALLED_PACKAGES,
Svet Ganov2af57082015-07-30 08:44:20 -0700355 UserHandle.getUserId(ops.uidState.uid));
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700356 } catch (RemoteException ignored) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800357 }
Svet Ganov2af57082015-07-30 08:44:20 -0700358 if (curUid != ops.uidState.uid) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800359 Slog.i(TAG, "Pruning old package " + ops.packageName
Svet Ganov2af57082015-07-30 08:44:20 -0700360 + "/" + ops.uidState + ": new uid=" + curUid);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800361 it.remove();
362 changed = true;
363 }
364 }
Svet Ganov2af57082015-07-30 08:44:20 -0700365
366 if (uidState.isDefault()) {
367 mUidStates.removeAt(i);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800368 }
369 }
370 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800371 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800372 }
373 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700374
Suprabh Shuklaaef25132017-01-23 18:09:03 -0800375 PackageManagerInternal packageManagerInternal = LocalServices.getService(
376 PackageManagerInternal.class);
377 packageManagerInternal.setExternalSourcesPolicy(
378 new PackageManagerInternal.ExternalSourcesPolicy() {
379 @Override
380 public int getPackageTrustedToInstallApps(String packageName, int uid) {
381 int appOpMode = checkOperation(AppOpsManager.OP_REQUEST_INSTALL_PACKAGES,
382 uid, packageName);
383 switch (appOpMode) {
384 case AppOpsManager.MODE_ALLOWED:
385 return PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
386 case AppOpsManager.MODE_ERRORED:
387 return PackageManagerInternal.ExternalSourcesPolicy.USER_BLOCKED;
388 default:
389 return PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT;
390 }
391 }
392 });
393
Sudheer Shanka2250d562016-11-07 15:41:02 -0800394 StorageManagerInternal storageManagerInternal = LocalServices.getService(
395 StorageManagerInternal.class);
396 storageManagerInternal.addExternalStoragePolicy(
397 new StorageManagerInternal.ExternalStorageMountPolicy() {
Svet Ganov6ee871e2015-07-10 14:29:33 -0700398 @Override
399 public int getMountMode(int uid, String packageName) {
400 if (Process.isIsolated(uid)) {
401 return Zygote.MOUNT_EXTERNAL_NONE;
402 }
403 if (noteOperation(AppOpsManager.OP_READ_EXTERNAL_STORAGE, uid,
404 packageName) != AppOpsManager.MODE_ALLOWED) {
405 return Zygote.MOUNT_EXTERNAL_NONE;
406 }
407 if (noteOperation(AppOpsManager.OP_WRITE_EXTERNAL_STORAGE, uid,
408 packageName) != AppOpsManager.MODE_ALLOWED) {
409 return Zygote.MOUNT_EXTERNAL_READ;
410 }
411 return Zygote.MOUNT_EXTERNAL_WRITE;
412 }
413
414 @Override
415 public boolean hasExternalStorage(int uid, String packageName) {
416 final int mountMode = getMountMode(uid, packageName);
417 return mountMode == Zygote.MOUNT_EXTERNAL_READ
418 || mountMode == Zygote.MOUNT_EXTERNAL_WRITE;
419 }
420 });
Dianne Hackborn514074f2013-02-11 10:52:46 -0800421 }
422
423 public void packageRemoved(int uid, String packageName) {
424 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700425 UidState uidState = mUidStates.get(uid);
426 if (uidState == null) {
427 return;
428 }
429
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800430 Ops ops = null;
Svet Ganov2af57082015-07-30 08:44:20 -0700431
432 // Remove any package state if such.
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800433 if (uidState.pkgOps != null) {
434 ops = uidState.pkgOps.remove(packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700435 }
436
437 // If we just nuked the last package state check if the UID is valid.
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800438 if (ops != null && uidState.pkgOps.isEmpty()
Svet Ganov2af57082015-07-30 08:44:20 -0700439 && getPackagesForUid(uid).length <= 0) {
440 mUidStates.remove(uid);
441 }
442
Svet Ganova7a0db62018-02-27 20:08:01 -0800443 // Finish ops other packages started on behalf of the package.
444 final int clientCount = mClients.size();
445 for (int i = 0; i < clientCount; i++) {
446 final ClientState client = mClients.valueAt(i);
447 if (client.mStartedOps == null) {
448 continue;
449 }
450 final int opCount = client.mStartedOps.size();
451 for (int j = opCount - 1; j >= 0; j--) {
452 final Op op = client.mStartedOps.get(j);
453 if (uid == op.uid && packageName.equals(op.packageName)) {
454 finishOperationLocked(op, /*finishNested*/ true);
455 client.mStartedOps.remove(j);
456 if (op.nesting <= 0) {
457 scheduleOpActiveChangedIfNeededLocked(op.op,
458 uid, packageName, false);
459 }
460 }
461 }
462 }
463
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800464 if (ops != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700465 scheduleFastWriteLocked();
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800466
467 final int opCount = ops.size();
468 for (int i = 0; i < opCount; i++) {
469 final Op op = ops.valueAt(i);
470 if (op.duration == -1) {
471 scheduleOpActiveChangedIfNeededLocked(
472 op.op, op.uid, op.packageName, false);
473 }
474 }
Dianne Hackborn514074f2013-02-11 10:52:46 -0800475 }
476 }
477 }
478
479 public void uidRemoved(int uid) {
480 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700481 if (mUidStates.indexOfKey(uid) >= 0) {
482 mUidStates.remove(uid);
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800483 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800484 }
485 }
486 }
487
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800488 public void shutdown() {
489 Slog.w(TAG, "Writing app ops before shutdown...");
Dianne Hackborn35654b62013-01-14 17:38:02 -0800490 boolean doWrite = false;
491 synchronized (this) {
492 if (mWriteScheduled) {
493 mWriteScheduled = false;
494 doWrite = true;
495 }
496 }
497 if (doWrite) {
498 writeState();
499 }
500 }
501
Dianne Hackborn72e39832013-01-18 18:36:09 -0800502 private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
503 ArrayList<AppOpsManager.OpEntry> resOps = null;
504 if (ops == null) {
505 resOps = new ArrayList<AppOpsManager.OpEntry>();
506 for (int j=0; j<pkgOps.size(); j++) {
507 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800508 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Svet Ganov99b60432015-06-27 13:15:22 -0700509 curOp.rejectTime, curOp.duration, curOp.proxyUid,
510 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800511 }
512 } else {
513 for (int j=0; j<ops.length; j++) {
514 Op curOp = pkgOps.get(ops[j]);
515 if (curOp != null) {
516 if (resOps == null) {
517 resOps = new ArrayList<AppOpsManager.OpEntry>();
518 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800519 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Svet Ganov99b60432015-06-27 13:15:22 -0700520 curOp.rejectTime, curOp.duration, curOp.proxyUid,
521 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800522 }
523 }
524 }
525 return resOps;
526 }
527
Dianne Hackbornc7214a32017-04-11 13:32:47 -0700528 private ArrayList<AppOpsManager.OpEntry> collectOps(SparseIntArray uidOps, int[] ops) {
529 ArrayList<AppOpsManager.OpEntry> resOps = null;
530 if (ops == null) {
531 resOps = new ArrayList<>();
532 for (int j=0; j<uidOps.size(); j++) {
533 resOps.add(new AppOpsManager.OpEntry(uidOps.keyAt(j), uidOps.valueAt(j),
534 0, 0, 0, -1, null));
535 }
536 } else {
537 for (int j=0; j<ops.length; j++) {
538 int index = uidOps.indexOfKey(ops[j]);
539 if (index >= 0) {
540 if (resOps == null) {
541 resOps = new ArrayList<>();
542 }
543 resOps.add(new AppOpsManager.OpEntry(uidOps.keyAt(index), uidOps.valueAt(index),
544 0, 0, 0, -1, null));
545 }
546 }
547 }
548 return resOps;
549 }
550
Dianne Hackborn35654b62013-01-14 17:38:02 -0800551 @Override
552 public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
553 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
554 Binder.getCallingPid(), Binder.getCallingUid(), null);
555 ArrayList<AppOpsManager.PackageOps> res = null;
556 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700557 final int uidStateCount = mUidStates.size();
558 for (int i = 0; i < uidStateCount; i++) {
559 UidState uidState = mUidStates.valueAt(i);
560 if (uidState.pkgOps == null || uidState.pkgOps.isEmpty()) {
561 continue;
562 }
563 ArrayMap<String, Ops> packages = uidState.pkgOps;
564 final int packageCount = packages.size();
565 for (int j = 0; j < packageCount; j++) {
566 Ops pkgOps = packages.valueAt(j);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800567 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800568 if (resOps != null) {
569 if (res == null) {
570 res = new ArrayList<AppOpsManager.PackageOps>();
571 }
572 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700573 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800574 res.add(resPackage);
575 }
576 }
577 }
578 }
579 return res;
580 }
581
582 @Override
Dianne Hackborn72e39832013-01-18 18:36:09 -0800583 public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
584 int[] ops) {
585 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
586 Binder.getCallingPid(), Binder.getCallingUid(), null);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000587 String resolvedPackageName = resolvePackageName(uid, packageName);
588 if (resolvedPackageName == null) {
589 return Collections.emptyList();
590 }
Dianne Hackborn72e39832013-01-18 18:36:09 -0800591 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -0700592 Ops pkgOps = getOpsRawLocked(uid, resolvedPackageName, false /* edit */,
593 false /* uidMismatchExpected */);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800594 if (pkgOps == null) {
595 return null;
596 }
597 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
598 if (resOps == null) {
599 return null;
600 }
601 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
602 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700603 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800604 res.add(resPackage);
605 return res;
606 }
607 }
608
Dianne Hackbornc7214a32017-04-11 13:32:47 -0700609 @Override
610 public List<AppOpsManager.PackageOps> getUidOps(int uid, int[] ops) {
611 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
612 Binder.getCallingPid(), Binder.getCallingUid(), null);
613 synchronized (this) {
614 UidState uidState = getUidStateLocked(uid, false);
615 if (uidState == null) {
616 return null;
617 }
618 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(uidState.opModes, ops);
619 if (resOps == null) {
620 return null;
621 }
622 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
623 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
624 null, uidState.uid, resOps);
625 res.add(resPackage);
626 return res;
627 }
628 }
629
Dianne Hackborn607b4142013-08-02 18:10:10 -0700630 private void pruneOp(Op op, int uid, String packageName) {
631 if (op.time == 0 && op.rejectTime == 0) {
Yohei Yukawaa965d652017-10-12 15:02:26 -0700632 Ops ops = getOpsRawLocked(uid, packageName, false /* edit */,
633 false /* uidMismatchExpected */);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700634 if (ops != null) {
635 ops.remove(op.op);
636 if (ops.size() <= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -0700637 UidState uidState = ops.uidState;
638 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700639 if (pkgOps != null) {
640 pkgOps.remove(ops.packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700641 if (pkgOps.isEmpty()) {
642 uidState.pkgOps = null;
643 }
644 if (uidState.isDefault()) {
645 mUidStates.remove(uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700646 }
647 }
648 }
649 }
650 }
651 }
652
Dianne Hackborn72e39832013-01-18 18:36:09 -0800653 @Override
Svet Ganov2af57082015-07-30 08:44:20 -0700654 public void setUidMode(int code, int uid, int mode) {
655 if (Binder.getCallingPid() != Process.myPid()) {
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -0800656 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
Svet Ganov2af57082015-07-30 08:44:20 -0700657 Binder.getCallingPid(), Binder.getCallingUid(), null);
658 }
659 verifyIncomingOp(code);
660 code = AppOpsManager.opToSwitch(code);
661
662 synchronized (this) {
663 final int defaultMode = AppOpsManager.opToDefaultMode(code);
664
665 UidState uidState = getUidStateLocked(uid, false);
666 if (uidState == null) {
667 if (mode == defaultMode) {
668 return;
669 }
670 uidState = new UidState(uid);
671 uidState.opModes = new SparseIntArray();
672 uidState.opModes.put(code, mode);
673 mUidStates.put(uid, uidState);
674 scheduleWriteLocked();
675 } else if (uidState.opModes == null) {
676 if (mode != defaultMode) {
677 uidState.opModes = new SparseIntArray();
678 uidState.opModes.put(code, mode);
679 scheduleWriteLocked();
680 }
681 } else {
682 if (uidState.opModes.get(code) == mode) {
683 return;
684 }
685 if (mode == defaultMode) {
686 uidState.opModes.delete(code);
687 if (uidState.opModes.size() <= 0) {
688 uidState.opModes = null;
689 }
690 } else {
691 uidState.opModes.put(code, mode);
692 }
693 scheduleWriteLocked();
694 }
695 }
696
Svetoslav215b44a2015-08-04 19:03:40 -0700697 String[] uidPackageNames = getPackagesForUid(uid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800698 ArrayMap<ModeCallback, ArraySet<String>> callbackSpecs = null;
Svet Ganov2af57082015-07-30 08:44:20 -0700699
riddle_hsu40b300f2015-11-23 13:22:03 +0800700 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800701 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -0700702 if (callbacks != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700703 final int callbackCount = callbacks.size();
704 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800705 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +0800706 ArraySet<String> changedPackages = new ArraySet<>();
707 Collections.addAll(changedPackages, uidPackageNames);
708 callbackSpecs = new ArrayMap<>();
709 callbackSpecs.put(callback, changedPackages);
710 }
711 }
712
713 for (String uidPackageName : uidPackageNames) {
714 callbacks = mPackageModeWatchers.get(uidPackageName);
715 if (callbacks != null) {
716 if (callbackSpecs == null) {
717 callbackSpecs = new ArrayMap<>();
Svet Ganov2af57082015-07-30 08:44:20 -0700718 }
riddle_hsu40b300f2015-11-23 13:22:03 +0800719 final int callbackCount = callbacks.size();
720 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800721 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +0800722 ArraySet<String> changedPackages = callbackSpecs.get(callback);
723 if (changedPackages == null) {
724 changedPackages = new ArraySet<>();
725 callbackSpecs.put(callback, changedPackages);
726 }
727 changedPackages.add(uidPackageName);
728 }
Svet Ganov2af57082015-07-30 08:44:20 -0700729 }
730 }
731 }
732
733 if (callbackSpecs == null) {
734 return;
735 }
736
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800737 for (int i = 0; i < callbackSpecs.size(); i++) {
738 final ModeCallback callback = callbackSpecs.keyAt(i);
739 final ArraySet<String> reportedPackageNames = callbackSpecs.valueAt(i);
740 if (reportedPackageNames == null) {
741 mHandler.sendMessage(PooledLambda.obtainMessage(
742 AppOpsService::notifyOpChanged,
743 this, callback, code, uid, (String) null));
744
745 } else {
746 final int reportedPackageCount = reportedPackageNames.size();
747 for (int j = 0; j < reportedPackageCount; j++) {
748 final String reportedPackageName = reportedPackageNames.valueAt(j);
749 mHandler.sendMessage(PooledLambda.obtainMessage(
750 AppOpsService::notifyOpChanged,
751 this, callback, code, uid, reportedPackageName));
Svet Ganov2af57082015-07-30 08:44:20 -0700752 }
753 }
Svet Ganov2af57082015-07-30 08:44:20 -0700754 }
755 }
756
757 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800758 public void setMode(int code, int uid, String packageName, int mode) {
Dianne Hackbornb64afe12014-07-22 16:29:04 -0700759 if (Binder.getCallingPid() != Process.myPid()) {
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -0800760 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
Dianne Hackbornb64afe12014-07-22 16:29:04 -0700761 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborn133b9df2014-07-01 13:06:10 -0700762 }
Dianne Hackborn961321f2013-02-05 17:22:41 -0800763 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800764 ArraySet<ModeCallback> repCbs = null;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800765 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800766 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700767 UidState uidState = getUidStateLocked(uid, false);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800768 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800769 if (op != null) {
770 if (op.mode != mode) {
771 op.mode = mode;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800772 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800773 if (cbs != null) {
774 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800775 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800776 }
777 repCbs.addAll(cbs);
778 }
779 cbs = mPackageModeWatchers.get(packageName);
780 if (cbs != null) {
781 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800782 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800783 }
784 repCbs.addAll(cbs);
785 }
David Braunf5d83192013-09-16 13:43:51 -0700786 if (mode == AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800787 // If going into the default mode, prune this op
788 // if there is nothing else interesting in it.
Dianne Hackborn607b4142013-08-02 18:10:10 -0700789 pruneOp(op, uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800790 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800791 scheduleFastWriteLocked();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800792 }
793 }
794 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800795 if (repCbs != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800796 mHandler.sendMessage(PooledLambda.obtainMessage(
797 AppOpsService::notifyOpChanged,
798 this, repCbs, code, uid, packageName));
Dianne Hackbornc2293022013-02-06 23:14:49 -0800799 }
800 }
801
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800802 private void notifyOpChanged(ArraySet<ModeCallback> callbacks, int code,
803 int uid, String packageName) {
804 for (int i = 0; i < callbacks.size(); i++) {
805 final ModeCallback callback = callbacks.valueAt(i);
806 notifyOpChanged(callback, code, uid, packageName);
807 }
808 }
809
810 private void notifyOpChanged(ModeCallback callback, int code,
811 int uid, String packageName) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700812 if (uid != UID_ANY && callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800813 return;
814 }
815 // There are components watching for mode changes such as window manager
816 // and location manager which are in our process. The callbacks in these
817 // components may require permissions our remote caller does not have.
818 final long identity = Binder.clearCallingIdentity();
819 try {
820 callback.mCallback.opChanged(code, uid, packageName);
821 } catch (RemoteException e) {
822 /* ignore */
823 } finally {
824 Binder.restoreCallingIdentity(identity);
825 }
826 }
827
828 private static HashMap<ModeCallback, ArrayList<ChangeRec>> addCallbacks(
829 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks,
830 int op, int uid, String packageName, ArraySet<ModeCallback> cbs) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700831 if (cbs == null) {
832 return callbacks;
833 }
834 if (callbacks == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700835 callbacks = new HashMap<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700836 }
Svet Ganov2af57082015-07-30 08:44:20 -0700837 boolean duplicate = false;
Dianne Hackborn68d76552017-02-27 15:32:03 -0800838 final int N = cbs.size();
839 for (int i=0; i<N; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800840 ModeCallback cb = cbs.valueAt(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700841 ArrayList<ChangeRec> reports = callbacks.get(cb);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700842 if (reports == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700843 reports = new ArrayList<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700844 callbacks.put(cb, reports);
Svet Ganov2af57082015-07-30 08:44:20 -0700845 } else {
846 final int reportCount = reports.size();
847 for (int j = 0; j < reportCount; j++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700848 ChangeRec report = reports.get(j);
849 if (report.op == op && report.pkg.equals(packageName)) {
Svet Ganov2af57082015-07-30 08:44:20 -0700850 duplicate = true;
851 break;
852 }
853 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700854 }
Svet Ganov2af57082015-07-30 08:44:20 -0700855 if (!duplicate) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700856 reports.add(new ChangeRec(op, uid, packageName));
Svet Ganov2af57082015-07-30 08:44:20 -0700857 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700858 }
859 return callbacks;
860 }
861
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700862 static final class ChangeRec {
863 final int op;
864 final int uid;
865 final String pkg;
866
867 ChangeRec(int _op, int _uid, String _pkg) {
868 op = _op;
869 uid = _uid;
870 pkg = _pkg;
871 }
872 }
873
Dianne Hackborn607b4142013-08-02 18:10:10 -0700874 @Override
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800875 public void resetAllModes(int reqUserId, String reqPackageName) {
876 final int callingPid = Binder.getCallingPid();
877 final int callingUid = Binder.getCallingUid();
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -0800878 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800879 callingPid, callingUid, null);
880 reqUserId = ActivityManager.handleIncomingUser(callingPid, callingUid, reqUserId,
881 true, true, "resetAllModes", null);
Svet Ganov2af57082015-07-30 08:44:20 -0700882
883 int reqUid = -1;
884 if (reqPackageName != null) {
885 try {
886 reqUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -0700887 reqPackageName, PackageManager.MATCH_UNINSTALLED_PACKAGES, reqUserId);
Svet Ganov2af57082015-07-30 08:44:20 -0700888 } catch (RemoteException e) {
889 /* ignore - local call */
890 }
891 }
892
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800893 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks = null;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700894 synchronized (this) {
895 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700896 for (int i = mUidStates.size() - 1; i >= 0; i--) {
897 UidState uidState = mUidStates.valueAt(i);
898
899 SparseIntArray opModes = uidState.opModes;
900 if (opModes != null && (uidState.uid == reqUid || reqUid == -1)) {
901 final int uidOpCount = opModes.size();
902 for (int j = uidOpCount - 1; j >= 0; j--) {
903 final int code = opModes.keyAt(j);
904 if (AppOpsManager.opAllowsReset(code)) {
905 opModes.removeAt(j);
906 if (opModes.size() <= 0) {
907 uidState.opModes = null;
908 }
909 for (String packageName : getPackagesForUid(uidState.uid)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700910 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700911 mOpModeWatchers.get(code));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700912 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700913 mPackageModeWatchers.get(packageName));
914 }
915 }
916 }
917 }
918
919 if (uidState.pkgOps == null) {
920 continue;
921 }
922
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800923 if (reqUserId != UserHandle.USER_ALL
Svet Ganov2af57082015-07-30 08:44:20 -0700924 && reqUserId != UserHandle.getUserId(uidState.uid)) {
Alexandra Gherghinad6a98972014-08-04 17:05:34 +0100925 // Skip any ops for a different user
926 continue;
927 }
Svet Ganov2af57082015-07-30 08:44:20 -0700928
929 Map<String, Ops> packages = uidState.pkgOps;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700930 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
931 while (it.hasNext()) {
932 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700933 String packageName = ent.getKey();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800934 if (reqPackageName != null && !reqPackageName.equals(packageName)) {
935 // Skip any ops for a different package
936 continue;
937 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700938 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700939 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700940 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -0700941 if (AppOpsManager.opAllowsReset(curOp.op)
942 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -0700943 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700944 changed = true;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700945 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -0700946 mOpModeWatchers.get(curOp.op));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700947 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -0700948 mPackageModeWatchers.get(packageName));
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700949 if (curOp.time == 0 && curOp.rejectTime == 0) {
950 pkgOps.removeAt(j);
951 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700952 }
953 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700954 if (pkgOps.size() == 0) {
955 it.remove();
956 }
957 }
Svet Ganov2af57082015-07-30 08:44:20 -0700958 if (uidState.isDefault()) {
959 mUidStates.remove(uidState.uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700960 }
961 }
Svet Ganov2af57082015-07-30 08:44:20 -0700962
Dianne Hackborn607b4142013-08-02 18:10:10 -0700963 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800964 scheduleFastWriteLocked();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700965 }
966 }
967 if (callbacks != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800968 for (Map.Entry<ModeCallback, ArrayList<ChangeRec>> ent : callbacks.entrySet()) {
969 ModeCallback cb = ent.getKey();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700970 ArrayList<ChangeRec> reports = ent.getValue();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700971 for (int i=0; i<reports.size(); i++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700972 ChangeRec rep = reports.get(i);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800973 mHandler.sendMessage(PooledLambda.obtainMessage(
974 AppOpsService::notifyOpChanged,
975 this, cb, rep.op, rep.uid, rep.pkg));
Dianne Hackborn607b4142013-08-02 18:10:10 -0700976 }
977 }
978 }
979 }
980
Dianne Hackbornc2293022013-02-06 23:14:49 -0800981 @Override
982 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800983 int watchedUid = -1;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700984 final int callingUid = Binder.getCallingUid();
985 final int callingPid = Binder.getCallingPid();
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800986 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
987 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700988 watchedUid = callingUid;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800989 }
990 Preconditions.checkArgumentInRange(op, AppOpsManager.OP_NONE,
991 AppOpsManager._NUM_OP - 1, "Invalid op code: " + op);
Svetoslav Ganov8de59712015-12-09 18:25:13 -0800992 if (callback == null) {
993 return;
994 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800995 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700996 op = (op != AppOpsManager.OP_NONE) ? AppOpsManager.opToSwitch(op) : op;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800997 ModeCallback cb = mModeWatchers.get(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -0800998 if (cb == null) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700999 cb = new ModeCallback(callback, watchedUid, callingUid, callingPid);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001000 mModeWatchers.put(callback.asBinder(), cb);
1001 }
1002 if (op != AppOpsManager.OP_NONE) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001003 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(op);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001004 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08001005 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001006 mOpModeWatchers.put(op, cbs);
1007 }
1008 cbs.add(cb);
1009 }
1010 if (packageName != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001011 ArraySet<ModeCallback> cbs = mPackageModeWatchers.get(packageName);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001012 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08001013 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001014 mPackageModeWatchers.put(packageName, cbs);
1015 }
1016 cbs.add(cb);
1017 }
1018 }
1019 }
1020
1021 @Override
1022 public void stopWatchingMode(IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -08001023 if (callback == null) {
1024 return;
1025 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001026 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001027 ModeCallback cb = mModeWatchers.remove(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -08001028 if (cb != null) {
1029 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001030 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001031 ArraySet<ModeCallback> cbs = mOpModeWatchers.valueAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001032 cbs.remove(cb);
1033 if (cbs.size() <= 0) {
1034 mOpModeWatchers.removeAt(i);
1035 }
1036 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001037 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001038 ArraySet<ModeCallback> cbs = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001039 cbs.remove(cb);
1040 if (cbs.size() <= 0) {
1041 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001042 }
1043 }
1044 }
1045 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001046 }
1047
1048 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001049 public IBinder getToken(IBinder clientToken) {
1050 synchronized (this) {
1051 ClientState cs = mClients.get(clientToken);
1052 if (cs == null) {
1053 cs = new ClientState(clientToken);
1054 mClients.put(clientToken, cs);
1055 }
1056 return cs;
1057 }
1058 }
1059
1060 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -08001061 public int checkOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001062 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001063 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001064 String resolvedPackageName = resolvePackageName(uid, packageName);
1065 if (resolvedPackageName == null) {
1066 return AppOpsManager.MODE_IGNORED;
1067 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001068 synchronized (this) {
Svet Ganov442ed572016-08-17 17:29:43 -07001069 if (isOpRestrictedLocked(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001070 return AppOpsManager.MODE_IGNORED;
1071 }
Svet Ganov2af57082015-07-30 08:44:20 -07001072 code = AppOpsManager.opToSwitch(code);
1073 UidState uidState = getUidStateLocked(uid, false);
Svet Ganovee438d42017-01-19 18:04:38 -08001074 if (uidState != null && uidState.opModes != null
1075 && uidState.opModes.indexOfKey(code) >= 0) {
1076 return uidState.opModes.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001077 }
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001078 Op op = getOpLocked(code, uid, resolvedPackageName, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001079 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -07001080 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001081 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001082 return op.mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001083 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001084 }
1085
1086 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001087 public int checkAudioOperation(int code, int usage, int uid, String packageName) {
Andrei Stingaceanuefc4a342016-03-22 14:43:01 +00001088 boolean suspended;
1089 try {
1090 suspended = isPackageSuspendedForUser(packageName, uid);
1091 } catch (IllegalArgumentException ex) {
1092 // Package not found.
1093 suspended = false;
1094 }
1095
1096 if (suspended) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001097 Slog.i(TAG, "Audio disabled for suspended package=" + packageName + " for uid=" + uid);
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001098 return AppOpsManager.MODE_IGNORED;
1099 }
1100
John Spurlock1af30c72014-03-10 08:33:35 -04001101 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001102 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -04001103 if (mode != AppOpsManager.MODE_ALLOWED) {
1104 return mode;
1105 }
1106 }
1107 return checkOperation(code, uid, packageName);
1108 }
1109
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001110 private boolean isPackageSuspendedForUser(String pkg, int uid) {
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001111 try {
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001112 return AppGlobals.getPackageManager().isPackageSuspendedForUser(
1113 pkg, UserHandle.getUserId(uid));
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001114 } catch (RemoteException re) {
1115 throw new SecurityException("Could not talk to package manager service");
1116 }
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001117 }
1118
John Spurlock7b414672014-07-18 13:02:39 -04001119 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
1120 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1121 if (usageRestrictions != null) {
1122 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001123 if (r != null && !r.exceptionPackages.contains(packageName)) {
1124 return r.mode;
1125 }
1126 }
1127 return AppOpsManager.MODE_ALLOWED;
1128 }
1129
1130 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001131 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -04001132 String[] exceptionPackages) {
1133 verifyIncomingUid(uid);
1134 verifyIncomingOp(code);
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -08001135 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
1136 Binder.getCallingPid(), Binder.getCallingUid(), null);
John Spurlock1af30c72014-03-10 08:33:35 -04001137 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001138 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1139 if (usageRestrictions == null) {
1140 usageRestrictions = new SparseArray<Restriction>();
1141 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -04001142 }
John Spurlock7b414672014-07-18 13:02:39 -04001143 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001144 if (mode != AppOpsManager.MODE_ALLOWED) {
1145 final Restriction r = new Restriction();
1146 r.mode = mode;
1147 if (exceptionPackages != null) {
1148 final int N = exceptionPackages.length;
1149 r.exceptionPackages = new ArraySet<String>(N);
1150 for (int i = 0; i < N; i++) {
1151 final String pkg = exceptionPackages[i];
1152 if (pkg != null) {
1153 r.exceptionPackages.add(pkg.trim());
1154 }
1155 }
1156 }
John Spurlock7b414672014-07-18 13:02:39 -04001157 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -04001158 }
1159 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001160
1161 mHandler.sendMessage(PooledLambda.obtainMessage(
Svet Ganov3a95f832018-03-23 17:44:30 -07001162 AppOpsService::notifyWatchersOfChange, this, code, UID_ANY));
John Spurlock1af30c72014-03-10 08:33:35 -04001163 }
1164
1165 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001166 public int checkPackage(int uid, String packageName) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001167 Preconditions.checkNotNull(packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001168 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001169 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1170 true /* uidMismatchExpected */);
1171 if (ops != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001172 return AppOpsManager.MODE_ALLOWED;
1173 } else {
1174 return AppOpsManager.MODE_ERRORED;
1175 }
1176 }
1177 }
1178
1179 @Override
Svet Ganov99b60432015-06-27 13:15:22 -07001180 public int noteProxyOperation(int code, String proxyPackageName,
1181 int proxiedUid, String proxiedPackageName) {
1182 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001183 final int proxyUid = Binder.getCallingUid();
1184 String resolveProxyPackageName = resolvePackageName(proxyUid, proxyPackageName);
1185 if (resolveProxyPackageName == null) {
1186 return AppOpsManager.MODE_IGNORED;
1187 }
1188 final int proxyMode = noteOperationUnchecked(code, proxyUid,
1189 resolveProxyPackageName, -1, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001190 if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
1191 return proxyMode;
1192 }
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001193 String resolveProxiedPackageName = resolvePackageName(proxiedUid, proxiedPackageName);
1194 if (resolveProxiedPackageName == null) {
1195 return AppOpsManager.MODE_IGNORED;
1196 }
1197 return noteOperationUnchecked(code, proxiedUid, resolveProxiedPackageName,
1198 proxyMode, resolveProxyPackageName);
Svet Ganov99b60432015-06-27 13:15:22 -07001199 }
1200
1201 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001202 public int noteOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001203 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001204 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001205 String resolvedPackageName = resolvePackageName(uid, packageName);
1206 if (resolvedPackageName == null) {
1207 return AppOpsManager.MODE_IGNORED;
1208 }
1209 return noteOperationUnchecked(code, uid, resolvedPackageName, 0, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001210 }
1211
1212 private int noteOperationUnchecked(int code, int uid, String packageName,
1213 int proxyUid, String proxyPackageName) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001214 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001215 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1216 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001217 if (ops == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001218 if (DEBUG) Slog.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001219 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001220 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001221 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001222 Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07001223 if (isOpRestrictedLocked(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001224 return AppOpsManager.MODE_IGNORED;
1225 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001226 if (op.duration == -1) {
1227 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
1228 + " code " + code + " time=" + op.time + " duration=" + op.duration);
1229 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001230 op.duration = 0;
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001231 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001232 UidState uidState = ops.uidState;
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001233 // If there is a non-default per UID policy (we set UID op mode only if
1234 // non-default) it takes over, otherwise use the per package policy.
1235 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -07001236 final int uidMode = uidState.opModes.get(switchCode);
1237 if (uidMode != AppOpsManager.MODE_ALLOWED) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001238 if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + op.mode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07001239 + switchCode + " (" + code + ") uid " + uid + " package "
1240 + packageName);
1241 op.rejectTime = System.currentTimeMillis();
1242 return uidMode;
1243 }
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001244 } else {
1245 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
1246 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001247 if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + op.mode + " for code "
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001248 + switchCode + " (" + code + ") uid " + uid + " package "
1249 + packageName);
1250 op.rejectTime = System.currentTimeMillis();
1251 return switchOp.mode;
1252 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001253 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001254 if (DEBUG) Slog.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001255 + " package " + packageName);
1256 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001257 op.rejectTime = 0;
Svet Ganov99b60432015-06-27 13:15:22 -07001258 op.proxyUid = proxyUid;
1259 op.proxyPackageName = proxyPackageName;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001260 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001261 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001262 }
1263
1264 @Override
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001265 public void startWatchingActive(int[] ops, IAppOpsActiveCallback callback) {
Svet Ganovf7b47252018-02-26 11:11:27 -08001266 int watchedUid = -1;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001267 final int callingUid = Binder.getCallingUid();
1268 final int callingPid = Binder.getCallingPid();
Svet Ganovf7b47252018-02-26 11:11:27 -08001269 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
1270 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001271 watchedUid = callingUid;
Svet Ganovf7b47252018-02-26 11:11:27 -08001272 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001273 if (ops != null) {
1274 Preconditions.checkArrayElementsInRange(ops, 0,
1275 AppOpsManager._NUM_OP - 1, "Invalid op code in: " + Arrays.toString(ops));
1276 }
1277 if (callback == null) {
1278 return;
1279 }
1280 synchronized (this) {
1281 SparseArray<ActiveCallback> callbacks = mActiveWatchers.get(callback.asBinder());
1282 if (callbacks == null) {
1283 callbacks = new SparseArray<>();
1284 mActiveWatchers.put(callback.asBinder(), callbacks);
1285 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001286 final ActiveCallback activeCallback = new ActiveCallback(callback, watchedUid,
1287 callingUid, callingPid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001288 for (int op : ops) {
1289 callbacks.put(op, activeCallback);
1290 }
1291 }
1292 }
1293
1294 @Override
1295 public void stopWatchingActive(IAppOpsActiveCallback callback) {
1296 if (callback == null) {
1297 return;
1298 }
1299 synchronized (this) {
1300 final SparseArray<ActiveCallback> activeCallbacks =
1301 mActiveWatchers.remove(callback.asBinder());
1302 if (activeCallbacks == null) {
1303 return;
1304 }
1305 final int callbackCount = activeCallbacks.size();
1306 for (int i = 0; i < callbackCount; i++) {
1307 // Apps ops are mapped to a singleton
1308 if (i == 0) {
1309 activeCallbacks.valueAt(i).destroy();
1310 }
1311 }
1312 }
1313 }
1314
1315 @Override
Svet Ganovf7b47252018-02-26 11:11:27 -08001316 public int startOperation(IBinder token, int code, int uid, String packageName,
1317 boolean startIfModeDefault) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001318 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001319 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001320 String resolvedPackageName = resolvePackageName(uid, packageName);
1321 if (resolvedPackageName == null) {
1322 return AppOpsManager.MODE_IGNORED;
1323 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001324 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001325 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001326 Ops ops = getOpsRawLocked(uid, resolvedPackageName, true /* edit */,
1327 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001328 if (ops == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001329 if (DEBUG) Slog.d(TAG, "startOperation: no op for code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001330 + " package " + resolvedPackageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001331 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001332 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001333 Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07001334 if (isOpRestrictedLocked(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001335 return AppOpsManager.MODE_IGNORED;
1336 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001337 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001338 UidState uidState = ops.uidState;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001339 // If there is a non-default per UID policy (we set UID op mode only if
1340 // non-default) it takes over, otherwise use the per package policy.
1341 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -07001342 final int uidMode = uidState.opModes.get(switchCode);
Svet Ganovf7b47252018-02-26 11:11:27 -08001343 if (uidMode != AppOpsManager.MODE_ALLOWED
1344 && (!startIfModeDefault || uidMode != AppOpsManager.MODE_DEFAULT)) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001345 if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + op.mode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07001346 + switchCode + " (" + code + ") uid " + uid + " package "
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001347 + resolvedPackageName);
Svet Ganov2af57082015-07-30 08:44:20 -07001348 op.rejectTime = System.currentTimeMillis();
1349 return uidMode;
1350 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001351 } else {
1352 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
Svet Ganovf7b47252018-02-26 11:11:27 -08001353 if (switchOp.mode != AppOpsManager.MODE_ALLOWED
1354 && (!startIfModeDefault || switchOp.mode != AppOpsManager.MODE_DEFAULT)) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001355 if (DEBUG) Slog.d(TAG, "startOperation: reject #" + op.mode + " for code "
1356 + switchCode + " (" + code + ") uid " + uid + " package "
1357 + resolvedPackageName);
1358 op.rejectTime = System.currentTimeMillis();
1359 return switchOp.mode;
1360 }
Svet Ganov2af57082015-07-30 08:44:20 -07001361 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001362 if (DEBUG) Slog.d(TAG, "startOperation: allowing code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001363 + " package " + resolvedPackageName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001364 if (op.nesting == 0) {
1365 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001366 op.rejectTime = 0;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001367 op.duration = -1;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001368 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001369 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001370 op.nesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001371 if (client.mStartedOps != null) {
1372 client.mStartedOps.add(op);
1373 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001374 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001375
1376 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001377 }
1378
1379 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001380 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001381 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001382 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001383 String resolvedPackageName = resolvePackageName(uid, packageName);
1384 if (resolvedPackageName == null) {
1385 return;
1386 }
1387 if (!(token instanceof ClientState)) {
1388 return;
1389 }
1390 ClientState client = (ClientState) token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001391 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001392 Op op = getOpLocked(code, uid, resolvedPackageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001393 if (op == null) {
1394 return;
1395 }
Svet Ganovf7b47252018-02-26 11:11:27 -08001396 if (!client.mStartedOps.remove(op)) {
Svet Ganovf5d5af12018-03-18 11:51:17 -07001397 // We finish ops when packages get removed to guarantee no dangling
1398 // started ops. However, some part of the system may asynchronously
1399 // finish ops for an already gone package. Hence, finishing an op
1400 // for a non existing package is fine and we don't log as a wtf.
1401 final long identity = Binder.clearCallingIdentity();
1402 try {
1403 if (LocalServices.getService(PackageManagerInternal.class).getPackageUid(
1404 resolvedPackageName, 0, UserHandle.getUserId(uid)) < 0) {
1405 Slog.i(TAG, "Finishing op=" + AppOpsManager.opToName(code)
1406 + " for non-existing package=" + resolvedPackageName
1407 + " in uid=" + uid);
1408 return;
1409 }
1410 } finally {
1411 Binder.restoreCallingIdentity(identity);
1412 }
1413 Slog.wtf(TAG, "Operation not started: uid=" + op.uid + " pkg="
1414 + op.packageName + " op=" + AppOpsManager.opToName(op.op));
Svet Ganov31d83ae2018-03-15 10:45:56 -07001415 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001416 }
Svet Ganova7a0db62018-02-27 20:08:01 -08001417 finishOperationLocked(op, /*finishNested*/ false);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001418 if (op.nesting <= 0) {
1419 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, false);
1420 }
1421 }
1422 }
1423
1424 private void scheduleOpActiveChangedIfNeededLocked(int code, int uid, String packageName,
1425 boolean active) {
1426 ArraySet<ActiveCallback> dispatchedCallbacks = null;
1427 final int callbackListCount = mActiveWatchers.size();
1428 for (int i = 0; i < callbackListCount; i++) {
1429 final SparseArray<ActiveCallback> callbacks = mActiveWatchers.valueAt(i);
1430 ActiveCallback callback = callbacks.get(code);
1431 if (callback != null) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001432 if (callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
Svet Ganovf7b47252018-02-26 11:11:27 -08001433 continue;
1434 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001435 if (dispatchedCallbacks == null) {
1436 dispatchedCallbacks = new ArraySet<>();
1437 }
1438 dispatchedCallbacks.add(callback);
1439 }
1440 }
1441 if (dispatchedCallbacks == null) {
1442 return;
1443 }
1444 mHandler.sendMessage(PooledLambda.obtainMessage(
1445 AppOpsService::notifyOpActiveChanged,
1446 this, dispatchedCallbacks, code, uid, packageName, active));
1447 }
1448
1449 private void notifyOpActiveChanged(ArraySet<ActiveCallback> callbacks,
1450 int code, int uid, String packageName, boolean active) {
1451 // There are components watching for mode changes such as window manager
1452 // and location manager which are in our process. The callbacks in these
1453 // components may require permissions our remote caller does not have.
1454 final long identity = Binder.clearCallingIdentity();
1455 try {
1456 final int callbackCount = callbacks.size();
1457 for (int i = 0; i < callbackCount; i++) {
1458 final ActiveCallback callback = callbacks.valueAt(i);
1459 try {
1460 callback.mCallback.opActiveChanged(code, uid, packageName, active);
1461 } catch (RemoteException e) {
1462 /* do nothing */
1463 }
1464 }
1465 } finally {
1466 Binder.restoreCallingIdentity(identity);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001467 }
1468 }
1469
Svet Ganovb9d71a62015-04-30 10:38:13 -07001470 @Override
1471 public int permissionToOpCode(String permission) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001472 if (permission == null) {
1473 return AppOpsManager.OP_NONE;
1474 }
Svet Ganovb9d71a62015-04-30 10:38:13 -07001475 return AppOpsManager.permissionToOpCode(permission);
1476 }
1477
Svet Ganova7a0db62018-02-27 20:08:01 -08001478 void finishOperationLocked(Op op, boolean finishNested) {
1479 if (op.nesting <= 1 || finishNested) {
1480 if (op.nesting == 1 || finishNested) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001481 op.duration = (int)(System.currentTimeMillis() - op.time);
1482 op.time += op.duration;
1483 } else {
1484 Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
1485 + op.packageName + " code " + op.op + " time=" + op.time
1486 + " duration=" + op.duration + " nesting=" + op.nesting);
1487 }
1488 op.nesting = 0;
1489 } else {
1490 op.nesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001491 }
1492 }
1493
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001494 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001495 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001496 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001497 }
1498 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001499 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001500 }
1501 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
1502 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001503 }
1504
Dianne Hackborn961321f2013-02-05 17:22:41 -08001505 private void verifyIncomingOp(int op) {
1506 if (op >= 0 && op < AppOpsManager._NUM_OP) {
1507 return;
1508 }
1509 throw new IllegalArgumentException("Bad operation #" + op);
1510 }
1511
Svet Ganov2af57082015-07-30 08:44:20 -07001512 private UidState getUidStateLocked(int uid, boolean edit) {
1513 UidState uidState = mUidStates.get(uid);
1514 if (uidState == null) {
1515 if (!edit) {
1516 return null;
1517 }
1518 uidState = new UidState(uid);
1519 mUidStates.put(uid, uidState);
1520 }
1521 return uidState;
1522 }
1523
Yohei Yukawaa965d652017-10-12 15:02:26 -07001524 private Ops getOpsRawLocked(int uid, String packageName, boolean edit,
1525 boolean uidMismatchExpected) {
Svet Ganov2af57082015-07-30 08:44:20 -07001526 UidState uidState = getUidStateLocked(uid, edit);
1527 if (uidState == null) {
1528 return null;
1529 }
1530
1531 if (uidState.pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001532 if (!edit) {
1533 return null;
1534 }
Svet Ganov2af57082015-07-30 08:44:20 -07001535 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001536 }
Svet Ganov2af57082015-07-30 08:44:20 -07001537
1538 Ops ops = uidState.pkgOps.get(packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001539 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001540 if (!edit) {
1541 return null;
1542 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001543 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001544 // This is the first time we have seen this package name under this uid,
1545 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -08001546 if (uid != 0) {
1547 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001548 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001549 int pkgUid = -1;
1550 try {
Jason Monk1c7c3192014-06-26 12:52:18 -04001551 ApplicationInfo appInfo = ActivityThread.getPackageManager()
Jeff Sharkeycd654482016-01-08 17:42:11 -07001552 .getApplicationInfo(packageName,
1553 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1554 UserHandle.getUserId(uid));
Jason Monk1c7c3192014-06-26 12:52:18 -04001555 if (appInfo != null) {
1556 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001557 isPrivileged = (appInfo.privateFlags
1558 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001559 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08001560 pkgUid = resolveUid(packageName);
1561 if (pkgUid >= 0) {
Chien-Yu Chen75cade02016-01-11 10:56:21 -08001562 isPrivileged = false;
Jason Monk1c7c3192014-06-26 12:52:18 -04001563 }
Dianne Hackborn713df152013-05-17 11:27:57 -07001564 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001565 } catch (RemoteException e) {
1566 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001567 }
1568 if (pkgUid != uid) {
1569 // Oops! The package name is not valid for the uid they are calling
1570 // under. Abort.
Yohei Yukawaa965d652017-10-12 15:02:26 -07001571 if (!uidMismatchExpected) {
1572 RuntimeException ex = new RuntimeException("here");
1573 ex.fillInStackTrace();
1574 Slog.w(TAG, "Bad call: specified package " + packageName
1575 + " under uid " + uid + " but it is really " + pkgUid, ex);
1576 }
Dianne Hackborn514074f2013-02-11 10:52:46 -08001577 return null;
1578 }
1579 } finally {
1580 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001581 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001582 }
Svet Ganov2af57082015-07-30 08:44:20 -07001583 ops = new Ops(packageName, uidState, isPrivileged);
1584 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001585 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08001586 return ops;
1587 }
1588
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001589 private void scheduleWriteLocked() {
1590 if (!mWriteScheduled) {
1591 mWriteScheduled = true;
1592 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
1593 }
1594 }
1595
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001596 private void scheduleFastWriteLocked() {
1597 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001598 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001599 mFastWriteScheduled = true;
1600 mHandler.removeCallbacks(mWriteRunner);
1601 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001602 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001603 }
1604
Dianne Hackborn72e39832013-01-18 18:36:09 -08001605 private Op getOpLocked(int code, int uid, String packageName, boolean edit) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001606 Ops ops = getOpsRawLocked(uid, packageName, edit,
1607 false /* uidMismatchExpected */);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001608 if (ops == null) {
1609 return null;
1610 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001611 return getOpLocked(ops, code, edit);
1612 }
1613
1614 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001615 Op op = ops.get(code);
1616 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001617 if (!edit) {
1618 return null;
1619 }
Svet Ganov2af57082015-07-30 08:44:20 -07001620 op = new Op(ops.uidState.uid, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001621 ops.put(code, op);
1622 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001623 if (edit) {
1624 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001625 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001626 return op;
1627 }
1628
Svet Ganov442ed572016-08-17 17:29:43 -07001629 private boolean isOpRestrictedLocked(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04001630 int userHandle = UserHandle.getUserId(uid);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001631 final int restrictionSetCount = mOpUserRestrictions.size();
Ruben Brunk29931bc2016-03-11 00:24:26 -08001632
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001633 for (int i = 0; i < restrictionSetCount; i++) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08001634 // For each client, check that the given op is not restricted, or that the given
1635 // package is exempt from the restriction.
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07001636 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07001637 if (restrictionState.hasRestriction(code, packageName, userHandle)) {
1638 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
1639 // If we are the system, bypass user restrictions for certain codes
1640 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001641 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1642 false /* uidMismatchExpected */);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07001643 if ((ops != null) && ops.isPrivileged) {
1644 return false;
1645 }
Ruben Brunk32f0fa42016-03-11 19:07:07 -08001646 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08001647 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001648 return true;
Jason Monk1c7c3192014-06-26 12:52:18 -04001649 }
Jason Monk62062992014-05-06 09:55:28 -04001650 }
1651 return false;
1652 }
1653
Dianne Hackborn35654b62013-01-14 17:38:02 -08001654 void readState() {
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001655 int oldVersion = NO_VERSION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001656 synchronized (mFile) {
1657 synchronized (this) {
1658 FileInputStream stream;
1659 try {
1660 stream = mFile.openRead();
1661 } catch (FileNotFoundException e) {
1662 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
1663 return;
1664 }
1665 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001666 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001667 try {
1668 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001669 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001670 int type;
1671 while ((type = parser.next()) != XmlPullParser.START_TAG
1672 && type != XmlPullParser.END_DOCUMENT) {
1673 ;
1674 }
1675
1676 if (type != XmlPullParser.START_TAG) {
1677 throw new IllegalStateException("no start tag found");
1678 }
1679
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001680 final String versionString = parser.getAttributeValue(null, "v");
1681 if (versionString != null) {
1682 oldVersion = Integer.parseInt(versionString);
1683 }
1684
Dianne Hackborn35654b62013-01-14 17:38:02 -08001685 int outerDepth = parser.getDepth();
1686 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1687 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1688 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1689 continue;
1690 }
1691
1692 String tagName = parser.getName();
1693 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001694 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07001695 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07001696 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001697 } else {
1698 Slog.w(TAG, "Unknown element under <app-ops>: "
1699 + parser.getName());
1700 XmlUtils.skipCurrentTag(parser);
1701 }
1702 }
1703 success = true;
1704 } catch (IllegalStateException e) {
1705 Slog.w(TAG, "Failed parsing " + e);
1706 } catch (NullPointerException e) {
1707 Slog.w(TAG, "Failed parsing " + e);
1708 } catch (NumberFormatException e) {
1709 Slog.w(TAG, "Failed parsing " + e);
1710 } catch (XmlPullParserException e) {
1711 Slog.w(TAG, "Failed parsing " + e);
1712 } catch (IOException e) {
1713 Slog.w(TAG, "Failed parsing " + e);
1714 } catch (IndexOutOfBoundsException e) {
1715 Slog.w(TAG, "Failed parsing " + e);
1716 } finally {
1717 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07001718 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001719 }
1720 try {
1721 stream.close();
1722 } catch (IOException e) {
1723 }
1724 }
1725 }
1726 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001727 synchronized (this) {
1728 upgradeLocked(oldVersion);
1729 }
1730 }
1731
1732 private void upgradeRunAnyInBackgroundLocked() {
1733 for (int i = 0; i < mUidStates.size(); i++) {
1734 final UidState uidState = mUidStates.valueAt(i);
1735 if (uidState == null) {
1736 continue;
1737 }
1738 if (uidState.opModes != null) {
1739 final int idx = uidState.opModes.indexOfKey(AppOpsManager.OP_RUN_IN_BACKGROUND);
1740 if (idx >= 0) {
1741 uidState.opModes.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND,
1742 uidState.opModes.valueAt(idx));
1743 }
1744 }
1745 if (uidState.pkgOps == null) {
1746 continue;
1747 }
1748 for (int j = 0; j < uidState.pkgOps.size(); j++) {
1749 Ops ops = uidState.pkgOps.valueAt(j);
1750 if (ops != null) {
1751 final Op op = ops.get(AppOpsManager.OP_RUN_IN_BACKGROUND);
1752 if (op != null && op.mode != AppOpsManager.opToDefaultMode(op.op)) {
1753 final Op copy = new Op(op.uid, op.packageName,
1754 AppOpsManager.OP_RUN_ANY_IN_BACKGROUND);
1755 copy.mode = op.mode;
1756 ops.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, copy);
1757 }
1758 }
1759 }
1760 }
1761 }
1762
1763 private void upgradeLocked(int oldVersion) {
1764 if (oldVersion >= CURRENT_VERSION) {
1765 return;
1766 }
1767 Slog.d(TAG, "Upgrading app-ops xml from version " + oldVersion + " to " + CURRENT_VERSION);
1768 switch (oldVersion) {
1769 case NO_VERSION:
1770 upgradeRunAnyInBackgroundLocked();
1771 // fall through
1772 case 1:
1773 // for future upgrades
1774 }
1775 scheduleFastWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001776 }
1777
Svet Ganov2af57082015-07-30 08:44:20 -07001778 void readUidOps(XmlPullParser parser) throws NumberFormatException,
1779 XmlPullParserException, IOException {
1780 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
1781 int outerDepth = parser.getDepth();
1782 int type;
1783 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1784 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1785 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1786 continue;
1787 }
1788
1789 String tagName = parser.getName();
1790 if (tagName.equals("op")) {
1791 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
1792 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
1793 UidState uidState = getUidStateLocked(uid, true);
1794 if (uidState.opModes == null) {
1795 uidState.opModes = new SparseIntArray();
1796 }
1797 uidState.opModes.put(code, mode);
1798 } else {
1799 Slog.w(TAG, "Unknown element under <uid-ops>: "
1800 + parser.getName());
1801 XmlUtils.skipCurrentTag(parser);
1802 }
1803 }
1804 }
1805
Dave Burke0997c5bd2013-08-02 20:25:02 +00001806 void readPackage(XmlPullParser parser) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001807 XmlPullParserException, IOException {
1808 String pkgName = parser.getAttributeValue(null, "n");
1809 int outerDepth = parser.getDepth();
1810 int type;
1811 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1812 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1813 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1814 continue;
1815 }
1816
1817 String tagName = parser.getName();
1818 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001819 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001820 } else {
1821 Slog.w(TAG, "Unknown element under <pkg>: "
1822 + parser.getName());
1823 XmlUtils.skipCurrentTag(parser);
1824 }
1825 }
1826 }
1827
Dave Burke0997c5bd2013-08-02 20:25:02 +00001828 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001829 XmlPullParserException, IOException {
1830 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Jason Monk1c7c3192014-06-26 12:52:18 -04001831 String isPrivilegedString = parser.getAttributeValue(null, "p");
1832 boolean isPrivileged = false;
1833 if (isPrivilegedString == null) {
1834 try {
1835 IPackageManager packageManager = ActivityThread.getPackageManager();
1836 if (packageManager != null) {
1837 ApplicationInfo appInfo = ActivityThread.getPackageManager()
1838 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
1839 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001840 isPrivileged = (appInfo.privateFlags
1841 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001842 }
1843 } else {
1844 // Could not load data, don't add to cache so it will be loaded later.
1845 return;
1846 }
1847 } catch (RemoteException e) {
1848 Slog.w(TAG, "Could not contact PackageManager", e);
1849 }
1850 } else {
1851 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
1852 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001853 int outerDepth = parser.getDepth();
1854 int type;
1855 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1856 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1857 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1858 continue;
1859 }
1860
1861 String tagName = parser.getName();
1862 if (tagName.equals("op")) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001863 Op op = new Op(uid, pkgName, Integer.parseInt(parser.getAttributeValue(null, "n")));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001864 String mode = parser.getAttributeValue(null, "m");
1865 if (mode != null) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001866 op.mode = Integer.parseInt(mode);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001867 }
1868 String time = parser.getAttributeValue(null, "t");
1869 if (time != null) {
1870 op.time = Long.parseLong(time);
1871 }
1872 time = parser.getAttributeValue(null, "r");
1873 if (time != null) {
1874 op.rejectTime = Long.parseLong(time);
1875 }
1876 String dur = parser.getAttributeValue(null, "d");
1877 if (dur != null) {
1878 op.duration = Integer.parseInt(dur);
1879 }
Svet Ganov99b60432015-06-27 13:15:22 -07001880 String proxyUid = parser.getAttributeValue(null, "pu");
1881 if (proxyUid != null) {
1882 op.proxyUid = Integer.parseInt(proxyUid);
1883 }
1884 String proxyPackageName = parser.getAttributeValue(null, "pp");
1885 if (proxyPackageName != null) {
1886 op.proxyPackageName = proxyPackageName;
1887 }
Svet Ganov2af57082015-07-30 08:44:20 -07001888
1889 UidState uidState = getUidStateLocked(uid, true);
1890 if (uidState.pkgOps == null) {
1891 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001892 }
Svet Ganov2af57082015-07-30 08:44:20 -07001893
1894 Ops ops = uidState.pkgOps.get(pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001895 if (ops == null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001896 ops = new Ops(pkgName, uidState, isPrivileged);
1897 uidState.pkgOps.put(pkgName, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001898 }
1899 ops.put(op.op, op);
1900 } else {
1901 Slog.w(TAG, "Unknown element under <pkg>: "
1902 + parser.getName());
1903 XmlUtils.skipCurrentTag(parser);
1904 }
1905 }
1906 }
1907
1908 void writeState() {
1909 synchronized (mFile) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001910 FileOutputStream stream;
1911 try {
1912 stream = mFile.startWrite();
1913 } catch (IOException e) {
1914 Slog.w(TAG, "Failed to write state: " + e);
1915 return;
1916 }
1917
Dianne Hackborne17b4452018-01-10 13:15:40 -08001918 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
1919
Dianne Hackborn35654b62013-01-14 17:38:02 -08001920 try {
1921 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001922 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001923 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001924 out.startTag(null, "app-ops");
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001925 out.attribute(null, "v", String.valueOf(CURRENT_VERSION));
Svet Ganov2af57082015-07-30 08:44:20 -07001926
1927 final int uidStateCount = mUidStates.size();
1928 for (int i = 0; i < uidStateCount; i++) {
1929 UidState uidState = mUidStates.valueAt(i);
1930 if (uidState.opModes != null && uidState.opModes.size() > 0) {
1931 out.startTag(null, "uid");
1932 out.attribute(null, "n", Integer.toString(uidState.uid));
1933 SparseIntArray uidOpModes = uidState.opModes;
1934 final int opCount = uidOpModes.size();
1935 for (int j = 0; j < opCount; j++) {
1936 final int op = uidOpModes.keyAt(j);
1937 final int mode = uidOpModes.valueAt(j);
1938 out.startTag(null, "op");
1939 out.attribute(null, "n", Integer.toString(op));
1940 out.attribute(null, "m", Integer.toString(mode));
1941 out.endTag(null, "op");
1942 }
1943 out.endTag(null, "uid");
1944 }
1945 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001946
1947 if (allOps != null) {
1948 String lastPkg = null;
1949 for (int i=0; i<allOps.size(); i++) {
1950 AppOpsManager.PackageOps pkg = allOps.get(i);
1951 if (!pkg.getPackageName().equals(lastPkg)) {
1952 if (lastPkg != null) {
1953 out.endTag(null, "pkg");
1954 }
1955 lastPkg = pkg.getPackageName();
1956 out.startTag(null, "pkg");
1957 out.attribute(null, "n", lastPkg);
1958 }
1959 out.startTag(null, "uid");
1960 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04001961 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001962 Ops ops = getOpsRawLocked(pkg.getUid(), pkg.getPackageName(),
1963 false /* edit */, false /* uidMismatchExpected */);
Jason Monk1c7c3192014-06-26 12:52:18 -04001964 // Should always be present as the list of PackageOps is generated
1965 // from Ops.
1966 if (ops != null) {
1967 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
1968 } else {
1969 out.attribute(null, "p", Boolean.toString(false));
1970 }
1971 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001972 List<AppOpsManager.OpEntry> ops = pkg.getOps();
1973 for (int j=0; j<ops.size(); j++) {
1974 AppOpsManager.OpEntry op = ops.get(j);
1975 out.startTag(null, "op");
1976 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07001977 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001978 out.attribute(null, "m", Integer.toString(op.getMode()));
1979 }
1980 long time = op.getTime();
1981 if (time != 0) {
1982 out.attribute(null, "t", Long.toString(time));
1983 }
1984 time = op.getRejectTime();
1985 if (time != 0) {
1986 out.attribute(null, "r", Long.toString(time));
1987 }
1988 int dur = op.getDuration();
1989 if (dur != 0) {
1990 out.attribute(null, "d", Integer.toString(dur));
1991 }
Svet Ganov99b60432015-06-27 13:15:22 -07001992 int proxyUid = op.getProxyUid();
1993 if (proxyUid != -1) {
1994 out.attribute(null, "pu", Integer.toString(proxyUid));
1995 }
1996 String proxyPackageName = op.getProxyPackageName();
1997 if (proxyPackageName != null) {
1998 out.attribute(null, "pp", proxyPackageName);
1999 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002000 out.endTag(null, "op");
2001 }
2002 out.endTag(null, "uid");
2003 }
2004 if (lastPkg != null) {
2005 out.endTag(null, "pkg");
2006 }
2007 }
2008
2009 out.endTag(null, "app-ops");
2010 out.endDocument();
2011 mFile.finishWrite(stream);
2012 } catch (IOException e) {
2013 Slog.w(TAG, "Failed to write state, restoring backup.", e);
2014 mFile.failWrite(stream);
2015 }
2016 }
2017 }
2018
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002019 static class Shell extends ShellCommand {
2020 final IAppOpsService mInterface;
2021 final AppOpsService mInternal;
2022
2023 int userId = UserHandle.USER_SYSTEM;
2024 String packageName;
2025 String opStr;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002026 String modeStr;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002027 int op;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002028 int mode;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002029 int packageUid;
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002030 int nonpackageUid;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05002031 final static Binder sBinder = new Binder();
2032 IBinder mToken;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002033
2034 Shell(IAppOpsService iface, AppOpsService internal) {
2035 mInterface = iface;
2036 mInternal = internal;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05002037 try {
2038 mToken = mInterface.getToken(sBinder);
2039 } catch (RemoteException e) {
2040 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002041 }
2042
2043 @Override
2044 public int onCommand(String cmd) {
2045 return onShellCommand(this, cmd);
2046 }
2047
2048 @Override
2049 public void onHelp() {
2050 PrintWriter pw = getOutPrintWriter();
2051 dumpCommandHelp(pw);
2052 }
2053
2054 private int strOpToOp(String op, PrintWriter err) {
2055 try {
2056 return AppOpsManager.strOpToOp(op);
2057 } catch (IllegalArgumentException e) {
2058 }
2059 try {
2060 return Integer.parseInt(op);
2061 } catch (NumberFormatException e) {
2062 }
2063 try {
2064 return AppOpsManager.strDebugOpToOp(op);
2065 } catch (IllegalArgumentException e) {
2066 err.println("Error: " + e.getMessage());
2067 return -1;
2068 }
2069 }
2070
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002071 int strModeToMode(String modeStr, PrintWriter err) {
2072 switch (modeStr) {
2073 case "allow":
2074 return AppOpsManager.MODE_ALLOWED;
2075 case "deny":
2076 return AppOpsManager.MODE_ERRORED;
2077 case "ignore":
2078 return AppOpsManager.MODE_IGNORED;
2079 case "default":
2080 return AppOpsManager.MODE_DEFAULT;
2081 }
2082 try {
2083 return Integer.parseInt(modeStr);
2084 } catch (NumberFormatException e) {
2085 }
2086 err.println("Error: Mode " + modeStr + " is not valid");
2087 return -1;
2088 }
2089
2090 int parseUserOpMode(int defMode, PrintWriter err) throws RemoteException {
2091 userId = UserHandle.USER_CURRENT;
2092 opStr = null;
2093 modeStr = null;
2094 for (String argument; (argument = getNextArg()) != null;) {
2095 if ("--user".equals(argument)) {
2096 userId = UserHandle.parseUserArg(getNextArgRequired());
2097 } else {
2098 if (opStr == null) {
2099 opStr = argument;
2100 } else if (modeStr == null) {
2101 modeStr = argument;
2102 break;
2103 }
2104 }
2105 }
2106 if (opStr == null) {
2107 err.println("Error: Operation not specified.");
2108 return -1;
2109 }
2110 op = strOpToOp(opStr, err);
2111 if (op < 0) {
2112 return -1;
2113 }
2114 if (modeStr != null) {
2115 if ((mode=strModeToMode(modeStr, err)) < 0) {
2116 return -1;
2117 }
2118 } else {
2119 mode = defMode;
2120 }
2121 return 0;
2122 }
2123
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002124 int parseUserPackageOp(boolean reqOp, PrintWriter err) throws RemoteException {
2125 userId = UserHandle.USER_CURRENT;
2126 packageName = null;
2127 opStr = null;
2128 for (String argument; (argument = getNextArg()) != null;) {
2129 if ("--user".equals(argument)) {
2130 userId = UserHandle.parseUserArg(getNextArgRequired());
2131 } else {
2132 if (packageName == null) {
2133 packageName = argument;
2134 } else if (opStr == null) {
2135 opStr = argument;
2136 break;
2137 }
2138 }
2139 }
2140 if (packageName == null) {
2141 err.println("Error: Package name not specified.");
2142 return -1;
2143 } else if (opStr == null && reqOp) {
2144 err.println("Error: Operation not specified.");
2145 return -1;
2146 }
2147 if (opStr != null) {
2148 op = strOpToOp(opStr, err);
2149 if (op < 0) {
2150 return -1;
2151 }
2152 } else {
2153 op = AppOpsManager.OP_NONE;
2154 }
2155 if (userId == UserHandle.USER_CURRENT) {
2156 userId = ActivityManager.getCurrentUser();
2157 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002158 nonpackageUid = -1;
2159 try {
2160 nonpackageUid = Integer.parseInt(packageName);
2161 } catch (NumberFormatException e) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002162 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002163 if (nonpackageUid == -1 && packageName.length() > 1 && packageName.charAt(0) == 'u'
2164 && packageName.indexOf('.') < 0) {
2165 int i = 1;
2166 while (i < packageName.length() && packageName.charAt(i) >= '0'
2167 && packageName.charAt(i) <= '9') {
2168 i++;
2169 }
2170 if (i > 1 && i < packageName.length()) {
2171 String userStr = packageName.substring(1, i);
2172 try {
2173 int user = Integer.parseInt(userStr);
2174 char type = packageName.charAt(i);
2175 i++;
2176 int startTypeVal = i;
2177 while (i < packageName.length() && packageName.charAt(i) >= '0'
2178 && packageName.charAt(i) <= '9') {
2179 i++;
2180 }
2181 if (i > startTypeVal) {
2182 String typeValStr = packageName.substring(startTypeVal, i);
2183 try {
2184 int typeVal = Integer.parseInt(typeValStr);
2185 if (type == 'a') {
2186 nonpackageUid = UserHandle.getUid(user,
2187 typeVal + Process.FIRST_APPLICATION_UID);
2188 } else if (type == 's') {
2189 nonpackageUid = UserHandle.getUid(user, typeVal);
2190 }
2191 } catch (NumberFormatException e) {
2192 }
2193 }
2194 } catch (NumberFormatException e) {
2195 }
2196 }
2197 }
2198 if (nonpackageUid != -1) {
2199 packageName = null;
2200 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08002201 packageUid = resolveUid(packageName);
2202 if (packageUid < 0) {
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002203 packageUid = AppGlobals.getPackageManager().getPackageUid(packageName,
2204 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
2205 }
2206 if (packageUid < 0) {
2207 err.println("Error: No UID for " + packageName + " in user " + userId);
2208 return -1;
2209 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002210 }
2211 return 0;
2212 }
2213 }
2214
2215 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002216 FileDescriptor err, String[] args, ShellCallback callback,
2217 ResultReceiver resultReceiver) {
2218 (new Shell(this, this)).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002219 }
2220
2221 static void dumpCommandHelp(PrintWriter pw) {
2222 pw.println("AppOps service (appops) commands:");
2223 pw.println(" help");
2224 pw.println(" Print this help text.");
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05002225 pw.println(" start [--user <USER_ID>] <PACKAGE | UID> <OP> ");
2226 pw.println(" Starts a given operation for a particular application.");
2227 pw.println(" stop [--user <USER_ID>] <PACKAGE | UID> <OP> ");
2228 pw.println(" Stops a given operation for a particular application.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002229 pw.println(" set [--user <USER_ID>] <PACKAGE | UID> <OP> <MODE>");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002230 pw.println(" Set the mode for a particular application and operation.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002231 pw.println(" get [--user <USER_ID>] <PACKAGE | UID> [<OP>]");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002232 pw.println(" Return the mode for a particular application and optional operation.");
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002233 pw.println(" query-op [--user <USER_ID>] <OP> [<MODE>]");
2234 pw.println(" Print all packages that currently have the given op in the given mode.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002235 pw.println(" reset [--user <USER_ID>] [<PACKAGE>]");
2236 pw.println(" Reset the given application or all applications to default modes.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002237 pw.println(" write-settings");
2238 pw.println(" Immediately write pending changes to storage.");
2239 pw.println(" read-settings");
2240 pw.println(" Read the last written settings, replacing current state in RAM.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002241 pw.println(" options:");
2242 pw.println(" <PACKAGE> an Android package name.");
2243 pw.println(" <OP> an AppOps operation.");
2244 pw.println(" <MODE> one of allow, ignore, deny, or default");
2245 pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
2246 pw.println(" specified, the current user is assumed.");
2247 }
2248
2249 static int onShellCommand(Shell shell, String cmd) {
2250 if (cmd == null) {
2251 return shell.handleDefaultCommands(cmd);
2252 }
2253 PrintWriter pw = shell.getOutPrintWriter();
2254 PrintWriter err = shell.getErrPrintWriter();
2255 try {
2256 switch (cmd) {
2257 case "set": {
2258 int res = shell.parseUserPackageOp(true, err);
2259 if (res < 0) {
2260 return res;
2261 }
2262 String modeStr = shell.getNextArg();
2263 if (modeStr == null) {
2264 err.println("Error: Mode not specified.");
2265 return -1;
2266 }
2267
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002268 final int mode = shell.strModeToMode(modeStr, err);
2269 if (mode < 0) {
2270 return -1;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002271 }
2272
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002273 if (shell.packageName != null) {
2274 shell.mInterface.setMode(shell.op, shell.packageUid, shell.packageName,
2275 mode);
2276 } else {
2277 shell.mInterface.setUidMode(shell.op, shell.nonpackageUid, mode);
2278 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002279 return 0;
2280 }
2281 case "get": {
2282 int res = shell.parseUserPackageOp(false, err);
2283 if (res < 0) {
2284 return res;
2285 }
2286
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002287 List<AppOpsManager.PackageOps> ops;
2288 if (shell.packageName != null) {
2289 ops = shell.mInterface.getOpsForPackage(
2290 shell.packageUid, shell.packageName,
2291 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
2292 } else {
2293 ops = shell.mInterface.getUidOps(
2294 shell.nonpackageUid,
2295 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
2296 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002297 if (ops == null || ops.size() <= 0) {
2298 pw.println("No operations.");
Svet Ganov82f09bc2018-01-12 22:08:40 -08002299 if (shell.op > AppOpsManager.OP_NONE && shell.op < AppOpsManager._NUM_OP) {
2300 pw.println("Default mode: " + AppOpsManager.modeToString(
2301 AppOpsManager.opToDefaultMode(shell.op)));
2302 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002303 return 0;
2304 }
2305 final long now = System.currentTimeMillis();
2306 for (int i=0; i<ops.size(); i++) {
2307 List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
2308 for (int j=0; j<entries.size(); j++) {
2309 AppOpsManager.OpEntry ent = entries.get(j);
2310 pw.print(AppOpsManager.opToName(ent.getOp()));
2311 pw.print(": ");
Svet Ganov82f09bc2018-01-12 22:08:40 -08002312 pw.print(AppOpsManager.modeToString(ent.getMode()));
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002313 if (ent.getTime() != 0) {
2314 pw.print("; time=");
2315 TimeUtils.formatDuration(now - ent.getTime(), pw);
2316 pw.print(" ago");
2317 }
2318 if (ent.getRejectTime() != 0) {
2319 pw.print("; rejectTime=");
2320 TimeUtils.formatDuration(now - ent.getRejectTime(), pw);
2321 pw.print(" ago");
2322 }
2323 if (ent.getDuration() == -1) {
2324 pw.print(" (running)");
2325 } else if (ent.getDuration() != 0) {
2326 pw.print("; duration=");
2327 TimeUtils.formatDuration(ent.getDuration(), pw);
2328 }
2329 pw.println();
2330 }
2331 }
2332 return 0;
2333 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002334 case "query-op": {
2335 int res = shell.parseUserOpMode(AppOpsManager.MODE_IGNORED, err);
2336 if (res < 0) {
2337 return res;
2338 }
2339 List<AppOpsManager.PackageOps> ops = shell.mInterface.getPackagesForOps(
2340 new int[] {shell.op});
2341 if (ops == null || ops.size() <= 0) {
2342 pw.println("No operations.");
2343 return 0;
2344 }
2345 for (int i=0; i<ops.size(); i++) {
2346 final AppOpsManager.PackageOps pkg = ops.get(i);
2347 boolean hasMatch = false;
2348 final List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
2349 for (int j=0; j<entries.size(); j++) {
2350 AppOpsManager.OpEntry ent = entries.get(j);
2351 if (ent.getOp() == shell.op && ent.getMode() == shell.mode) {
2352 hasMatch = true;
2353 break;
2354 }
2355 }
2356 if (hasMatch) {
2357 pw.println(pkg.getPackageName());
2358 }
2359 }
2360 return 0;
2361 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002362 case "reset": {
2363 String packageName = null;
2364 int userId = UserHandle.USER_CURRENT;
2365 for (String argument; (argument = shell.getNextArg()) != null;) {
2366 if ("--user".equals(argument)) {
2367 String userStr = shell.getNextArgRequired();
2368 userId = UserHandle.parseUserArg(userStr);
2369 } else {
2370 if (packageName == null) {
2371 packageName = argument;
2372 } else {
2373 err.println("Error: Unsupported argument: " + argument);
2374 return -1;
2375 }
2376 }
2377 }
2378
2379 if (userId == UserHandle.USER_CURRENT) {
2380 userId = ActivityManager.getCurrentUser();
2381 }
2382
2383 shell.mInterface.resetAllModes(userId, packageName);
2384 pw.print("Reset all modes for: ");
2385 if (userId == UserHandle.USER_ALL) {
2386 pw.print("all users");
2387 } else {
2388 pw.print("user "); pw.print(userId);
2389 }
2390 pw.print(", ");
2391 if (packageName == null) {
2392 pw.println("all packages");
2393 } else {
2394 pw.print("package "); pw.println(packageName);
2395 }
2396 return 0;
2397 }
2398 case "write-settings": {
2399 shell.mInternal.mContext.enforcePermission(
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -08002400 android.Manifest.permission.MANAGE_APP_OPS_MODES,
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002401 Binder.getCallingPid(), Binder.getCallingUid(), null);
2402 long token = Binder.clearCallingIdentity();
2403 try {
2404 synchronized (shell.mInternal) {
2405 shell.mInternal.mHandler.removeCallbacks(shell.mInternal.mWriteRunner);
2406 }
2407 shell.mInternal.writeState();
2408 pw.println("Current settings written.");
2409 } finally {
2410 Binder.restoreCallingIdentity(token);
2411 }
2412 return 0;
2413 }
2414 case "read-settings": {
2415 shell.mInternal.mContext.enforcePermission(
Dianne Hackbornbf1b57d2018-03-07 12:42:47 -08002416 android.Manifest.permission.MANAGE_APP_OPS_MODES,
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002417 Binder.getCallingPid(), Binder.getCallingUid(), null);
2418 long token = Binder.clearCallingIdentity();
2419 try {
2420 shell.mInternal.readState();
2421 pw.println("Last settings read.");
2422 } finally {
2423 Binder.restoreCallingIdentity(token);
2424 }
2425 return 0;
2426 }
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05002427 case "start": {
2428 int res = shell.parseUserPackageOp(true, err);
2429 if (res < 0) {
2430 return res;
2431 }
2432
2433 if (shell.packageName != null) {
2434 shell.mInterface.startOperation(shell.mToken,
2435 shell.op, shell.packageUid, shell.packageName, true);
2436 } else {
2437 return -1;
2438 }
2439 return 0;
2440 }
2441 case "stop": {
2442 int res = shell.parseUserPackageOp(true, err);
2443 if (res < 0) {
2444 return res;
2445 }
2446
2447 if (shell.packageName != null) {
2448 shell.mInterface.finishOperation(shell.mToken,
2449 shell.op, shell.packageUid, shell.packageName);
2450 } else {
2451 return -1;
2452 }
2453 return 0;
2454 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002455 default:
2456 return shell.handleDefaultCommands(cmd);
2457 }
2458 } catch (RemoteException e) {
2459 pw.println("Remote exception: " + e);
2460 }
2461 return -1;
2462 }
2463
2464 private void dumpHelp(PrintWriter pw) {
2465 pw.println("AppOps service (appops) dump options:");
2466 pw.println(" none");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002467 }
2468
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002469 @Override
2470 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002471 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002472
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002473 if (args != null) {
2474 for (int i=0; i<args.length; i++) {
2475 String arg = args[i];
2476 if ("-h".equals(arg)) {
2477 dumpHelp(pw);
2478 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07002479 } else if ("-a".equals(arg)) {
2480 // dump all data
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002481 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
2482 pw.println("Unknown option: " + arg);
2483 return;
2484 } else {
2485 pw.println("Unknown command: " + arg);
2486 return;
2487 }
2488 }
2489 }
2490
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002491 synchronized (this) {
2492 pw.println("Current AppOps Service state:");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002493 final long now = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002494 boolean needSep = false;
2495 if (mOpModeWatchers.size() > 0) {
2496 needSep = true;
2497 pw.println(" Op mode watchers:");
2498 for (int i=0; i<mOpModeWatchers.size(); i++) {
2499 pw.print(" Op "); pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
2500 pw.println(":");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002501 ArraySet<ModeCallback> callbacks = mOpModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002502 for (int j=0; j<callbacks.size(); j++) {
2503 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08002504 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002505 }
2506 }
2507 }
2508 if (mPackageModeWatchers.size() > 0) {
2509 needSep = true;
2510 pw.println(" Package mode watchers:");
2511 for (int i=0; i<mPackageModeWatchers.size(); i++) {
2512 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
2513 pw.println(":");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002514 ArraySet<ModeCallback> callbacks = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002515 for (int j=0; j<callbacks.size(); j++) {
2516 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08002517 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002518 }
2519 }
2520 }
2521 if (mModeWatchers.size() > 0) {
2522 needSep = true;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002523 pw.println(" All op mode watchers:");
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002524 for (int i=0; i<mModeWatchers.size(); i++) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002525 pw.print(" ");
2526 pw.print(Integer.toHexString(System.identityHashCode(mModeWatchers.keyAt(i))));
2527 pw.print(": "); pw.println(mModeWatchers.valueAt(i));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002528 }
2529 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002530 if (mActiveWatchers.size() > 0) {
2531 needSep = true;
2532 pw.println(" All op active watchers:");
2533 for (int i = 0; i < mActiveWatchers.size(); i++) {
2534 final SparseArray<ActiveCallback> activeWatchers = mActiveWatchers.valueAt(i);
2535 if (activeWatchers.size() <= 0) {
2536 continue;
2537 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002538 pw.print(" ");
2539 pw.print(Integer.toHexString(System.identityHashCode(
2540 mActiveWatchers.keyAt(i))));
2541 pw.println(" ->");
2542 pw.print(" [");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002543 final int opCount = activeWatchers.size();
2544 for (i = 0; i < opCount; i++) {
2545 pw.print(AppOpsManager.opToName(activeWatchers.keyAt(i)));
2546 if (i < opCount - 1) {
2547 pw.print(',');
2548 }
2549 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002550 pw.println("]");
2551 pw.print(" ");
2552 pw.println(activeWatchers.valueAt(0));
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002553 }
2554 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002555 if (mClients.size() > 0) {
2556 needSep = true;
2557 pw.println(" Clients:");
2558 for (int i=0; i<mClients.size(); i++) {
2559 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
2560 ClientState cs = mClients.valueAt(i);
2561 pw.print(" "); pw.println(cs);
Svet Ganovf7b47252018-02-26 11:11:27 -08002562 if (cs.mStartedOps.size() > 0) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002563 pw.println(" Started ops:");
2564 for (int j=0; j<cs.mStartedOps.size(); j++) {
2565 Op op = cs.mStartedOps.get(j);
2566 pw.print(" "); pw.print("uid="); pw.print(op.uid);
2567 pw.print(" pkg="); pw.print(op.packageName);
2568 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
2569 }
2570 }
2571 }
2572 }
John Spurlock1af30c72014-03-10 08:33:35 -04002573 if (mAudioRestrictions.size() > 0) {
2574 boolean printedHeader = false;
2575 for (int o=0; o<mAudioRestrictions.size(); o++) {
2576 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
2577 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
2578 for (int i=0; i<restrictions.size(); i++) {
2579 if (!printedHeader){
2580 pw.println(" Audio Restrictions:");
2581 printedHeader = true;
2582 needSep = true;
2583 }
John Spurlock7b414672014-07-18 13:02:39 -04002584 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04002585 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04002586 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04002587 Restriction r = restrictions.valueAt(i);
2588 pw.print(": mode="); pw.println(r.mode);
2589 if (!r.exceptionPackages.isEmpty()) {
2590 pw.println(" Exceptions:");
2591 for (int j=0; j<r.exceptionPackages.size(); j++) {
2592 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
2593 }
2594 }
2595 }
2596 }
2597 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002598 if (needSep) {
2599 pw.println();
2600 }
Svet Ganov2af57082015-07-30 08:44:20 -07002601 for (int i=0; i<mUidStates.size(); i++) {
2602 UidState uidState = mUidStates.valueAt(i);
2603
2604 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
Svet Ganovee438d42017-01-19 18:04:38 -08002605 needSep = true;
Svet Ganov2af57082015-07-30 08:44:20 -07002606
2607 SparseIntArray opModes = uidState.opModes;
2608 if (opModes != null) {
2609 final int opModeCount = opModes.size();
2610 for (int j = 0; j < opModeCount; j++) {
2611 final int code = opModes.keyAt(j);
2612 final int mode = opModes.valueAt(j);
2613 pw.print(" "); pw.print(AppOpsManager.opToName(code));
2614 pw.print(": mode="); pw.println(mode);
2615 }
2616 }
2617
2618 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
2619 if (pkgOps == null) {
2620 continue;
2621 }
2622
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002623 for (Ops ops : pkgOps.values()) {
2624 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
2625 for (int j=0; j<ops.size(); j++) {
2626 Op op = ops.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002627 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
2628 pw.print(": mode="); pw.print(op.mode);
2629 if (op.time != 0) {
2630 pw.print("; time="); TimeUtils.formatDuration(now-op.time, pw);
2631 pw.print(" ago");
2632 }
2633 if (op.rejectTime != 0) {
2634 pw.print("; rejectTime="); TimeUtils.formatDuration(now-op.rejectTime, pw);
2635 pw.print(" ago");
2636 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002637 if (op.duration == -1) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002638 pw.print(" (running)");
2639 } else if (op.duration != 0) {
2640 pw.print("; duration="); TimeUtils.formatDuration(op.duration, pw);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002641 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002642 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002643 }
2644 }
2645 }
Svet Ganovee438d42017-01-19 18:04:38 -08002646 if (needSep) {
2647 pw.println();
2648 }
2649
2650 final int userRestrictionCount = mOpUserRestrictions.size();
2651 for (int i = 0; i < userRestrictionCount; i++) {
2652 IBinder token = mOpUserRestrictions.keyAt(i);
2653 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
2654 pw.println(" User restrictions for token " + token + ":");
2655
2656 final int restrictionCount = restrictionState.perUserRestrictions != null
2657 ? restrictionState.perUserRestrictions.size() : 0;
2658 if (restrictionCount > 0) {
2659 pw.println(" Restricted ops:");
2660 for (int j = 0; j < restrictionCount; j++) {
2661 int userId = restrictionState.perUserRestrictions.keyAt(j);
2662 boolean[] restrictedOps = restrictionState.perUserRestrictions.valueAt(j);
2663 if (restrictedOps == null) {
2664 continue;
2665 }
2666 StringBuilder restrictedOpsValue = new StringBuilder();
2667 restrictedOpsValue.append("[");
2668 final int restrictedOpCount = restrictedOps.length;
2669 for (int k = 0; k < restrictedOpCount; k++) {
2670 if (restrictedOps[k]) {
2671 if (restrictedOpsValue.length() > 1) {
2672 restrictedOpsValue.append(", ");
2673 }
2674 restrictedOpsValue.append(AppOpsManager.opToName(k));
2675 }
2676 }
2677 restrictedOpsValue.append("]");
2678 pw.print(" "); pw.print("user: "); pw.print(userId);
2679 pw.print(" restricted ops: "); pw.println(restrictedOpsValue);
2680 }
2681 }
2682
2683 final int excludedPackageCount = restrictionState.perUserExcludedPackages != null
2684 ? restrictionState.perUserExcludedPackages.size() : 0;
2685 if (excludedPackageCount > 0) {
2686 pw.println(" Excluded packages:");
2687 for (int j = 0; j < excludedPackageCount; j++) {
2688 int userId = restrictionState.perUserExcludedPackages.keyAt(j);
2689 String[] packageNames = restrictionState.perUserExcludedPackages.valueAt(j);
2690 pw.print(" "); pw.print("user: "); pw.print(userId);
2691 pw.print(" packages: "); pw.println(Arrays.toString(packageNames));
2692 }
2693 }
2694 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002695 }
2696 }
John Spurlock1af30c72014-03-10 08:33:35 -04002697
2698 private static final class Restriction {
2699 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
2700 int mode;
2701 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
2702 }
Jason Monk62062992014-05-06 09:55:28 -04002703
2704 @Override
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002705 public void setUserRestrictions(Bundle restrictions, IBinder token, int userHandle) {
Jason Monk62062992014-05-06 09:55:28 -04002706 checkSystemUid("setUserRestrictions");
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002707 Preconditions.checkNotNull(restrictions);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002708 Preconditions.checkNotNull(token);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002709 for (int i = 0; i < AppOpsManager._NUM_OP; i++) {
Jason Monk62062992014-05-06 09:55:28 -04002710 String restriction = AppOpsManager.opToRestriction(i);
Suprabh Shukla64e0dcb2016-05-24 16:23:11 -07002711 if (restriction != null) {
2712 setUserRestrictionNoCheck(i, restrictions.getBoolean(restriction, false), token,
2713 userHandle, null);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002714 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002715 }
2716 }
2717
2718 @Override
Ruben Brunk29931bc2016-03-11 00:24:26 -08002719 public void setUserRestriction(int code, boolean restricted, IBinder token, int userHandle,
2720 String[] exceptionPackages) {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002721 if (Binder.getCallingPid() != Process.myPid()) {
2722 mContext.enforcePermission(Manifest.permission.MANAGE_APP_OPS_RESTRICTIONS,
2723 Binder.getCallingPid(), Binder.getCallingUid(), null);
2724 }
2725 if (userHandle != UserHandle.getCallingUserId()) {
2726 if (mContext.checkCallingOrSelfPermission(Manifest.permission
2727 .INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
2728 && mContext.checkCallingOrSelfPermission(Manifest.permission
2729 .INTERACT_ACROSS_USERS) != PackageManager.PERMISSION_GRANTED) {
2730 throw new SecurityException("Need INTERACT_ACROSS_USERS_FULL or"
2731 + " INTERACT_ACROSS_USERS to interact cross user ");
Jason Monk62062992014-05-06 09:55:28 -04002732 }
2733 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002734 verifyIncomingOp(code);
2735 Preconditions.checkNotNull(token);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002736 setUserRestrictionNoCheck(code, restricted, token, userHandle, exceptionPackages);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002737 }
2738
2739 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
Ruben Brunk29931bc2016-03-11 00:24:26 -08002740 int userHandle, String[] exceptionPackages) {
Svet Ganov442ed572016-08-17 17:29:43 -07002741 synchronized (AppOpsService.this) {
2742 ClientRestrictionState restrictionState = mOpUserRestrictions.get(token);
2743
2744 if (restrictionState == null) {
2745 try {
2746 restrictionState = new ClientRestrictionState(token);
2747 } catch (RemoteException e) {
2748 return;
2749 }
2750 mOpUserRestrictions.put(token, restrictionState);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002751 }
Svet Ganov442ed572016-08-17 17:29:43 -07002752
2753 if (restrictionState.setRestriction(code, restricted, exceptionPackages, userHandle)) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002754 mHandler.sendMessage(PooledLambda.obtainMessage(
Svet Ganov3a95f832018-03-23 17:44:30 -07002755 AppOpsService::notifyWatchersOfChange, this, code, UID_ANY));
Svet Ganov442ed572016-08-17 17:29:43 -07002756 }
2757
2758 if (restrictionState.isDefault()) {
2759 mOpUserRestrictions.remove(token);
2760 restrictionState.destroy();
2761 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002762 }
Julia Reynoldsbb21c252016-04-05 16:01:49 -04002763 }
2764
Svet Ganov3a95f832018-03-23 17:44:30 -07002765 private void notifyWatchersOfChange(int code, int uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002766 final ArraySet<ModeCallback> clonedCallbacks;
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002767 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002768 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002769 if (callbacks == null) {
2770 return;
2771 }
Dianne Hackborn68d76552017-02-27 15:32:03 -08002772 clonedCallbacks = new ArraySet<>(callbacks);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002773 }
2774
Svet Ganov3a95f832018-03-23 17:44:30 -07002775 notifyOpChanged(clonedCallbacks, code, uid, null);
Jason Monk62062992014-05-06 09:55:28 -04002776 }
2777
2778 @Override
2779 public void removeUser(int userHandle) throws RemoteException {
2780 checkSystemUid("removeUser");
Svet Ganov442ed572016-08-17 17:29:43 -07002781 synchronized (AppOpsService.this) {
2782 final int tokenCount = mOpUserRestrictions.size();
2783 for (int i = tokenCount - 1; i >= 0; i--) {
2784 ClientRestrictionState opRestrictions = mOpUserRestrictions.valueAt(i);
2785 opRestrictions.removeUser(userHandle);
2786 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002787 removeUidsForUserLocked(userHandle);
2788 }
2789 }
2790
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002791 @Override
2792 public boolean isOperationActive(int code, int uid, String packageName) {
Svet Ganovf7b47252018-02-26 11:11:27 -08002793 if (Binder.getCallingUid() != uid) {
2794 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
2795 != PackageManager.PERMISSION_GRANTED) {
2796 return false;
2797 }
2798 }
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002799 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002800 final String resolvedPackageName = resolvePackageName(uid, packageName);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002801 if (resolvedPackageName == null) {
2802 return false;
2803 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002804 synchronized (AppOpsService.this) {
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002805 for (int i = mClients.size() - 1; i >= 0; i--) {
2806 final ClientState client = mClients.valueAt(i);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002807 for (int j = client.mStartedOps.size() - 1; j >= 0; j--) {
2808 final Op op = client.mStartedOps.get(j);
2809 if (op.op == code && op.uid == uid) return true;
2810 }
2811 }
2812 }
2813 return false;
2814 }
2815
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002816 private void removeUidsForUserLocked(int userHandle) {
2817 for (int i = mUidStates.size() - 1; i >= 0; --i) {
2818 final int uid = mUidStates.keyAt(i);
2819 if (UserHandle.getUserId(uid) == userHandle) {
2820 mUidStates.removeAt(i);
2821 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002822 }
2823 }
2824
Jason Monk62062992014-05-06 09:55:28 -04002825 private void checkSystemUid(String function) {
2826 int uid = Binder.getCallingUid();
2827 if (uid != Process.SYSTEM_UID) {
2828 throw new SecurityException(function + " must by called by the system");
2829 }
2830 }
2831
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002832 private static String resolvePackageName(int uid, String packageName) {
Svet Ganov82f09bc2018-01-12 22:08:40 -08002833 if (uid == Process.ROOT_UID) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002834 return "root";
2835 } else if (uid == Process.SHELL_UID) {
2836 return "com.android.shell";
Svet Ganov82f09bc2018-01-12 22:08:40 -08002837 } else if (uid == Process.MEDIA_UID) {
2838 return "media";
2839 } else if (uid == Process.AUDIOSERVER_UID) {
2840 return "audioserver";
2841 } else if (uid == Process.CAMERASERVER_UID) {
2842 return "cameraserver";
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002843 } else if (uid == Process.SYSTEM_UID && packageName == null) {
2844 return "android";
2845 }
2846 return packageName;
2847 }
2848
Svet Ganov82f09bc2018-01-12 22:08:40 -08002849 private static int resolveUid(String packageName) {
2850 if (packageName == null) {
2851 return -1;
2852 }
2853 switch (packageName) {
2854 case "root":
2855 return Process.ROOT_UID;
2856 case "shell":
2857 return Process.SHELL_UID;
2858 case "media":
2859 return Process.MEDIA_UID;
2860 case "audioserver":
2861 return Process.AUDIOSERVER_UID;
2862 case "cameraserver":
2863 return Process.CAMERASERVER_UID;
2864 }
2865 return -1;
2866 }
2867
Svet Ganov2af57082015-07-30 08:44:20 -07002868 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07002869 String[] packageNames = null;
Svet Ganov2af57082015-07-30 08:44:20 -07002870 try {
riddle_hsu40b300f2015-11-23 13:22:03 +08002871 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -07002872 } catch (RemoteException e) {
2873 /* ignore - local call */
2874 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07002875 if (packageNames == null) {
2876 return EmptyArray.STRING;
2877 }
2878 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07002879 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002880
2881 private final class ClientRestrictionState implements DeathRecipient {
2882 private final IBinder token;
2883 SparseArray<boolean[]> perUserRestrictions;
2884 SparseArray<String[]> perUserExcludedPackages;
2885
2886 public ClientRestrictionState(IBinder token)
2887 throws RemoteException {
2888 token.linkToDeath(this, 0);
2889 this.token = token;
2890 }
2891
2892 public boolean setRestriction(int code, boolean restricted,
2893 String[] excludedPackages, int userId) {
2894 boolean changed = false;
2895
2896 if (perUserRestrictions == null && restricted) {
2897 perUserRestrictions = new SparseArray<>();
2898 }
2899
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002900 int[] users;
2901 if (userId == UserHandle.USER_ALL) {
2902 List<UserInfo> liveUsers = UserManager.get(mContext).getUsers(false);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002903
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002904 users = new int[liveUsers.size()];
2905 for (int i = 0; i < liveUsers.size(); i++) {
2906 users[i] = liveUsers.get(i).id;
2907 }
2908 } else {
2909 users = new int[]{userId};
2910 }
2911
2912 if (perUserRestrictions != null) {
2913 int numUsers = users.length;
2914
2915 for (int i = 0; i < numUsers; i++) {
2916 int thisUserId = users[i];
2917
2918 boolean[] userRestrictions = perUserRestrictions.get(thisUserId);
2919 if (userRestrictions == null && restricted) {
2920 userRestrictions = new boolean[AppOpsManager._NUM_OP];
2921 perUserRestrictions.put(thisUserId, userRestrictions);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002922 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002923 if (userRestrictions != null && userRestrictions[code] != restricted) {
2924 userRestrictions[code] = restricted;
2925 if (!restricted && isDefault(userRestrictions)) {
2926 perUserRestrictions.remove(thisUserId);
2927 userRestrictions = null;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002928 }
2929 changed = true;
2930 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002931
2932 if (userRestrictions != null) {
2933 final boolean noExcludedPackages = ArrayUtils.isEmpty(excludedPackages);
2934 if (perUserExcludedPackages == null && !noExcludedPackages) {
2935 perUserExcludedPackages = new SparseArray<>();
2936 }
2937 if (perUserExcludedPackages != null && !Arrays.equals(excludedPackages,
2938 perUserExcludedPackages.get(thisUserId))) {
2939 if (noExcludedPackages) {
2940 perUserExcludedPackages.remove(thisUserId);
2941 if (perUserExcludedPackages.size() <= 0) {
2942 perUserExcludedPackages = null;
2943 }
2944 } else {
2945 perUserExcludedPackages.put(thisUserId, excludedPackages);
2946 }
2947 changed = true;
2948 }
2949 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002950 }
2951 }
2952
2953 return changed;
2954 }
2955
2956 public boolean hasRestriction(int restriction, String packageName, int userId) {
2957 if (perUserRestrictions == null) {
2958 return false;
2959 }
2960 boolean[] restrictions = perUserRestrictions.get(userId);
2961 if (restrictions == null) {
2962 return false;
2963 }
2964 if (!restrictions[restriction]) {
2965 return false;
2966 }
2967 if (perUserExcludedPackages == null) {
2968 return true;
2969 }
2970 String[] perUserExclusions = perUserExcludedPackages.get(userId);
2971 if (perUserExclusions == null) {
2972 return true;
2973 }
2974 return !ArrayUtils.contains(perUserExclusions, packageName);
2975 }
2976
2977 public void removeUser(int userId) {
2978 if (perUserExcludedPackages != null) {
2979 perUserExcludedPackages.remove(userId);
2980 if (perUserExcludedPackages.size() <= 0) {
2981 perUserExcludedPackages = null;
2982 }
2983 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002984 if (perUserRestrictions != null) {
2985 perUserRestrictions.remove(userId);
2986 if (perUserRestrictions.size() <= 0) {
2987 perUserRestrictions = null;
2988 }
2989 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002990 }
2991
2992 public boolean isDefault() {
2993 return perUserRestrictions == null || perUserRestrictions.size() <= 0;
2994 }
2995
2996 @Override
2997 public void binderDied() {
2998 synchronized (AppOpsService.this) {
2999 mOpUserRestrictions.remove(token);
3000 if (perUserRestrictions == null) {
3001 return;
3002 }
3003 final int userCount = perUserRestrictions.size();
3004 for (int i = 0; i < userCount; i++) {
3005 final boolean[] restrictions = perUserRestrictions.valueAt(i);
3006 final int restrictionCount = restrictions.length;
3007 for (int j = 0; j < restrictionCount; j++) {
3008 if (restrictions[j]) {
3009 final int changedCode = j;
Svet Ganov3a95f832018-03-23 17:44:30 -07003010 mHandler.post(() -> notifyWatchersOfChange(changedCode, UID_ANY));
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07003011 }
3012 }
3013 }
3014 destroy();
3015 }
3016 }
3017
3018 public void destroy() {
3019 token.unlinkToDeath(this, 0);
3020 }
3021
3022 private boolean isDefault(boolean[] array) {
3023 if (ArrayUtils.isEmpty(array)) {
3024 return true;
3025 }
3026 for (boolean value : array) {
3027 if (value) {
3028 return false;
3029 }
3030 }
3031 return true;
3032 }
3033 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003034}