blob: 50b8df2ae20b3a0a41fb93fa7ae8bee5d5be8d48 [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;
48import android.util.Log;
49import android.util.Slog;
50import android.util.SparseArray;
51import android.util.SparseIntArray;
52import android.util.TimeUtils;
53import android.util.Xml;
54
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070055import com.android.internal.annotations.VisibleForTesting;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070056import com.android.internal.app.IAppOpsCallback;
57import com.android.internal.app.IAppOpsService;
58import com.android.internal.os.Zygote;
59import com.android.internal.util.ArrayUtils;
60import com.android.internal.util.DumpUtils;
61import com.android.internal.util.FastXmlSerializer;
62import com.android.internal.util.Preconditions;
63import com.android.internal.util.XmlUtils;
64
65import libcore.util.EmptyArray;
66
67import org.xmlpull.v1.XmlPullParser;
68import org.xmlpull.v1.XmlPullParserException;
69import org.xmlpull.v1.XmlSerializer;
70
Dianne Hackborna06de0f2012-12-11 16:34:47 -080071import java.io.File;
72import java.io.FileDescriptor;
Dianne Hackborn35654b62013-01-14 17:38:02 -080073import java.io.FileInputStream;
74import java.io.FileNotFoundException;
75import java.io.FileOutputStream;
76import java.io.IOException;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080077import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010078import java.nio.charset.StandardCharsets;
Dianne Hackborn35654b62013-01-14 17:38:02 -080079import java.util.ArrayList;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -070080import java.util.Arrays;
Svetoslav215b44a2015-08-04 19:03:40 -070081import java.util.Collections;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080082import java.util.HashMap;
Dianne Hackbornc2293022013-02-06 23:14:49 -080083import java.util.Iterator;
Dianne Hackborn35654b62013-01-14 17:38:02 -080084import java.util.List;
Dianne Hackborn607b4142013-08-02 18:10:10 -070085import java.util.Map;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080086
Dianne Hackborna06de0f2012-12-11 16:34:47 -080087public class AppOpsService extends IAppOpsService.Stub {
88 static final String TAG = "AppOps";
Dianne Hackborn35654b62013-01-14 17:38:02 -080089 static final boolean DEBUG = false;
90
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070091 private static final int NO_VERSION = -1;
92 /** Increment by one every time and add the corresponding upgrade logic in
93 * {@link #upgradeLocked(int)} below. The first version was 1 */
94 private static final int CURRENT_VERSION = 1;
95
Dianne Hackborn35654b62013-01-14 17:38:02 -080096 // Write at most every 30 minutes.
97 static final long WRITE_DELAY = DEBUG ? 1000 : 30*60*1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080098
99 Context mContext;
100 final AtomicFile mFile;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800101 final Handler mHandler;
102
103 boolean mWriteScheduled;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800104 boolean mFastWriteScheduled;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800105 final Runnable mWriteRunner = new Runnable() {
106 public void run() {
107 synchronized (AppOpsService.this) {
108 mWriteScheduled = false;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800109 mFastWriteScheduled = false;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800110 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
111 @Override protected Void doInBackground(Void... params) {
112 writeState();
113 return null;
114 }
115 };
116 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
117 }
118 }
119 };
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800120
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700121 @VisibleForTesting
122 final SparseArray<UidState> mUidStates = new SparseArray<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800123
Ruben Brunk29931bc2016-03-11 00:24:26 -0800124 /*
125 * These are app op restrictions imposed per user from various parties.
Ruben Brunk29931bc2016-03-11 00:24:26 -0800126 */
Svetoslav Ganova8bbd762016-05-13 17:08:16 -0700127 private final ArrayMap<IBinder, ClientRestrictionState> mOpUserRestrictions = new ArrayMap<>();
Jason Monk62062992014-05-06 09:55:28 -0400128
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700129 @VisibleForTesting
130 static final class UidState {
Svet Ganov2af57082015-07-30 08:44:20 -0700131 public final int uid;
132 public ArrayMap<String, Ops> pkgOps;
133 public SparseIntArray opModes;
134
135 public UidState(int uid) {
136 this.uid = uid;
137 }
138
139 public void clear() {
140 pkgOps = null;
141 opModes = null;
142 }
143
144 public boolean isDefault() {
145 return (pkgOps == null || pkgOps.isEmpty())
146 && (opModes == null || opModes.size() <= 0);
147 }
148 }
149
Dianne Hackbornc2293022013-02-06 23:14:49 -0800150 public final static class Ops extends SparseArray<Op> {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800151 public final String packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700152 public final UidState uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400153 public final boolean isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800154
Svet Ganov2af57082015-07-30 08:44:20 -0700155 public Ops(String _packageName, UidState _uidState, boolean _isPrivileged) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800156 packageName = _packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700157 uidState = _uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400158 isPrivileged = _isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800159 }
160 }
161
Dianne Hackbornc2293022013-02-06 23:14:49 -0800162 public final static class Op {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700163 public final int uid;
164 public final String packageName;
Svet Ganov99b60432015-06-27 13:15:22 -0700165 public int proxyUid = -1;
166 public String proxyPackageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800167 public final int op;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800168 public int mode;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800169 public int duration;
170 public long time;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800171 public long rejectTime;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800172 public int nesting;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800173
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700174 public Op(int _uid, String _packageName, int _op) {
175 uid = _uid;
176 packageName = _packageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800177 op = _op;
David Braunf5d83192013-09-16 13:43:51 -0700178 mode = AppOpsManager.opToDefaultMode(op);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800179 }
180 }
181
Dianne Hackborn68d76552017-02-27 15:32:03 -0800182 final SparseArray<ArraySet<Callback>> mOpModeWatchers = new SparseArray<>();
183 final ArrayMap<String, ArraySet<Callback>> mPackageModeWatchers = new ArrayMap<>();
184 final ArrayMap<IBinder, Callback> mModeWatchers = new ArrayMap<>();
185 final SparseArray<SparseArray<Restriction>> mAudioRestrictions = new SparseArray<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800186
187 public final class Callback implements DeathRecipient {
188 final IAppOpsCallback mCallback;
189
190 public Callback(IAppOpsCallback callback) {
191 mCallback = callback;
192 try {
193 mCallback.asBinder().linkToDeath(this, 0);
194 } catch (RemoteException e) {
195 }
196 }
197
198 public void unlinkToDeath() {
199 mCallback.asBinder().unlinkToDeath(this, 0);
200 }
201
202 @Override
203 public void binderDied() {
204 stopWatchingMode(mCallback);
205 }
206 }
207
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700208 final ArrayMap<IBinder, ClientState> mClients = new ArrayMap<IBinder, ClientState>();
209
210 public final class ClientState extends Binder implements DeathRecipient {
211 final IBinder mAppToken;
212 final int mPid;
213 final ArrayList<Op> mStartedOps;
214
215 public ClientState(IBinder appToken) {
216 mAppToken = appToken;
217 mPid = Binder.getCallingPid();
218 if (appToken instanceof Binder) {
219 // For local clients, there is no reason to track them.
220 mStartedOps = null;
221 } else {
222 mStartedOps = new ArrayList<Op>();
223 try {
224 mAppToken.linkToDeath(this, 0);
225 } catch (RemoteException e) {
226 }
227 }
228 }
229
230 @Override
231 public String toString() {
232 return "ClientState{" +
233 "mAppToken=" + mAppToken +
234 ", " + (mStartedOps != null ? ("pid=" + mPid) : "local") +
235 '}';
236 }
237
238 @Override
239 public void binderDied() {
240 synchronized (AppOpsService.this) {
241 for (int i=mStartedOps.size()-1; i>=0; i--) {
242 finishOperationLocked(mStartedOps.get(i));
243 }
244 mClients.remove(mAppToken);
245 }
246 }
247 }
248
Jeff Brown6f357d32014-01-15 20:40:55 -0800249 public AppOpsService(File storagePath, Handler handler) {
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600250 LockGuard.installLock(this, LockGuard.INDEX_APP_OPS);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800251 mFile = new AtomicFile(storagePath);
Jeff Brown6f357d32014-01-15 20:40:55 -0800252 mHandler = handler;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800253 readState();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800254 }
David Braunf5d83192013-09-16 13:43:51 -0700255
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800256 public void publish(Context context) {
257 mContext = context;
258 ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
259 }
260
Dianne Hackborn514074f2013-02-11 10:52:46 -0800261 public void systemReady() {
262 synchronized (this) {
263 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700264 for (int i = mUidStates.size() - 1; i >= 0; i--) {
265 UidState uidState = mUidStates.valueAt(i);
266
267 String[] packageNames = getPackagesForUid(uidState.uid);
268 if (ArrayUtils.isEmpty(packageNames)) {
269 uidState.clear();
270 mUidStates.removeAt(i);
271 changed = true;
272 continue;
273 }
274
275 ArrayMap<String, Ops> pkgs = uidState.pkgOps;
276 if (pkgs == null) {
277 continue;
278 }
279
Dianne Hackborn514074f2013-02-11 10:52:46 -0800280 Iterator<Ops> it = pkgs.values().iterator();
281 while (it.hasNext()) {
282 Ops ops = it.next();
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700283 int curUid = -1;
Dianne Hackborn514074f2013-02-11 10:52:46 -0800284 try {
Jeff Sharkeycd654482016-01-08 17:42:11 -0700285 curUid = AppGlobals.getPackageManager().getPackageUid(ops.packageName,
286 PackageManager.MATCH_UNINSTALLED_PACKAGES,
Svet Ganov2af57082015-07-30 08:44:20 -0700287 UserHandle.getUserId(ops.uidState.uid));
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700288 } catch (RemoteException ignored) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800289 }
Svet Ganov2af57082015-07-30 08:44:20 -0700290 if (curUid != ops.uidState.uid) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800291 Slog.i(TAG, "Pruning old package " + ops.packageName
Svet Ganov2af57082015-07-30 08:44:20 -0700292 + "/" + ops.uidState + ": new uid=" + curUid);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800293 it.remove();
294 changed = true;
295 }
296 }
Svet Ganov2af57082015-07-30 08:44:20 -0700297
298 if (uidState.isDefault()) {
299 mUidStates.removeAt(i);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800300 }
301 }
302 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800303 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800304 }
305 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700306
Suprabh Shuklaaef25132017-01-23 18:09:03 -0800307 PackageManagerInternal packageManagerInternal = LocalServices.getService(
308 PackageManagerInternal.class);
309 packageManagerInternal.setExternalSourcesPolicy(
310 new PackageManagerInternal.ExternalSourcesPolicy() {
311 @Override
312 public int getPackageTrustedToInstallApps(String packageName, int uid) {
313 int appOpMode = checkOperation(AppOpsManager.OP_REQUEST_INSTALL_PACKAGES,
314 uid, packageName);
315 switch (appOpMode) {
316 case AppOpsManager.MODE_ALLOWED:
317 return PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
318 case AppOpsManager.MODE_ERRORED:
319 return PackageManagerInternal.ExternalSourcesPolicy.USER_BLOCKED;
320 default:
321 return PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT;
322 }
323 }
324 });
325
Sudheer Shanka2250d562016-11-07 15:41:02 -0800326 StorageManagerInternal storageManagerInternal = LocalServices.getService(
327 StorageManagerInternal.class);
328 storageManagerInternal.addExternalStoragePolicy(
329 new StorageManagerInternal.ExternalStorageMountPolicy() {
Svet Ganov6ee871e2015-07-10 14:29:33 -0700330 @Override
331 public int getMountMode(int uid, String packageName) {
332 if (Process.isIsolated(uid)) {
333 return Zygote.MOUNT_EXTERNAL_NONE;
334 }
335 if (noteOperation(AppOpsManager.OP_READ_EXTERNAL_STORAGE, uid,
336 packageName) != AppOpsManager.MODE_ALLOWED) {
337 return Zygote.MOUNT_EXTERNAL_NONE;
338 }
339 if (noteOperation(AppOpsManager.OP_WRITE_EXTERNAL_STORAGE, uid,
340 packageName) != AppOpsManager.MODE_ALLOWED) {
341 return Zygote.MOUNT_EXTERNAL_READ;
342 }
343 return Zygote.MOUNT_EXTERNAL_WRITE;
344 }
345
346 @Override
347 public boolean hasExternalStorage(int uid, String packageName) {
348 final int mountMode = getMountMode(uid, packageName);
349 return mountMode == Zygote.MOUNT_EXTERNAL_READ
350 || mountMode == Zygote.MOUNT_EXTERNAL_WRITE;
351 }
352 });
Dianne Hackborn514074f2013-02-11 10:52:46 -0800353 }
354
355 public void packageRemoved(int uid, String packageName) {
356 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700357 UidState uidState = mUidStates.get(uid);
358 if (uidState == null) {
359 return;
360 }
361
362 boolean changed = false;
363
364 // Remove any package state if such.
365 if (uidState.pkgOps != null && uidState.pkgOps.remove(packageName) != null) {
366 changed = true;
367 }
368
369 // If we just nuked the last package state check if the UID is valid.
370 if (changed && uidState.pkgOps.isEmpty()
371 && getPackagesForUid(uid).length <= 0) {
372 mUidStates.remove(uid);
373 }
374
375 if (changed) {
376 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800377 }
378 }
379 }
380
381 public void uidRemoved(int uid) {
382 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700383 if (mUidStates.indexOfKey(uid) >= 0) {
384 mUidStates.remove(uid);
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800385 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800386 }
387 }
388 }
389
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800390 public void shutdown() {
391 Slog.w(TAG, "Writing app ops before shutdown...");
Dianne Hackborn35654b62013-01-14 17:38:02 -0800392 boolean doWrite = false;
393 synchronized (this) {
394 if (mWriteScheduled) {
395 mWriteScheduled = false;
396 doWrite = true;
397 }
398 }
399 if (doWrite) {
400 writeState();
401 }
402 }
403
Dianne Hackborn72e39832013-01-18 18:36:09 -0800404 private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
405 ArrayList<AppOpsManager.OpEntry> resOps = null;
406 if (ops == null) {
407 resOps = new ArrayList<AppOpsManager.OpEntry>();
408 for (int j=0; j<pkgOps.size(); j++) {
409 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800410 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Svet Ganov99b60432015-06-27 13:15:22 -0700411 curOp.rejectTime, curOp.duration, curOp.proxyUid,
412 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800413 }
414 } else {
415 for (int j=0; j<ops.length; j++) {
416 Op curOp = pkgOps.get(ops[j]);
417 if (curOp != null) {
418 if (resOps == null) {
419 resOps = new ArrayList<AppOpsManager.OpEntry>();
420 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800421 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Svet Ganov99b60432015-06-27 13:15:22 -0700422 curOp.rejectTime, curOp.duration, curOp.proxyUid,
423 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800424 }
425 }
426 }
427 return resOps;
428 }
429
Dianne Hackbornc7214a32017-04-11 13:32:47 -0700430 private ArrayList<AppOpsManager.OpEntry> collectOps(SparseIntArray uidOps, int[] ops) {
431 ArrayList<AppOpsManager.OpEntry> resOps = null;
432 if (ops == null) {
433 resOps = new ArrayList<>();
434 for (int j=0; j<uidOps.size(); j++) {
435 resOps.add(new AppOpsManager.OpEntry(uidOps.keyAt(j), uidOps.valueAt(j),
436 0, 0, 0, -1, null));
437 }
438 } else {
439 for (int j=0; j<ops.length; j++) {
440 int index = uidOps.indexOfKey(ops[j]);
441 if (index >= 0) {
442 if (resOps == null) {
443 resOps = new ArrayList<>();
444 }
445 resOps.add(new AppOpsManager.OpEntry(uidOps.keyAt(index), uidOps.valueAt(index),
446 0, 0, 0, -1, null));
447 }
448 }
449 }
450 return resOps;
451 }
452
Dianne Hackborn35654b62013-01-14 17:38:02 -0800453 @Override
454 public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
455 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
456 Binder.getCallingPid(), Binder.getCallingUid(), null);
457 ArrayList<AppOpsManager.PackageOps> res = null;
458 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700459 final int uidStateCount = mUidStates.size();
460 for (int i = 0; i < uidStateCount; i++) {
461 UidState uidState = mUidStates.valueAt(i);
462 if (uidState.pkgOps == null || uidState.pkgOps.isEmpty()) {
463 continue;
464 }
465 ArrayMap<String, Ops> packages = uidState.pkgOps;
466 final int packageCount = packages.size();
467 for (int j = 0; j < packageCount; j++) {
468 Ops pkgOps = packages.valueAt(j);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800469 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800470 if (resOps != null) {
471 if (res == null) {
472 res = new ArrayList<AppOpsManager.PackageOps>();
473 }
474 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700475 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800476 res.add(resPackage);
477 }
478 }
479 }
480 }
481 return res;
482 }
483
484 @Override
Dianne Hackborn72e39832013-01-18 18:36:09 -0800485 public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
486 int[] ops) {
487 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
488 Binder.getCallingPid(), Binder.getCallingUid(), null);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000489 String resolvedPackageName = resolvePackageName(uid, packageName);
490 if (resolvedPackageName == null) {
491 return Collections.emptyList();
492 }
Dianne Hackborn72e39832013-01-18 18:36:09 -0800493 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000494 Ops pkgOps = getOpsRawLocked(uid, resolvedPackageName, false);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800495 if (pkgOps == null) {
496 return null;
497 }
498 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
499 if (resOps == null) {
500 return null;
501 }
502 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
503 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700504 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800505 res.add(resPackage);
506 return res;
507 }
508 }
509
Dianne Hackbornc7214a32017-04-11 13:32:47 -0700510 @Override
511 public List<AppOpsManager.PackageOps> getUidOps(int uid, int[] ops) {
512 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
513 Binder.getCallingPid(), Binder.getCallingUid(), null);
514 synchronized (this) {
515 UidState uidState = getUidStateLocked(uid, false);
516 if (uidState == null) {
517 return null;
518 }
519 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(uidState.opModes, ops);
520 if (resOps == null) {
521 return null;
522 }
523 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
524 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
525 null, uidState.uid, resOps);
526 res.add(resPackage);
527 return res;
528 }
529 }
530
Dianne Hackborn607b4142013-08-02 18:10:10 -0700531 private void pruneOp(Op op, int uid, String packageName) {
532 if (op.time == 0 && op.rejectTime == 0) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000533 Ops ops = getOpsRawLocked(uid, packageName, false);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700534 if (ops != null) {
535 ops.remove(op.op);
536 if (ops.size() <= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -0700537 UidState uidState = ops.uidState;
538 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700539 if (pkgOps != null) {
540 pkgOps.remove(ops.packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700541 if (pkgOps.isEmpty()) {
542 uidState.pkgOps = null;
543 }
544 if (uidState.isDefault()) {
545 mUidStates.remove(uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700546 }
547 }
548 }
549 }
550 }
551 }
552
Dianne Hackborn72e39832013-01-18 18:36:09 -0800553 @Override
Svet Ganov2af57082015-07-30 08:44:20 -0700554 public void setUidMode(int code, int uid, int mode) {
555 if (Binder.getCallingPid() != Process.myPid()) {
556 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
557 Binder.getCallingPid(), Binder.getCallingUid(), null);
558 }
559 verifyIncomingOp(code);
560 code = AppOpsManager.opToSwitch(code);
561
562 synchronized (this) {
563 final int defaultMode = AppOpsManager.opToDefaultMode(code);
564
565 UidState uidState = getUidStateLocked(uid, false);
566 if (uidState == null) {
567 if (mode == defaultMode) {
568 return;
569 }
570 uidState = new UidState(uid);
571 uidState.opModes = new SparseIntArray();
572 uidState.opModes.put(code, mode);
573 mUidStates.put(uid, uidState);
574 scheduleWriteLocked();
575 } else if (uidState.opModes == null) {
576 if (mode != defaultMode) {
577 uidState.opModes = new SparseIntArray();
578 uidState.opModes.put(code, mode);
579 scheduleWriteLocked();
580 }
581 } else {
582 if (uidState.opModes.get(code) == mode) {
583 return;
584 }
585 if (mode == defaultMode) {
586 uidState.opModes.delete(code);
587 if (uidState.opModes.size() <= 0) {
588 uidState.opModes = null;
589 }
590 } else {
591 uidState.opModes.put(code, mode);
592 }
593 scheduleWriteLocked();
594 }
595 }
596
Svetoslav215b44a2015-08-04 19:03:40 -0700597 String[] uidPackageNames = getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -0700598 ArrayMap<Callback, ArraySet<String>> callbackSpecs = null;
599
riddle_hsu40b300f2015-11-23 13:22:03 +0800600 synchronized (this) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800601 ArraySet<Callback> callbacks = mOpModeWatchers.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -0700602 if (callbacks != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700603 final int callbackCount = callbacks.size();
604 for (int i = 0; i < callbackCount; i++) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800605 Callback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +0800606 ArraySet<String> changedPackages = new ArraySet<>();
607 Collections.addAll(changedPackages, uidPackageNames);
608 callbackSpecs = new ArrayMap<>();
609 callbackSpecs.put(callback, changedPackages);
610 }
611 }
612
613 for (String uidPackageName : uidPackageNames) {
614 callbacks = mPackageModeWatchers.get(uidPackageName);
615 if (callbacks != null) {
616 if (callbackSpecs == null) {
617 callbackSpecs = new ArrayMap<>();
Svet Ganov2af57082015-07-30 08:44:20 -0700618 }
riddle_hsu40b300f2015-11-23 13:22:03 +0800619 final int callbackCount = callbacks.size();
620 for (int i = 0; i < callbackCount; i++) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800621 Callback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +0800622 ArraySet<String> changedPackages = callbackSpecs.get(callback);
623 if (changedPackages == null) {
624 changedPackages = new ArraySet<>();
625 callbackSpecs.put(callback, changedPackages);
626 }
627 changedPackages.add(uidPackageName);
628 }
Svet Ganov2af57082015-07-30 08:44:20 -0700629 }
630 }
631 }
632
633 if (callbackSpecs == null) {
634 return;
635 }
636
637 // There are components watching for mode changes such as window manager
638 // and location manager which are in our process. The callbacks in these
639 // components may require permissions our remote caller does not have.
640 final long identity = Binder.clearCallingIdentity();
641 try {
642 for (int i = 0; i < callbackSpecs.size(); i++) {
643 Callback callback = callbackSpecs.keyAt(i);
644 ArraySet<String> reportedPackageNames = callbackSpecs.valueAt(i);
645 try {
646 if (reportedPackageNames == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700647 callback.mCallback.opChanged(code, uid, null);
Svet Ganov2af57082015-07-30 08:44:20 -0700648 } else {
649 final int reportedPackageCount = reportedPackageNames.size();
650 for (int j = 0; j < reportedPackageCount; j++) {
651 String reportedPackageName = reportedPackageNames.valueAt(j);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700652 callback.mCallback.opChanged(code, uid, reportedPackageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700653 }
654 }
655 } catch (RemoteException e) {
656 Log.w(TAG, "Error dispatching op op change", e);
657 }
658 }
659 } finally {
660 Binder.restoreCallingIdentity(identity);
661 }
662 }
663
664 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800665 public void setMode(int code, int uid, String packageName, int mode) {
Dianne Hackbornb64afe12014-07-22 16:29:04 -0700666 if (Binder.getCallingPid() != Process.myPid()) {
667 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
668 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborn133b9df2014-07-01 13:06:10 -0700669 }
Dianne Hackborn961321f2013-02-05 17:22:41 -0800670 verifyIncomingOp(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800671 ArrayList<Callback> repCbs = null;
672 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800673 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700674 UidState uidState = getUidStateLocked(uid, false);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800675 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800676 if (op != null) {
677 if (op.mode != mode) {
678 op.mode = mode;
Dianne Hackborn68d76552017-02-27 15:32:03 -0800679 ArraySet<Callback> cbs = mOpModeWatchers.get(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800680 if (cbs != null) {
681 if (repCbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800682 repCbs = new ArrayList<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800683 }
684 repCbs.addAll(cbs);
685 }
686 cbs = mPackageModeWatchers.get(packageName);
687 if (cbs != null) {
688 if (repCbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800689 repCbs = new ArrayList<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800690 }
691 repCbs.addAll(cbs);
692 }
David Braunf5d83192013-09-16 13:43:51 -0700693 if (mode == AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800694 // If going into the default mode, prune this op
695 // if there is nothing else interesting in it.
Dianne Hackborn607b4142013-08-02 18:10:10 -0700696 pruneOp(op, uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800697 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800698 scheduleFastWriteLocked();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800699 }
700 }
701 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800702 if (repCbs != null) {
Svet Ganov38536112015-05-19 12:45:52 -0700703 // There are components watching for mode changes such as window manager
704 // and location manager which are in our process. The callbacks in these
705 // components may require permissions our remote caller does not have.
706 final long identity = Binder.clearCallingIdentity();
707 try {
708 for (int i = 0; i < repCbs.size(); i++) {
709 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700710 repCbs.get(i).mCallback.opChanged(code, uid, packageName);
Svet Ganov38536112015-05-19 12:45:52 -0700711 } catch (RemoteException e) {
712 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800713 }
Svet Ganov38536112015-05-19 12:45:52 -0700714 } finally {
715 Binder.restoreCallingIdentity(identity);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800716 }
717 }
718 }
719
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700720 private static HashMap<Callback, ArrayList<ChangeRec>> addCallbacks(
721 HashMap<Callback, ArrayList<ChangeRec>> callbacks,
Dianne Hackborn68d76552017-02-27 15:32:03 -0800722 int op, int uid, String packageName, ArraySet<Callback> cbs) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700723 if (cbs == null) {
724 return callbacks;
725 }
726 if (callbacks == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700727 callbacks = new HashMap<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700728 }
Svet Ganov2af57082015-07-30 08:44:20 -0700729 boolean duplicate = false;
Dianne Hackborn68d76552017-02-27 15:32:03 -0800730 final int N = cbs.size();
731 for (int i=0; i<N; i++) {
732 Callback cb = cbs.valueAt(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700733 ArrayList<ChangeRec> reports = callbacks.get(cb);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700734 if (reports == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700735 reports = new ArrayList<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700736 callbacks.put(cb, reports);
Svet Ganov2af57082015-07-30 08:44:20 -0700737 } else {
738 final int reportCount = reports.size();
739 for (int j = 0; j < reportCount; j++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700740 ChangeRec report = reports.get(j);
741 if (report.op == op && report.pkg.equals(packageName)) {
Svet Ganov2af57082015-07-30 08:44:20 -0700742 duplicate = true;
743 break;
744 }
745 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700746 }
Svet Ganov2af57082015-07-30 08:44:20 -0700747 if (!duplicate) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700748 reports.add(new ChangeRec(op, uid, packageName));
Svet Ganov2af57082015-07-30 08:44:20 -0700749 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700750 }
751 return callbacks;
752 }
753
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700754 static final class ChangeRec {
755 final int op;
756 final int uid;
757 final String pkg;
758
759 ChangeRec(int _op, int _uid, String _pkg) {
760 op = _op;
761 uid = _uid;
762 pkg = _pkg;
763 }
764 }
765
Dianne Hackborn607b4142013-08-02 18:10:10 -0700766 @Override
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800767 public void resetAllModes(int reqUserId, String reqPackageName) {
768 final int callingPid = Binder.getCallingPid();
769 final int callingUid = Binder.getCallingUid();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700770 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800771 callingPid, callingUid, null);
772 reqUserId = ActivityManager.handleIncomingUser(callingPid, callingUid, reqUserId,
773 true, true, "resetAllModes", null);
Svet Ganov2af57082015-07-30 08:44:20 -0700774
775 int reqUid = -1;
776 if (reqPackageName != null) {
777 try {
778 reqUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -0700779 reqPackageName, PackageManager.MATCH_UNINSTALLED_PACKAGES, reqUserId);
Svet Ganov2af57082015-07-30 08:44:20 -0700780 } catch (RemoteException e) {
781 /* ignore - local call */
782 }
783 }
784
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700785 HashMap<Callback, ArrayList<ChangeRec>> callbacks = null;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700786 synchronized (this) {
787 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700788 for (int i = mUidStates.size() - 1; i >= 0; i--) {
789 UidState uidState = mUidStates.valueAt(i);
790
791 SparseIntArray opModes = uidState.opModes;
792 if (opModes != null && (uidState.uid == reqUid || reqUid == -1)) {
793 final int uidOpCount = opModes.size();
794 for (int j = uidOpCount - 1; j >= 0; j--) {
795 final int code = opModes.keyAt(j);
796 if (AppOpsManager.opAllowsReset(code)) {
797 opModes.removeAt(j);
798 if (opModes.size() <= 0) {
799 uidState.opModes = null;
800 }
801 for (String packageName : getPackagesForUid(uidState.uid)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700802 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700803 mOpModeWatchers.get(code));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700804 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700805 mPackageModeWatchers.get(packageName));
806 }
807 }
808 }
809 }
810
811 if (uidState.pkgOps == null) {
812 continue;
813 }
814
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800815 if (reqUserId != UserHandle.USER_ALL
Svet Ganov2af57082015-07-30 08:44:20 -0700816 && reqUserId != UserHandle.getUserId(uidState.uid)) {
Alexandra Gherghinad6a98972014-08-04 17:05:34 +0100817 // Skip any ops for a different user
818 continue;
819 }
Svet Ganov2af57082015-07-30 08:44:20 -0700820
821 Map<String, Ops> packages = uidState.pkgOps;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700822 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
823 while (it.hasNext()) {
824 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700825 String packageName = ent.getKey();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800826 if (reqPackageName != null && !reqPackageName.equals(packageName)) {
827 // Skip any ops for a different package
828 continue;
829 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700830 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700831 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700832 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -0700833 if (AppOpsManager.opAllowsReset(curOp.op)
834 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -0700835 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700836 changed = true;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700837 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -0700838 mOpModeWatchers.get(curOp.op));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700839 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -0700840 mPackageModeWatchers.get(packageName));
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700841 if (curOp.time == 0 && curOp.rejectTime == 0) {
842 pkgOps.removeAt(j);
843 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700844 }
845 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700846 if (pkgOps.size() == 0) {
847 it.remove();
848 }
849 }
Svet Ganov2af57082015-07-30 08:44:20 -0700850 if (uidState.isDefault()) {
851 mUidStates.remove(uidState.uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700852 }
853 }
Svet Ganov2af57082015-07-30 08:44:20 -0700854
Dianne Hackborn607b4142013-08-02 18:10:10 -0700855 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800856 scheduleFastWriteLocked();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700857 }
858 }
859 if (callbacks != null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700860 for (Map.Entry<Callback, ArrayList<ChangeRec>> ent : callbacks.entrySet()) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700861 Callback cb = ent.getKey();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700862 ArrayList<ChangeRec> reports = ent.getValue();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700863 for (int i=0; i<reports.size(); i++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700864 ChangeRec rep = reports.get(i);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700865 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700866 cb.mCallback.opChanged(rep.op, rep.uid, rep.pkg);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700867 } catch (RemoteException e) {
868 }
869 }
870 }
871 }
872 }
873
Dianne Hackbornc2293022013-02-06 23:14:49 -0800874 @Override
875 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -0800876 if (callback == null) {
877 return;
878 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800879 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700880 op = (op != AppOpsManager.OP_NONE) ? AppOpsManager.opToSwitch(op) : op;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800881 Callback cb = mModeWatchers.get(callback.asBinder());
882 if (cb == null) {
883 cb = new Callback(callback);
884 mModeWatchers.put(callback.asBinder(), cb);
885 }
886 if (op != AppOpsManager.OP_NONE) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800887 ArraySet<Callback> cbs = mOpModeWatchers.get(op);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800888 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800889 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800890 mOpModeWatchers.put(op, cbs);
891 }
892 cbs.add(cb);
893 }
894 if (packageName != null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800895 ArraySet<Callback> cbs = mPackageModeWatchers.get(packageName);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800896 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800897 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800898 mPackageModeWatchers.put(packageName, cbs);
899 }
900 cbs.add(cb);
901 }
902 }
903 }
904
905 @Override
906 public void stopWatchingMode(IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -0800907 if (callback == null) {
908 return;
909 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800910 synchronized (this) {
911 Callback cb = mModeWatchers.remove(callback.asBinder());
912 if (cb != null) {
913 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700914 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800915 ArraySet<Callback> cbs = mOpModeWatchers.valueAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800916 cbs.remove(cb);
917 if (cbs.size() <= 0) {
918 mOpModeWatchers.removeAt(i);
919 }
920 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700921 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
Dianne Hackborn68d76552017-02-27 15:32:03 -0800922 ArraySet<Callback> cbs = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700923 cbs.remove(cb);
924 if (cbs.size() <= 0) {
925 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800926 }
927 }
928 }
929 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800930 }
931
932 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700933 public IBinder getToken(IBinder clientToken) {
934 synchronized (this) {
935 ClientState cs = mClients.get(clientToken);
936 if (cs == null) {
937 cs = new ClientState(clientToken);
938 mClients.put(clientToken, cs);
939 }
940 return cs;
941 }
942 }
943
944 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800945 public int checkOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800946 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800947 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000948 String resolvedPackageName = resolvePackageName(uid, packageName);
949 if (resolvedPackageName == null) {
950 return AppOpsManager.MODE_IGNORED;
951 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800952 synchronized (this) {
Svet Ganov442ed572016-08-17 17:29:43 -0700953 if (isOpRestrictedLocked(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -0400954 return AppOpsManager.MODE_IGNORED;
955 }
Svet Ganov2af57082015-07-30 08:44:20 -0700956 code = AppOpsManager.opToSwitch(code);
957 UidState uidState = getUidStateLocked(uid, false);
Svet Ganovee438d42017-01-19 18:04:38 -0800958 if (uidState != null && uidState.opModes != null
959 && uidState.opModes.indexOfKey(code) >= 0) {
960 return uidState.opModes.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -0700961 }
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000962 Op op = getOpLocked(code, uid, resolvedPackageName, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800963 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -0700964 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800965 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800966 return op.mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800967 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800968 }
969
970 @Override
John Spurlock7b414672014-07-18 13:02:39 -0400971 public int checkAudioOperation(int code, int usage, int uid, String packageName) {
Andrei Stingaceanuefc4a342016-03-22 14:43:01 +0000972 boolean suspended;
973 try {
974 suspended = isPackageSuspendedForUser(packageName, uid);
975 } catch (IllegalArgumentException ex) {
976 // Package not found.
977 suspended = false;
978 }
979
980 if (suspended) {
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000981 Log.i(TAG, "Audio disabled for suspended package=" + packageName + " for uid=" + uid);
982 return AppOpsManager.MODE_IGNORED;
983 }
984
John Spurlock1af30c72014-03-10 08:33:35 -0400985 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -0400986 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -0400987 if (mode != AppOpsManager.MODE_ALLOWED) {
988 return mode;
989 }
990 }
991 return checkOperation(code, uid, packageName);
992 }
993
Andrei Stingaceanu355b2322016-02-12 16:43:51 +0000994 private boolean isPackageSuspendedForUser(String pkg, int uid) {
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000995 try {
Andrei Stingaceanu355b2322016-02-12 16:43:51 +0000996 return AppGlobals.getPackageManager().isPackageSuspendedForUser(
997 pkg, UserHandle.getUserId(uid));
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000998 } catch (RemoteException re) {
999 throw new SecurityException("Could not talk to package manager service");
1000 }
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001001 }
1002
John Spurlock7b414672014-07-18 13:02:39 -04001003 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
1004 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1005 if (usageRestrictions != null) {
1006 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001007 if (r != null && !r.exceptionPackages.contains(packageName)) {
1008 return r.mode;
1009 }
1010 }
1011 return AppOpsManager.MODE_ALLOWED;
1012 }
1013
1014 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001015 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -04001016 String[] exceptionPackages) {
1017 verifyIncomingUid(uid);
1018 verifyIncomingOp(code);
1019 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001020 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1021 if (usageRestrictions == null) {
1022 usageRestrictions = new SparseArray<Restriction>();
1023 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -04001024 }
John Spurlock7b414672014-07-18 13:02:39 -04001025 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001026 if (mode != AppOpsManager.MODE_ALLOWED) {
1027 final Restriction r = new Restriction();
1028 r.mode = mode;
1029 if (exceptionPackages != null) {
1030 final int N = exceptionPackages.length;
1031 r.exceptionPackages = new ArraySet<String>(N);
1032 for (int i = 0; i < N; i++) {
1033 final String pkg = exceptionPackages[i];
1034 if (pkg != null) {
1035 r.exceptionPackages.add(pkg.trim());
1036 }
1037 }
1038 }
John Spurlock7b414672014-07-18 13:02:39 -04001039 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -04001040 }
1041 }
Julia Reynoldsbb21c252016-04-05 16:01:49 -04001042 notifyWatchersOfChange(code);
John Spurlock1af30c72014-03-10 08:33:35 -04001043 }
1044
1045 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001046 public int checkPackage(int uid, String packageName) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001047 Preconditions.checkNotNull(packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001048 synchronized (this) {
Dianne Hackborn0fcef842014-09-12 15:38:33 -07001049 if (getOpsRawLocked(uid, packageName, true) != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001050 return AppOpsManager.MODE_ALLOWED;
1051 } else {
1052 return AppOpsManager.MODE_ERRORED;
1053 }
1054 }
1055 }
1056
1057 @Override
Svet Ganov99b60432015-06-27 13:15:22 -07001058 public int noteProxyOperation(int code, String proxyPackageName,
1059 int proxiedUid, String proxiedPackageName) {
1060 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001061 final int proxyUid = Binder.getCallingUid();
1062 String resolveProxyPackageName = resolvePackageName(proxyUid, proxyPackageName);
1063 if (resolveProxyPackageName == null) {
1064 return AppOpsManager.MODE_IGNORED;
1065 }
1066 final int proxyMode = noteOperationUnchecked(code, proxyUid,
1067 resolveProxyPackageName, -1, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001068 if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
1069 return proxyMode;
1070 }
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001071 String resolveProxiedPackageName = resolvePackageName(proxiedUid, proxiedPackageName);
1072 if (resolveProxiedPackageName == null) {
1073 return AppOpsManager.MODE_IGNORED;
1074 }
1075 return noteOperationUnchecked(code, proxiedUid, resolveProxiedPackageName,
1076 proxyMode, resolveProxyPackageName);
Svet Ganov99b60432015-06-27 13:15:22 -07001077 }
1078
1079 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001080 public int noteOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001081 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001082 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001083 String resolvedPackageName = resolvePackageName(uid, packageName);
1084 if (resolvedPackageName == null) {
1085 return AppOpsManager.MODE_IGNORED;
1086 }
1087 return noteOperationUnchecked(code, uid, resolvedPackageName, 0, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001088 }
1089
1090 private int noteOperationUnchecked(int code, int uid, String packageName,
1091 int proxyUid, String proxyPackageName) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001092 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001093 Ops ops = getOpsRawLocked(uid, packageName, true);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001094 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001095 if (DEBUG) Log.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
1096 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001097 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001098 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001099 Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07001100 if (isOpRestrictedLocked(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001101 return AppOpsManager.MODE_IGNORED;
1102 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001103 if (op.duration == -1) {
1104 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
1105 + " code " + code + " time=" + op.time + " duration=" + op.duration);
1106 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001107 op.duration = 0;
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001108 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001109 UidState uidState = ops.uidState;
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001110 // If there is a non-default per UID policy (we set UID op mode only if
1111 // non-default) it takes over, otherwise use the per package policy.
1112 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -07001113 final int uidMode = uidState.opModes.get(switchCode);
1114 if (uidMode != AppOpsManager.MODE_ALLOWED) {
1115 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1116 + switchCode + " (" + code + ") uid " + uid + " package "
1117 + packageName);
1118 op.rejectTime = System.currentTimeMillis();
1119 return uidMode;
1120 }
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001121 } else {
1122 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
1123 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
1124 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1125 + switchCode + " (" + code + ") uid " + uid + " package "
1126 + packageName);
1127 op.rejectTime = System.currentTimeMillis();
1128 return switchOp.mode;
1129 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001130 }
1131 if (DEBUG) Log.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
1132 + " package " + packageName);
1133 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001134 op.rejectTime = 0;
Svet Ganov99b60432015-06-27 13:15:22 -07001135 op.proxyUid = proxyUid;
1136 op.proxyPackageName = proxyPackageName;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001137 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001138 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001139 }
1140
1141 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001142 public int startOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001143 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001144 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001145 String resolvedPackageName = resolvePackageName(uid, packageName);
1146 if (resolvedPackageName == null) {
1147 return AppOpsManager.MODE_IGNORED;
1148 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001149 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001150 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001151 Ops ops = getOpsRawLocked(uid, resolvedPackageName, true);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001152 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001153 if (DEBUG) Log.d(TAG, "startOperation: no op for code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001154 + " package " + resolvedPackageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001155 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001156 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001157 Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07001158 if (isOpRestrictedLocked(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001159 return AppOpsManager.MODE_IGNORED;
1160 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001161 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001162 UidState uidState = ops.uidState;
1163 if (uidState.opModes != null) {
1164 final int uidMode = uidState.opModes.get(switchCode);
1165 if (uidMode != AppOpsManager.MODE_ALLOWED) {
1166 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1167 + switchCode + " (" + code + ") uid " + uid + " package "
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001168 + resolvedPackageName);
Svet Ganov2af57082015-07-30 08:44:20 -07001169 op.rejectTime = System.currentTimeMillis();
1170 return uidMode;
1171 }
1172 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001173 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
1174 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
1175 if (DEBUG) Log.d(TAG, "startOperation: reject #" + op.mode + " for code "
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001176 + switchCode + " (" + code + ") uid " + uid + " package "
1177 + resolvedPackageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001178 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001179 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001180 }
1181 if (DEBUG) Log.d(TAG, "startOperation: allowing code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001182 + " package " + resolvedPackageName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001183 if (op.nesting == 0) {
1184 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001185 op.rejectTime = 0;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001186 op.duration = -1;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001187 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001188 op.nesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001189 if (client.mStartedOps != null) {
1190 client.mStartedOps.add(op);
1191 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001192 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001193 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001194 }
1195
1196 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001197 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001198 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001199 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001200 String resolvedPackageName = resolvePackageName(uid, packageName);
1201 if (resolvedPackageName == null) {
1202 return;
1203 }
1204 if (!(token instanceof ClientState)) {
1205 return;
1206 }
1207 ClientState client = (ClientState) token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001208 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001209 Op op = getOpLocked(code, uid, resolvedPackageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001210 if (op == null) {
1211 return;
1212 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001213 if (client.mStartedOps != null) {
1214 if (!client.mStartedOps.remove(op)) {
1215 throw new IllegalStateException("Operation not started: uid" + op.uid
1216 + " pkg=" + op.packageName + " op=" + op.op);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001217 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001218 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001219 finishOperationLocked(op);
1220 }
1221 }
1222
Svet Ganovb9d71a62015-04-30 10:38:13 -07001223 @Override
1224 public int permissionToOpCode(String permission) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001225 if (permission == null) {
1226 return AppOpsManager.OP_NONE;
1227 }
Svet Ganovb9d71a62015-04-30 10:38:13 -07001228 return AppOpsManager.permissionToOpCode(permission);
1229 }
1230
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001231 void finishOperationLocked(Op op) {
1232 if (op.nesting <= 1) {
1233 if (op.nesting == 1) {
1234 op.duration = (int)(System.currentTimeMillis() - op.time);
1235 op.time += op.duration;
1236 } else {
1237 Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
1238 + op.packageName + " code " + op.op + " time=" + op.time
1239 + " duration=" + op.duration + " nesting=" + op.nesting);
1240 }
1241 op.nesting = 0;
1242 } else {
1243 op.nesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001244 }
1245 }
1246
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001247 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001248 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001249 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001250 }
1251 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001252 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001253 }
1254 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
1255 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001256 }
1257
Dianne Hackborn961321f2013-02-05 17:22:41 -08001258 private void verifyIncomingOp(int op) {
1259 if (op >= 0 && op < AppOpsManager._NUM_OP) {
1260 return;
1261 }
1262 throw new IllegalArgumentException("Bad operation #" + op);
1263 }
1264
Svet Ganov2af57082015-07-30 08:44:20 -07001265 private UidState getUidStateLocked(int uid, boolean edit) {
1266 UidState uidState = mUidStates.get(uid);
1267 if (uidState == null) {
1268 if (!edit) {
1269 return null;
1270 }
1271 uidState = new UidState(uid);
1272 mUidStates.put(uid, uidState);
1273 }
1274 return uidState;
1275 }
1276
Dianne Hackborn0fcef842014-09-12 15:38:33 -07001277 private Ops getOpsRawLocked(int uid, String packageName, boolean edit) {
Svet Ganov2af57082015-07-30 08:44:20 -07001278 UidState uidState = getUidStateLocked(uid, edit);
1279 if (uidState == null) {
1280 return null;
1281 }
1282
1283 if (uidState.pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001284 if (!edit) {
1285 return null;
1286 }
Svet Ganov2af57082015-07-30 08:44:20 -07001287 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001288 }
Svet Ganov2af57082015-07-30 08:44:20 -07001289
1290 Ops ops = uidState.pkgOps.get(packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001291 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001292 if (!edit) {
1293 return null;
1294 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001295 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001296 // This is the first time we have seen this package name under this uid,
1297 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -08001298 if (uid != 0) {
1299 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001300 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001301 int pkgUid = -1;
1302 try {
Jason Monk1c7c3192014-06-26 12:52:18 -04001303 ApplicationInfo appInfo = ActivityThread.getPackageManager()
Jeff Sharkeycd654482016-01-08 17:42:11 -07001304 .getApplicationInfo(packageName,
1305 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1306 UserHandle.getUserId(uid));
Jason Monk1c7c3192014-06-26 12:52:18 -04001307 if (appInfo != null) {
1308 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001309 isPrivileged = (appInfo.privateFlags
1310 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001311 } else {
1312 if ("media".equals(packageName)) {
1313 pkgUid = Process.MEDIA_UID;
1314 isPrivileged = false;
Andy Hunged0ea402015-10-30 14:11:46 -07001315 } else if ("audioserver".equals(packageName)) {
1316 pkgUid = Process.AUDIOSERVER_UID;
1317 isPrivileged = false;
Chien-Yu Chen75cade02016-01-11 10:56:21 -08001318 } else if ("cameraserver".equals(packageName)) {
1319 pkgUid = Process.CAMERASERVER_UID;
1320 isPrivileged = false;
Jason Monk1c7c3192014-06-26 12:52:18 -04001321 }
Dianne Hackborn713df152013-05-17 11:27:57 -07001322 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001323 } catch (RemoteException e) {
1324 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001325 }
1326 if (pkgUid != uid) {
1327 // Oops! The package name is not valid for the uid they are calling
1328 // under. Abort.
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001329 RuntimeException ex = new RuntimeException("here");
1330 ex.fillInStackTrace();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001331 Slog.w(TAG, "Bad call: specified package " + packageName
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001332 + " under uid " + uid + " but it is really " + pkgUid, ex);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001333 return null;
1334 }
1335 } finally {
1336 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001337 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001338 }
Svet Ganov2af57082015-07-30 08:44:20 -07001339 ops = new Ops(packageName, uidState, isPrivileged);
1340 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001341 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08001342 return ops;
1343 }
1344
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001345 private void scheduleWriteLocked() {
1346 if (!mWriteScheduled) {
1347 mWriteScheduled = true;
1348 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
1349 }
1350 }
1351
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001352 private void scheduleFastWriteLocked() {
1353 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001354 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001355 mFastWriteScheduled = true;
1356 mHandler.removeCallbacks(mWriteRunner);
1357 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001358 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001359 }
1360
Dianne Hackborn72e39832013-01-18 18:36:09 -08001361 private Op getOpLocked(int code, int uid, String packageName, boolean edit) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001362 Ops ops = getOpsRawLocked(uid, packageName, edit);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001363 if (ops == null) {
1364 return null;
1365 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001366 return getOpLocked(ops, code, edit);
1367 }
1368
1369 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001370 Op op = ops.get(code);
1371 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001372 if (!edit) {
1373 return null;
1374 }
Svet Ganov2af57082015-07-30 08:44:20 -07001375 op = new Op(ops.uidState.uid, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001376 ops.put(code, op);
1377 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001378 if (edit) {
1379 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001380 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001381 return op;
1382 }
1383
Svet Ganov442ed572016-08-17 17:29:43 -07001384 private boolean isOpRestrictedLocked(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04001385 int userHandle = UserHandle.getUserId(uid);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001386 final int restrictionSetCount = mOpUserRestrictions.size();
Ruben Brunk29931bc2016-03-11 00:24:26 -08001387
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001388 for (int i = 0; i < restrictionSetCount; i++) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08001389 // For each client, check that the given op is not restricted, or that the given
1390 // package is exempt from the restriction.
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07001391 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07001392 if (restrictionState.hasRestriction(code, packageName, userHandle)) {
1393 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
1394 // If we are the system, bypass user restrictions for certain codes
1395 synchronized (this) {
1396 Ops ops = getOpsRawLocked(uid, packageName, true);
1397 if ((ops != null) && ops.isPrivileged) {
1398 return false;
1399 }
Ruben Brunk32f0fa42016-03-11 19:07:07 -08001400 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08001401 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001402 return true;
Jason Monk1c7c3192014-06-26 12:52:18 -04001403 }
Jason Monk62062992014-05-06 09:55:28 -04001404 }
1405 return false;
1406 }
1407
Dianne Hackborn35654b62013-01-14 17:38:02 -08001408 void readState() {
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001409 int oldVersion = NO_VERSION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001410 synchronized (mFile) {
1411 synchronized (this) {
1412 FileInputStream stream;
1413 try {
1414 stream = mFile.openRead();
1415 } catch (FileNotFoundException e) {
1416 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
1417 return;
1418 }
1419 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001420 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001421 try {
1422 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001423 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001424 int type;
1425 while ((type = parser.next()) != XmlPullParser.START_TAG
1426 && type != XmlPullParser.END_DOCUMENT) {
1427 ;
1428 }
1429
1430 if (type != XmlPullParser.START_TAG) {
1431 throw new IllegalStateException("no start tag found");
1432 }
1433
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001434 final String versionString = parser.getAttributeValue(null, "v");
1435 if (versionString != null) {
1436 oldVersion = Integer.parseInt(versionString);
1437 }
1438
Dianne Hackborn35654b62013-01-14 17:38:02 -08001439 int outerDepth = parser.getDepth();
1440 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1441 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1442 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1443 continue;
1444 }
1445
1446 String tagName = parser.getName();
1447 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001448 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07001449 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07001450 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001451 } else {
1452 Slog.w(TAG, "Unknown element under <app-ops>: "
1453 + parser.getName());
1454 XmlUtils.skipCurrentTag(parser);
1455 }
1456 }
1457 success = true;
1458 } catch (IllegalStateException e) {
1459 Slog.w(TAG, "Failed parsing " + e);
1460 } catch (NullPointerException e) {
1461 Slog.w(TAG, "Failed parsing " + e);
1462 } catch (NumberFormatException e) {
1463 Slog.w(TAG, "Failed parsing " + e);
1464 } catch (XmlPullParserException e) {
1465 Slog.w(TAG, "Failed parsing " + e);
1466 } catch (IOException e) {
1467 Slog.w(TAG, "Failed parsing " + e);
1468 } catch (IndexOutOfBoundsException e) {
1469 Slog.w(TAG, "Failed parsing " + e);
1470 } finally {
1471 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07001472 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001473 }
1474 try {
1475 stream.close();
1476 } catch (IOException e) {
1477 }
1478 }
1479 }
1480 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001481 synchronized (this) {
1482 upgradeLocked(oldVersion);
1483 }
1484 }
1485
1486 private void upgradeRunAnyInBackgroundLocked() {
1487 for (int i = 0; i < mUidStates.size(); i++) {
1488 final UidState uidState = mUidStates.valueAt(i);
1489 if (uidState == null) {
1490 continue;
1491 }
1492 if (uidState.opModes != null) {
1493 final int idx = uidState.opModes.indexOfKey(AppOpsManager.OP_RUN_IN_BACKGROUND);
1494 if (idx >= 0) {
1495 uidState.opModes.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND,
1496 uidState.opModes.valueAt(idx));
1497 }
1498 }
1499 if (uidState.pkgOps == null) {
1500 continue;
1501 }
1502 for (int j = 0; j < uidState.pkgOps.size(); j++) {
1503 Ops ops = uidState.pkgOps.valueAt(j);
1504 if (ops != null) {
1505 final Op op = ops.get(AppOpsManager.OP_RUN_IN_BACKGROUND);
1506 if (op != null && op.mode != AppOpsManager.opToDefaultMode(op.op)) {
1507 final Op copy = new Op(op.uid, op.packageName,
1508 AppOpsManager.OP_RUN_ANY_IN_BACKGROUND);
1509 copy.mode = op.mode;
1510 ops.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, copy);
1511 }
1512 }
1513 }
1514 }
1515 }
1516
1517 private void upgradeLocked(int oldVersion) {
1518 if (oldVersion >= CURRENT_VERSION) {
1519 return;
1520 }
1521 Slog.d(TAG, "Upgrading app-ops xml from version " + oldVersion + " to " + CURRENT_VERSION);
1522 switch (oldVersion) {
1523 case NO_VERSION:
1524 upgradeRunAnyInBackgroundLocked();
1525 // fall through
1526 case 1:
1527 // for future upgrades
1528 }
1529 scheduleFastWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001530 }
1531
Svet Ganov2af57082015-07-30 08:44:20 -07001532 void readUidOps(XmlPullParser parser) throws NumberFormatException,
1533 XmlPullParserException, IOException {
1534 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
1535 int outerDepth = parser.getDepth();
1536 int type;
1537 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1538 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1539 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1540 continue;
1541 }
1542
1543 String tagName = parser.getName();
1544 if (tagName.equals("op")) {
1545 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
1546 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
1547 UidState uidState = getUidStateLocked(uid, true);
1548 if (uidState.opModes == null) {
1549 uidState.opModes = new SparseIntArray();
1550 }
1551 uidState.opModes.put(code, mode);
1552 } else {
1553 Slog.w(TAG, "Unknown element under <uid-ops>: "
1554 + parser.getName());
1555 XmlUtils.skipCurrentTag(parser);
1556 }
1557 }
1558 }
1559
Dave Burke0997c5bd2013-08-02 20:25:02 +00001560 void readPackage(XmlPullParser parser) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001561 XmlPullParserException, IOException {
1562 String pkgName = parser.getAttributeValue(null, "n");
1563 int outerDepth = parser.getDepth();
1564 int type;
1565 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1566 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1567 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1568 continue;
1569 }
1570
1571 String tagName = parser.getName();
1572 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001573 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001574 } else {
1575 Slog.w(TAG, "Unknown element under <pkg>: "
1576 + parser.getName());
1577 XmlUtils.skipCurrentTag(parser);
1578 }
1579 }
1580 }
1581
Dave Burke0997c5bd2013-08-02 20:25:02 +00001582 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001583 XmlPullParserException, IOException {
1584 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Jason Monk1c7c3192014-06-26 12:52:18 -04001585 String isPrivilegedString = parser.getAttributeValue(null, "p");
1586 boolean isPrivileged = false;
1587 if (isPrivilegedString == null) {
1588 try {
1589 IPackageManager packageManager = ActivityThread.getPackageManager();
1590 if (packageManager != null) {
1591 ApplicationInfo appInfo = ActivityThread.getPackageManager()
1592 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
1593 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001594 isPrivileged = (appInfo.privateFlags
1595 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001596 }
1597 } else {
1598 // Could not load data, don't add to cache so it will be loaded later.
1599 return;
1600 }
1601 } catch (RemoteException e) {
1602 Slog.w(TAG, "Could not contact PackageManager", e);
1603 }
1604 } else {
1605 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
1606 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001607 int outerDepth = parser.getDepth();
1608 int type;
1609 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1610 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1611 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1612 continue;
1613 }
1614
1615 String tagName = parser.getName();
1616 if (tagName.equals("op")) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001617 Op op = new Op(uid, pkgName, Integer.parseInt(parser.getAttributeValue(null, "n")));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001618 String mode = parser.getAttributeValue(null, "m");
1619 if (mode != null) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001620 op.mode = Integer.parseInt(mode);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001621 }
1622 String time = parser.getAttributeValue(null, "t");
1623 if (time != null) {
1624 op.time = Long.parseLong(time);
1625 }
1626 time = parser.getAttributeValue(null, "r");
1627 if (time != null) {
1628 op.rejectTime = Long.parseLong(time);
1629 }
1630 String dur = parser.getAttributeValue(null, "d");
1631 if (dur != null) {
1632 op.duration = Integer.parseInt(dur);
1633 }
Svet Ganov99b60432015-06-27 13:15:22 -07001634 String proxyUid = parser.getAttributeValue(null, "pu");
1635 if (proxyUid != null) {
1636 op.proxyUid = Integer.parseInt(proxyUid);
1637 }
1638 String proxyPackageName = parser.getAttributeValue(null, "pp");
1639 if (proxyPackageName != null) {
1640 op.proxyPackageName = proxyPackageName;
1641 }
Svet Ganov2af57082015-07-30 08:44:20 -07001642
1643 UidState uidState = getUidStateLocked(uid, true);
1644 if (uidState.pkgOps == null) {
1645 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001646 }
Svet Ganov2af57082015-07-30 08:44:20 -07001647
1648 Ops ops = uidState.pkgOps.get(pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001649 if (ops == null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001650 ops = new Ops(pkgName, uidState, isPrivileged);
1651 uidState.pkgOps.put(pkgName, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001652 }
1653 ops.put(op.op, op);
1654 } else {
1655 Slog.w(TAG, "Unknown element under <pkg>: "
1656 + parser.getName());
1657 XmlUtils.skipCurrentTag(parser);
1658 }
1659 }
1660 }
1661
1662 void writeState() {
1663 synchronized (mFile) {
1664 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
1665
1666 FileOutputStream stream;
1667 try {
1668 stream = mFile.startWrite();
1669 } catch (IOException e) {
1670 Slog.w(TAG, "Failed to write state: " + e);
1671 return;
1672 }
1673
1674 try {
1675 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001676 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001677 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001678 out.startTag(null, "app-ops");
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001679 out.attribute(null, "v", String.valueOf(CURRENT_VERSION));
Svet Ganov2af57082015-07-30 08:44:20 -07001680
1681 final int uidStateCount = mUidStates.size();
1682 for (int i = 0; i < uidStateCount; i++) {
1683 UidState uidState = mUidStates.valueAt(i);
1684 if (uidState.opModes != null && uidState.opModes.size() > 0) {
1685 out.startTag(null, "uid");
1686 out.attribute(null, "n", Integer.toString(uidState.uid));
1687 SparseIntArray uidOpModes = uidState.opModes;
1688 final int opCount = uidOpModes.size();
1689 for (int j = 0; j < opCount; j++) {
1690 final int op = uidOpModes.keyAt(j);
1691 final int mode = uidOpModes.valueAt(j);
1692 out.startTag(null, "op");
1693 out.attribute(null, "n", Integer.toString(op));
1694 out.attribute(null, "m", Integer.toString(mode));
1695 out.endTag(null, "op");
1696 }
1697 out.endTag(null, "uid");
1698 }
1699 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001700
1701 if (allOps != null) {
1702 String lastPkg = null;
1703 for (int i=0; i<allOps.size(); i++) {
1704 AppOpsManager.PackageOps pkg = allOps.get(i);
1705 if (!pkg.getPackageName().equals(lastPkg)) {
1706 if (lastPkg != null) {
1707 out.endTag(null, "pkg");
1708 }
1709 lastPkg = pkg.getPackageName();
1710 out.startTag(null, "pkg");
1711 out.attribute(null, "n", lastPkg);
1712 }
1713 out.startTag(null, "uid");
1714 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04001715 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001716 Ops ops = getOpsRawLocked(pkg.getUid(), pkg.getPackageName(), false);
Jason Monk1c7c3192014-06-26 12:52:18 -04001717 // Should always be present as the list of PackageOps is generated
1718 // from Ops.
1719 if (ops != null) {
1720 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
1721 } else {
1722 out.attribute(null, "p", Boolean.toString(false));
1723 }
1724 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001725 List<AppOpsManager.OpEntry> ops = pkg.getOps();
1726 for (int j=0; j<ops.size(); j++) {
1727 AppOpsManager.OpEntry op = ops.get(j);
1728 out.startTag(null, "op");
1729 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07001730 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001731 out.attribute(null, "m", Integer.toString(op.getMode()));
1732 }
1733 long time = op.getTime();
1734 if (time != 0) {
1735 out.attribute(null, "t", Long.toString(time));
1736 }
1737 time = op.getRejectTime();
1738 if (time != 0) {
1739 out.attribute(null, "r", Long.toString(time));
1740 }
1741 int dur = op.getDuration();
1742 if (dur != 0) {
1743 out.attribute(null, "d", Integer.toString(dur));
1744 }
Svet Ganov99b60432015-06-27 13:15:22 -07001745 int proxyUid = op.getProxyUid();
1746 if (proxyUid != -1) {
1747 out.attribute(null, "pu", Integer.toString(proxyUid));
1748 }
1749 String proxyPackageName = op.getProxyPackageName();
1750 if (proxyPackageName != null) {
1751 out.attribute(null, "pp", proxyPackageName);
1752 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001753 out.endTag(null, "op");
1754 }
1755 out.endTag(null, "uid");
1756 }
1757 if (lastPkg != null) {
1758 out.endTag(null, "pkg");
1759 }
1760 }
1761
1762 out.endTag(null, "app-ops");
1763 out.endDocument();
1764 mFile.finishWrite(stream);
1765 } catch (IOException e) {
1766 Slog.w(TAG, "Failed to write state, restoring backup.", e);
1767 mFile.failWrite(stream);
1768 }
1769 }
1770 }
1771
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001772 static class Shell extends ShellCommand {
1773 final IAppOpsService mInterface;
1774 final AppOpsService mInternal;
1775
1776 int userId = UserHandle.USER_SYSTEM;
1777 String packageName;
1778 String opStr;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001779 String modeStr;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001780 int op;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001781 int mode;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001782 int packageUid;
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001783 int nonpackageUid;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001784
1785 Shell(IAppOpsService iface, AppOpsService internal) {
1786 mInterface = iface;
1787 mInternal = internal;
1788 }
1789
1790 @Override
1791 public int onCommand(String cmd) {
1792 return onShellCommand(this, cmd);
1793 }
1794
1795 @Override
1796 public void onHelp() {
1797 PrintWriter pw = getOutPrintWriter();
1798 dumpCommandHelp(pw);
1799 }
1800
1801 private int strOpToOp(String op, PrintWriter err) {
1802 try {
1803 return AppOpsManager.strOpToOp(op);
1804 } catch (IllegalArgumentException e) {
1805 }
1806 try {
1807 return Integer.parseInt(op);
1808 } catch (NumberFormatException e) {
1809 }
1810 try {
1811 return AppOpsManager.strDebugOpToOp(op);
1812 } catch (IllegalArgumentException e) {
1813 err.println("Error: " + e.getMessage());
1814 return -1;
1815 }
1816 }
1817
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001818 int strModeToMode(String modeStr, PrintWriter err) {
1819 switch (modeStr) {
1820 case "allow":
1821 return AppOpsManager.MODE_ALLOWED;
1822 case "deny":
1823 return AppOpsManager.MODE_ERRORED;
1824 case "ignore":
1825 return AppOpsManager.MODE_IGNORED;
1826 case "default":
1827 return AppOpsManager.MODE_DEFAULT;
1828 }
1829 try {
1830 return Integer.parseInt(modeStr);
1831 } catch (NumberFormatException e) {
1832 }
1833 err.println("Error: Mode " + modeStr + " is not valid");
1834 return -1;
1835 }
1836
1837 int parseUserOpMode(int defMode, PrintWriter err) throws RemoteException {
1838 userId = UserHandle.USER_CURRENT;
1839 opStr = null;
1840 modeStr = null;
1841 for (String argument; (argument = getNextArg()) != null;) {
1842 if ("--user".equals(argument)) {
1843 userId = UserHandle.parseUserArg(getNextArgRequired());
1844 } else {
1845 if (opStr == null) {
1846 opStr = argument;
1847 } else if (modeStr == null) {
1848 modeStr = argument;
1849 break;
1850 }
1851 }
1852 }
1853 if (opStr == null) {
1854 err.println("Error: Operation not specified.");
1855 return -1;
1856 }
1857 op = strOpToOp(opStr, err);
1858 if (op < 0) {
1859 return -1;
1860 }
1861 if (modeStr != null) {
1862 if ((mode=strModeToMode(modeStr, err)) < 0) {
1863 return -1;
1864 }
1865 } else {
1866 mode = defMode;
1867 }
1868 return 0;
1869 }
1870
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001871 int parseUserPackageOp(boolean reqOp, PrintWriter err) throws RemoteException {
1872 userId = UserHandle.USER_CURRENT;
1873 packageName = null;
1874 opStr = null;
1875 for (String argument; (argument = getNextArg()) != null;) {
1876 if ("--user".equals(argument)) {
1877 userId = UserHandle.parseUserArg(getNextArgRequired());
1878 } else {
1879 if (packageName == null) {
1880 packageName = argument;
1881 } else if (opStr == null) {
1882 opStr = argument;
1883 break;
1884 }
1885 }
1886 }
1887 if (packageName == null) {
1888 err.println("Error: Package name not specified.");
1889 return -1;
1890 } else if (opStr == null && reqOp) {
1891 err.println("Error: Operation not specified.");
1892 return -1;
1893 }
1894 if (opStr != null) {
1895 op = strOpToOp(opStr, err);
1896 if (op < 0) {
1897 return -1;
1898 }
1899 } else {
1900 op = AppOpsManager.OP_NONE;
1901 }
1902 if (userId == UserHandle.USER_CURRENT) {
1903 userId = ActivityManager.getCurrentUser();
1904 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001905 nonpackageUid = -1;
1906 try {
1907 nonpackageUid = Integer.parseInt(packageName);
1908 } catch (NumberFormatException e) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001909 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001910 if (nonpackageUid == -1 && packageName.length() > 1 && packageName.charAt(0) == 'u'
1911 && packageName.indexOf('.') < 0) {
1912 int i = 1;
1913 while (i < packageName.length() && packageName.charAt(i) >= '0'
1914 && packageName.charAt(i) <= '9') {
1915 i++;
1916 }
1917 if (i > 1 && i < packageName.length()) {
1918 String userStr = packageName.substring(1, i);
1919 try {
1920 int user = Integer.parseInt(userStr);
1921 char type = packageName.charAt(i);
1922 i++;
1923 int startTypeVal = i;
1924 while (i < packageName.length() && packageName.charAt(i) >= '0'
1925 && packageName.charAt(i) <= '9') {
1926 i++;
1927 }
1928 if (i > startTypeVal) {
1929 String typeValStr = packageName.substring(startTypeVal, i);
1930 try {
1931 int typeVal = Integer.parseInt(typeValStr);
1932 if (type == 'a') {
1933 nonpackageUid = UserHandle.getUid(user,
1934 typeVal + Process.FIRST_APPLICATION_UID);
1935 } else if (type == 's') {
1936 nonpackageUid = UserHandle.getUid(user, typeVal);
1937 }
1938 } catch (NumberFormatException e) {
1939 }
1940 }
1941 } catch (NumberFormatException e) {
1942 }
1943 }
1944 }
1945 if (nonpackageUid != -1) {
1946 packageName = null;
1947 } else {
1948 if ("root".equals(packageName)) {
1949 packageUid = 0;
1950 } else {
1951 packageUid = AppGlobals.getPackageManager().getPackageUid(packageName,
1952 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
1953 }
1954 if (packageUid < 0) {
1955 err.println("Error: No UID for " + packageName + " in user " + userId);
1956 return -1;
1957 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001958 }
1959 return 0;
1960 }
1961 }
1962
1963 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07001964 FileDescriptor err, String[] args, ShellCallback callback,
1965 ResultReceiver resultReceiver) {
1966 (new Shell(this, this)).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001967 }
1968
1969 static void dumpCommandHelp(PrintWriter pw) {
1970 pw.println("AppOps service (appops) commands:");
1971 pw.println(" help");
1972 pw.println(" Print this help text.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001973 pw.println(" set [--user <USER_ID>] <PACKAGE | UID> <OP> <MODE>");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001974 pw.println(" Set the mode for a particular application and operation.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001975 pw.println(" get [--user <USER_ID>] <PACKAGE | UID> [<OP>]");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001976 pw.println(" Return the mode for a particular application and optional operation.");
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001977 pw.println(" query-op [--user <USER_ID>] <OP> [<MODE>]");
1978 pw.println(" Print all packages that currently have the given op in the given mode.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001979 pw.println(" reset [--user <USER_ID>] [<PACKAGE>]");
1980 pw.println(" Reset the given application or all applications to default modes.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001981 pw.println(" write-settings");
1982 pw.println(" Immediately write pending changes to storage.");
1983 pw.println(" read-settings");
1984 pw.println(" Read the last written settings, replacing current state in RAM.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001985 pw.println(" options:");
1986 pw.println(" <PACKAGE> an Android package name.");
1987 pw.println(" <OP> an AppOps operation.");
1988 pw.println(" <MODE> one of allow, ignore, deny, or default");
1989 pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
1990 pw.println(" specified, the current user is assumed.");
1991 }
1992
1993 static int onShellCommand(Shell shell, String cmd) {
1994 if (cmd == null) {
1995 return shell.handleDefaultCommands(cmd);
1996 }
1997 PrintWriter pw = shell.getOutPrintWriter();
1998 PrintWriter err = shell.getErrPrintWriter();
1999 try {
2000 switch (cmd) {
2001 case "set": {
2002 int res = shell.parseUserPackageOp(true, err);
2003 if (res < 0) {
2004 return res;
2005 }
2006 String modeStr = shell.getNextArg();
2007 if (modeStr == null) {
2008 err.println("Error: Mode not specified.");
2009 return -1;
2010 }
2011
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002012 final int mode = shell.strModeToMode(modeStr, err);
2013 if (mode < 0) {
2014 return -1;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002015 }
2016
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002017 if (shell.packageName != null) {
2018 shell.mInterface.setMode(shell.op, shell.packageUid, shell.packageName,
2019 mode);
2020 } else {
2021 shell.mInterface.setUidMode(shell.op, shell.nonpackageUid, mode);
2022 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002023 return 0;
2024 }
2025 case "get": {
2026 int res = shell.parseUserPackageOp(false, err);
2027 if (res < 0) {
2028 return res;
2029 }
2030
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002031 List<AppOpsManager.PackageOps> ops;
2032 if (shell.packageName != null) {
2033 ops = shell.mInterface.getOpsForPackage(
2034 shell.packageUid, shell.packageName,
2035 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
2036 } else {
2037 ops = shell.mInterface.getUidOps(
2038 shell.nonpackageUid,
2039 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
2040 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002041 if (ops == null || ops.size() <= 0) {
2042 pw.println("No operations.");
2043 return 0;
2044 }
2045 final long now = System.currentTimeMillis();
2046 for (int i=0; i<ops.size(); i++) {
2047 List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
2048 for (int j=0; j<entries.size(); j++) {
2049 AppOpsManager.OpEntry ent = entries.get(j);
2050 pw.print(AppOpsManager.opToName(ent.getOp()));
2051 pw.print(": ");
2052 switch (ent.getMode()) {
2053 case AppOpsManager.MODE_ALLOWED:
2054 pw.print("allow");
2055 break;
2056 case AppOpsManager.MODE_IGNORED:
2057 pw.print("ignore");
2058 break;
2059 case AppOpsManager.MODE_ERRORED:
2060 pw.print("deny");
2061 break;
2062 case AppOpsManager.MODE_DEFAULT:
2063 pw.print("default");
2064 break;
2065 default:
2066 pw.print("mode=");
2067 pw.print(ent.getMode());
2068 break;
2069 }
2070 if (ent.getTime() != 0) {
2071 pw.print("; time=");
2072 TimeUtils.formatDuration(now - ent.getTime(), pw);
2073 pw.print(" ago");
2074 }
2075 if (ent.getRejectTime() != 0) {
2076 pw.print("; rejectTime=");
2077 TimeUtils.formatDuration(now - ent.getRejectTime(), pw);
2078 pw.print(" ago");
2079 }
2080 if (ent.getDuration() == -1) {
2081 pw.print(" (running)");
2082 } else if (ent.getDuration() != 0) {
2083 pw.print("; duration=");
2084 TimeUtils.formatDuration(ent.getDuration(), pw);
2085 }
2086 pw.println();
2087 }
2088 }
2089 return 0;
2090 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002091 case "query-op": {
2092 int res = shell.parseUserOpMode(AppOpsManager.MODE_IGNORED, err);
2093 if (res < 0) {
2094 return res;
2095 }
2096 List<AppOpsManager.PackageOps> ops = shell.mInterface.getPackagesForOps(
2097 new int[] {shell.op});
2098 if (ops == null || ops.size() <= 0) {
2099 pw.println("No operations.");
2100 return 0;
2101 }
2102 for (int i=0; i<ops.size(); i++) {
2103 final AppOpsManager.PackageOps pkg = ops.get(i);
2104 boolean hasMatch = false;
2105 final List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
2106 for (int j=0; j<entries.size(); j++) {
2107 AppOpsManager.OpEntry ent = entries.get(j);
2108 if (ent.getOp() == shell.op && ent.getMode() == shell.mode) {
2109 hasMatch = true;
2110 break;
2111 }
2112 }
2113 if (hasMatch) {
2114 pw.println(pkg.getPackageName());
2115 }
2116 }
2117 return 0;
2118 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002119 case "reset": {
2120 String packageName = null;
2121 int userId = UserHandle.USER_CURRENT;
2122 for (String argument; (argument = shell.getNextArg()) != null;) {
2123 if ("--user".equals(argument)) {
2124 String userStr = shell.getNextArgRequired();
2125 userId = UserHandle.parseUserArg(userStr);
2126 } else {
2127 if (packageName == null) {
2128 packageName = argument;
2129 } else {
2130 err.println("Error: Unsupported argument: " + argument);
2131 return -1;
2132 }
2133 }
2134 }
2135
2136 if (userId == UserHandle.USER_CURRENT) {
2137 userId = ActivityManager.getCurrentUser();
2138 }
2139
2140 shell.mInterface.resetAllModes(userId, packageName);
2141 pw.print("Reset all modes for: ");
2142 if (userId == UserHandle.USER_ALL) {
2143 pw.print("all users");
2144 } else {
2145 pw.print("user "); pw.print(userId);
2146 }
2147 pw.print(", ");
2148 if (packageName == null) {
2149 pw.println("all packages");
2150 } else {
2151 pw.print("package "); pw.println(packageName);
2152 }
2153 return 0;
2154 }
2155 case "write-settings": {
2156 shell.mInternal.mContext.enforcePermission(
2157 android.Manifest.permission.UPDATE_APP_OPS_STATS,
2158 Binder.getCallingPid(), Binder.getCallingUid(), null);
2159 long token = Binder.clearCallingIdentity();
2160 try {
2161 synchronized (shell.mInternal) {
2162 shell.mInternal.mHandler.removeCallbacks(shell.mInternal.mWriteRunner);
2163 }
2164 shell.mInternal.writeState();
2165 pw.println("Current settings written.");
2166 } finally {
2167 Binder.restoreCallingIdentity(token);
2168 }
2169 return 0;
2170 }
2171 case "read-settings": {
2172 shell.mInternal.mContext.enforcePermission(
2173 android.Manifest.permission.UPDATE_APP_OPS_STATS,
2174 Binder.getCallingPid(), Binder.getCallingUid(), null);
2175 long token = Binder.clearCallingIdentity();
2176 try {
2177 shell.mInternal.readState();
2178 pw.println("Last settings read.");
2179 } finally {
2180 Binder.restoreCallingIdentity(token);
2181 }
2182 return 0;
2183 }
2184 default:
2185 return shell.handleDefaultCommands(cmd);
2186 }
2187 } catch (RemoteException e) {
2188 pw.println("Remote exception: " + e);
2189 }
2190 return -1;
2191 }
2192
2193 private void dumpHelp(PrintWriter pw) {
2194 pw.println("AppOps service (appops) dump options:");
2195 pw.println(" none");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002196 }
2197
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002198 @Override
2199 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002200 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002201
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002202 if (args != null) {
2203 for (int i=0; i<args.length; i++) {
2204 String arg = args[i];
2205 if ("-h".equals(arg)) {
2206 dumpHelp(pw);
2207 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07002208 } else if ("-a".equals(arg)) {
2209 // dump all data
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002210 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
2211 pw.println("Unknown option: " + arg);
2212 return;
2213 } else {
2214 pw.println("Unknown command: " + arg);
2215 return;
2216 }
2217 }
2218 }
2219
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002220 synchronized (this) {
2221 pw.println("Current AppOps Service state:");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002222 final long now = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002223 boolean needSep = false;
2224 if (mOpModeWatchers.size() > 0) {
2225 needSep = true;
2226 pw.println(" Op mode watchers:");
2227 for (int i=0; i<mOpModeWatchers.size(); i++) {
2228 pw.print(" Op "); pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
2229 pw.println(":");
Dianne Hackborn68d76552017-02-27 15:32:03 -08002230 ArraySet<Callback> callbacks = mOpModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002231 for (int j=0; j<callbacks.size(); j++) {
2232 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08002233 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002234 }
2235 }
2236 }
2237 if (mPackageModeWatchers.size() > 0) {
2238 needSep = true;
2239 pw.println(" Package mode watchers:");
2240 for (int i=0; i<mPackageModeWatchers.size(); i++) {
2241 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
2242 pw.println(":");
Dianne Hackborn68d76552017-02-27 15:32:03 -08002243 ArraySet<Callback> callbacks = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002244 for (int j=0; j<callbacks.size(); j++) {
2245 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08002246 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002247 }
2248 }
2249 }
2250 if (mModeWatchers.size() > 0) {
2251 needSep = true;
2252 pw.println(" All mode watchers:");
2253 for (int i=0; i<mModeWatchers.size(); i++) {
2254 pw.print(" "); pw.print(mModeWatchers.keyAt(i));
2255 pw.print(" -> "); pw.println(mModeWatchers.valueAt(i));
2256 }
2257 }
2258 if (mClients.size() > 0) {
2259 needSep = true;
2260 pw.println(" Clients:");
2261 for (int i=0; i<mClients.size(); i++) {
2262 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
2263 ClientState cs = mClients.valueAt(i);
2264 pw.print(" "); pw.println(cs);
2265 if (cs.mStartedOps != null && cs.mStartedOps.size() > 0) {
2266 pw.println(" Started ops:");
2267 for (int j=0; j<cs.mStartedOps.size(); j++) {
2268 Op op = cs.mStartedOps.get(j);
2269 pw.print(" "); pw.print("uid="); pw.print(op.uid);
2270 pw.print(" pkg="); pw.print(op.packageName);
2271 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
2272 }
2273 }
2274 }
2275 }
John Spurlock1af30c72014-03-10 08:33:35 -04002276 if (mAudioRestrictions.size() > 0) {
2277 boolean printedHeader = false;
2278 for (int o=0; o<mAudioRestrictions.size(); o++) {
2279 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
2280 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
2281 for (int i=0; i<restrictions.size(); i++) {
2282 if (!printedHeader){
2283 pw.println(" Audio Restrictions:");
2284 printedHeader = true;
2285 needSep = true;
2286 }
John Spurlock7b414672014-07-18 13:02:39 -04002287 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04002288 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04002289 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04002290 Restriction r = restrictions.valueAt(i);
2291 pw.print(": mode="); pw.println(r.mode);
2292 if (!r.exceptionPackages.isEmpty()) {
2293 pw.println(" Exceptions:");
2294 for (int j=0; j<r.exceptionPackages.size(); j++) {
2295 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
2296 }
2297 }
2298 }
2299 }
2300 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002301 if (needSep) {
2302 pw.println();
2303 }
Svet Ganov2af57082015-07-30 08:44:20 -07002304 for (int i=0; i<mUidStates.size(); i++) {
2305 UidState uidState = mUidStates.valueAt(i);
2306
2307 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
Svet Ganovee438d42017-01-19 18:04:38 -08002308 needSep = true;
Svet Ganov2af57082015-07-30 08:44:20 -07002309
2310 SparseIntArray opModes = uidState.opModes;
2311 if (opModes != null) {
2312 final int opModeCount = opModes.size();
2313 for (int j = 0; j < opModeCount; j++) {
2314 final int code = opModes.keyAt(j);
2315 final int mode = opModes.valueAt(j);
2316 pw.print(" "); pw.print(AppOpsManager.opToName(code));
2317 pw.print(": mode="); pw.println(mode);
2318 }
2319 }
2320
2321 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
2322 if (pkgOps == null) {
2323 continue;
2324 }
2325
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002326 for (Ops ops : pkgOps.values()) {
2327 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
2328 for (int j=0; j<ops.size(); j++) {
2329 Op op = ops.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002330 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
2331 pw.print(": mode="); pw.print(op.mode);
2332 if (op.time != 0) {
2333 pw.print("; time="); TimeUtils.formatDuration(now-op.time, pw);
2334 pw.print(" ago");
2335 }
2336 if (op.rejectTime != 0) {
2337 pw.print("; rejectTime="); TimeUtils.formatDuration(now-op.rejectTime, pw);
2338 pw.print(" ago");
2339 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002340 if (op.duration == -1) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002341 pw.print(" (running)");
2342 } else if (op.duration != 0) {
2343 pw.print("; duration="); TimeUtils.formatDuration(op.duration, pw);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002344 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002345 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002346 }
2347 }
2348 }
Svet Ganovee438d42017-01-19 18:04:38 -08002349 if (needSep) {
2350 pw.println();
2351 }
2352
2353 final int userRestrictionCount = mOpUserRestrictions.size();
2354 for (int i = 0; i < userRestrictionCount; i++) {
2355 IBinder token = mOpUserRestrictions.keyAt(i);
2356 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
2357 pw.println(" User restrictions for token " + token + ":");
2358
2359 final int restrictionCount = restrictionState.perUserRestrictions != null
2360 ? restrictionState.perUserRestrictions.size() : 0;
2361 if (restrictionCount > 0) {
2362 pw.println(" Restricted ops:");
2363 for (int j = 0; j < restrictionCount; j++) {
2364 int userId = restrictionState.perUserRestrictions.keyAt(j);
2365 boolean[] restrictedOps = restrictionState.perUserRestrictions.valueAt(j);
2366 if (restrictedOps == null) {
2367 continue;
2368 }
2369 StringBuilder restrictedOpsValue = new StringBuilder();
2370 restrictedOpsValue.append("[");
2371 final int restrictedOpCount = restrictedOps.length;
2372 for (int k = 0; k < restrictedOpCount; k++) {
2373 if (restrictedOps[k]) {
2374 if (restrictedOpsValue.length() > 1) {
2375 restrictedOpsValue.append(", ");
2376 }
2377 restrictedOpsValue.append(AppOpsManager.opToName(k));
2378 }
2379 }
2380 restrictedOpsValue.append("]");
2381 pw.print(" "); pw.print("user: "); pw.print(userId);
2382 pw.print(" restricted ops: "); pw.println(restrictedOpsValue);
2383 }
2384 }
2385
2386 final int excludedPackageCount = restrictionState.perUserExcludedPackages != null
2387 ? restrictionState.perUserExcludedPackages.size() : 0;
2388 if (excludedPackageCount > 0) {
2389 pw.println(" Excluded packages:");
2390 for (int j = 0; j < excludedPackageCount; j++) {
2391 int userId = restrictionState.perUserExcludedPackages.keyAt(j);
2392 String[] packageNames = restrictionState.perUserExcludedPackages.valueAt(j);
2393 pw.print(" "); pw.print("user: "); pw.print(userId);
2394 pw.print(" packages: "); pw.println(Arrays.toString(packageNames));
2395 }
2396 }
2397 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002398 }
2399 }
John Spurlock1af30c72014-03-10 08:33:35 -04002400
2401 private static final class Restriction {
2402 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
2403 int mode;
2404 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
2405 }
Jason Monk62062992014-05-06 09:55:28 -04002406
2407 @Override
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002408 public void setUserRestrictions(Bundle restrictions, IBinder token, int userHandle) {
Jason Monk62062992014-05-06 09:55:28 -04002409 checkSystemUid("setUserRestrictions");
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002410 Preconditions.checkNotNull(restrictions);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002411 Preconditions.checkNotNull(token);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002412 for (int i = 0; i < AppOpsManager._NUM_OP; i++) {
Jason Monk62062992014-05-06 09:55:28 -04002413 String restriction = AppOpsManager.opToRestriction(i);
Suprabh Shukla64e0dcb2016-05-24 16:23:11 -07002414 if (restriction != null) {
2415 setUserRestrictionNoCheck(i, restrictions.getBoolean(restriction, false), token,
2416 userHandle, null);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002417 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002418 }
2419 }
2420
2421 @Override
Ruben Brunk29931bc2016-03-11 00:24:26 -08002422 public void setUserRestriction(int code, boolean restricted, IBinder token, int userHandle,
2423 String[] exceptionPackages) {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002424 if (Binder.getCallingPid() != Process.myPid()) {
2425 mContext.enforcePermission(Manifest.permission.MANAGE_APP_OPS_RESTRICTIONS,
2426 Binder.getCallingPid(), Binder.getCallingUid(), null);
2427 }
2428 if (userHandle != UserHandle.getCallingUserId()) {
2429 if (mContext.checkCallingOrSelfPermission(Manifest.permission
2430 .INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
2431 && mContext.checkCallingOrSelfPermission(Manifest.permission
2432 .INTERACT_ACROSS_USERS) != PackageManager.PERMISSION_GRANTED) {
2433 throw new SecurityException("Need INTERACT_ACROSS_USERS_FULL or"
2434 + " INTERACT_ACROSS_USERS to interact cross user ");
Jason Monk62062992014-05-06 09:55:28 -04002435 }
2436 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002437 verifyIncomingOp(code);
2438 Preconditions.checkNotNull(token);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002439 setUserRestrictionNoCheck(code, restricted, token, userHandle, exceptionPackages);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002440 }
2441
2442 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
Ruben Brunk29931bc2016-03-11 00:24:26 -08002443 int userHandle, String[] exceptionPackages) {
Svet Ganov442ed572016-08-17 17:29:43 -07002444 boolean notifyChange = false;
Ruben Brunk29931bc2016-03-11 00:24:26 -08002445
Svet Ganov442ed572016-08-17 17:29:43 -07002446 synchronized (AppOpsService.this) {
2447 ClientRestrictionState restrictionState = mOpUserRestrictions.get(token);
2448
2449 if (restrictionState == null) {
2450 try {
2451 restrictionState = new ClientRestrictionState(token);
2452 } catch (RemoteException e) {
2453 return;
2454 }
2455 mOpUserRestrictions.put(token, restrictionState);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002456 }
Svet Ganov442ed572016-08-17 17:29:43 -07002457
2458 if (restrictionState.setRestriction(code, restricted, exceptionPackages, userHandle)) {
2459 notifyChange = true;
2460 }
2461
2462 if (restrictionState.isDefault()) {
2463 mOpUserRestrictions.remove(token);
2464 restrictionState.destroy();
2465 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002466 }
2467
Svet Ganov442ed572016-08-17 17:29:43 -07002468 if (notifyChange) {
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002469 notifyWatchersOfChange(code);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002470 }
Julia Reynoldsbb21c252016-04-05 16:01:49 -04002471 }
2472
2473 private void notifyWatchersOfChange(int code) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08002474 final ArraySet<Callback> clonedCallbacks;
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002475 synchronized (this) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08002476 ArraySet<Callback> callbacks = mOpModeWatchers.get(code);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002477 if (callbacks == null) {
2478 return;
2479 }
Dianne Hackborn68d76552017-02-27 15:32:03 -08002480 clonedCallbacks = new ArraySet<>(callbacks);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002481 }
2482
2483 // There are components watching for mode changes such as window manager
2484 // and location manager which are in our process. The callbacks in these
Dianne Hackborn68d76552017-02-27 15:32:03 -08002485 // components may require permissions our remote caller does not have.
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002486 final long identity = Binder.clearCallingIdentity();
2487 try {
2488 final int callbackCount = clonedCallbacks.size();
2489 for (int i = 0; i < callbackCount; i++) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08002490 Callback callback = clonedCallbacks.valueAt(i);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002491 try {
2492 callback.mCallback.opChanged(code, -1, null);
2493 } catch (RemoteException e) {
2494 Log.w(TAG, "Error dispatching op op change", e);
2495 }
2496 }
2497 } finally {
2498 Binder.restoreCallingIdentity(identity);
2499 }
Jason Monk62062992014-05-06 09:55:28 -04002500 }
2501
2502 @Override
2503 public void removeUser(int userHandle) throws RemoteException {
2504 checkSystemUid("removeUser");
Svet Ganov442ed572016-08-17 17:29:43 -07002505 synchronized (AppOpsService.this) {
2506 final int tokenCount = mOpUserRestrictions.size();
2507 for (int i = tokenCount - 1; i >= 0; i--) {
2508 ClientRestrictionState opRestrictions = mOpUserRestrictions.valueAt(i);
2509 opRestrictions.removeUser(userHandle);
2510 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002511 removeUidsForUserLocked(userHandle);
2512 }
2513 }
2514
Jeff Sharkey35e46d22017-06-09 10:01:20 -06002515 @Override
2516 public boolean isOperationActive(int code, int uid, String packageName) {
2517 verifyIncomingUid(uid);
2518 verifyIncomingOp(code);
2519 String resolvedPackageName = resolvePackageName(uid, packageName);
2520 if (resolvedPackageName == null) {
2521 return false;
2522 }
2523 synchronized (this) {
2524 for (int i = mClients.size() - 1; i >= 0; i--) {
2525 final ClientState client = mClients.valueAt(i);
2526 if (client.mStartedOps == null) continue;
2527
2528 for (int j = client.mStartedOps.size() - 1; j >= 0; j--) {
2529 final Op op = client.mStartedOps.get(j);
2530 if (op.op == code && op.uid == uid) return true;
2531 }
2532 }
2533 }
2534 return false;
2535 }
2536
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002537 private void removeUidsForUserLocked(int userHandle) {
2538 for (int i = mUidStates.size() - 1; i >= 0; --i) {
2539 final int uid = mUidStates.keyAt(i);
2540 if (UserHandle.getUserId(uid) == userHandle) {
2541 mUidStates.removeAt(i);
2542 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002543 }
2544 }
2545
Jason Monk62062992014-05-06 09:55:28 -04002546 private void checkSystemUid(String function) {
2547 int uid = Binder.getCallingUid();
2548 if (uid != Process.SYSTEM_UID) {
2549 throw new SecurityException(function + " must by called by the system");
2550 }
2551 }
2552
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002553 private static String resolvePackageName(int uid, String packageName) {
2554 if (uid == 0) {
2555 return "root";
2556 } else if (uid == Process.SHELL_UID) {
2557 return "com.android.shell";
2558 } else if (uid == Process.SYSTEM_UID && packageName == null) {
2559 return "android";
2560 }
2561 return packageName;
2562 }
2563
Svet Ganov2af57082015-07-30 08:44:20 -07002564 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07002565 String[] packageNames = null;
Svet Ganov2af57082015-07-30 08:44:20 -07002566 try {
riddle_hsu40b300f2015-11-23 13:22:03 +08002567 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -07002568 } catch (RemoteException e) {
2569 /* ignore - local call */
2570 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07002571 if (packageNames == null) {
2572 return EmptyArray.STRING;
2573 }
2574 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07002575 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002576
2577 private final class ClientRestrictionState implements DeathRecipient {
2578 private final IBinder token;
2579 SparseArray<boolean[]> perUserRestrictions;
2580 SparseArray<String[]> perUserExcludedPackages;
2581
2582 public ClientRestrictionState(IBinder token)
2583 throws RemoteException {
2584 token.linkToDeath(this, 0);
2585 this.token = token;
2586 }
2587
2588 public boolean setRestriction(int code, boolean restricted,
2589 String[] excludedPackages, int userId) {
2590 boolean changed = false;
2591
2592 if (perUserRestrictions == null && restricted) {
2593 perUserRestrictions = new SparseArray<>();
2594 }
2595
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002596 int[] users;
2597 if (userId == UserHandle.USER_ALL) {
2598 List<UserInfo> liveUsers = UserManager.get(mContext).getUsers(false);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002599
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002600 users = new int[liveUsers.size()];
2601 for (int i = 0; i < liveUsers.size(); i++) {
2602 users[i] = liveUsers.get(i).id;
2603 }
2604 } else {
2605 users = new int[]{userId};
2606 }
2607
2608 if (perUserRestrictions != null) {
2609 int numUsers = users.length;
2610
2611 for (int i = 0; i < numUsers; i++) {
2612 int thisUserId = users[i];
2613
2614 boolean[] userRestrictions = perUserRestrictions.get(thisUserId);
2615 if (userRestrictions == null && restricted) {
2616 userRestrictions = new boolean[AppOpsManager._NUM_OP];
2617 perUserRestrictions.put(thisUserId, userRestrictions);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002618 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002619 if (userRestrictions != null && userRestrictions[code] != restricted) {
2620 userRestrictions[code] = restricted;
2621 if (!restricted && isDefault(userRestrictions)) {
2622 perUserRestrictions.remove(thisUserId);
2623 userRestrictions = null;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002624 }
2625 changed = true;
2626 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07002627
2628 if (userRestrictions != null) {
2629 final boolean noExcludedPackages = ArrayUtils.isEmpty(excludedPackages);
2630 if (perUserExcludedPackages == null && !noExcludedPackages) {
2631 perUserExcludedPackages = new SparseArray<>();
2632 }
2633 if (perUserExcludedPackages != null && !Arrays.equals(excludedPackages,
2634 perUserExcludedPackages.get(thisUserId))) {
2635 if (noExcludedPackages) {
2636 perUserExcludedPackages.remove(thisUserId);
2637 if (perUserExcludedPackages.size() <= 0) {
2638 perUserExcludedPackages = null;
2639 }
2640 } else {
2641 perUserExcludedPackages.put(thisUserId, excludedPackages);
2642 }
2643 changed = true;
2644 }
2645 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002646 }
2647 }
2648
2649 return changed;
2650 }
2651
2652 public boolean hasRestriction(int restriction, String packageName, int userId) {
2653 if (perUserRestrictions == null) {
2654 return false;
2655 }
2656 boolean[] restrictions = perUserRestrictions.get(userId);
2657 if (restrictions == null) {
2658 return false;
2659 }
2660 if (!restrictions[restriction]) {
2661 return false;
2662 }
2663 if (perUserExcludedPackages == null) {
2664 return true;
2665 }
2666 String[] perUserExclusions = perUserExcludedPackages.get(userId);
2667 if (perUserExclusions == null) {
2668 return true;
2669 }
2670 return !ArrayUtils.contains(perUserExclusions, packageName);
2671 }
2672
2673 public void removeUser(int userId) {
2674 if (perUserExcludedPackages != null) {
2675 perUserExcludedPackages.remove(userId);
2676 if (perUserExcludedPackages.size() <= 0) {
2677 perUserExcludedPackages = null;
2678 }
2679 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07002680 if (perUserRestrictions != null) {
2681 perUserRestrictions.remove(userId);
2682 if (perUserRestrictions.size() <= 0) {
2683 perUserRestrictions = null;
2684 }
2685 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002686 }
2687
2688 public boolean isDefault() {
2689 return perUserRestrictions == null || perUserRestrictions.size() <= 0;
2690 }
2691
2692 @Override
2693 public void binderDied() {
2694 synchronized (AppOpsService.this) {
2695 mOpUserRestrictions.remove(token);
2696 if (perUserRestrictions == null) {
2697 return;
2698 }
2699 final int userCount = perUserRestrictions.size();
2700 for (int i = 0; i < userCount; i++) {
2701 final boolean[] restrictions = perUserRestrictions.valueAt(i);
2702 final int restrictionCount = restrictions.length;
2703 for (int j = 0; j < restrictionCount; j++) {
2704 if (restrictions[j]) {
2705 final int changedCode = j;
2706 mHandler.post(() -> notifyWatchersOfChange(changedCode));
2707 }
2708 }
2709 }
2710 destroy();
2711 }
2712 }
2713
2714 public void destroy() {
2715 token.unlinkToDeath(this, 0);
2716 }
2717
2718 private boolean isDefault(boolean[] array) {
2719 if (ArrayUtils.isEmpty(array)) {
2720 return true;
2721 }
2722 for (boolean value : array) {
2723 if (value) {
2724 return false;
2725 }
2726 }
2727 return true;
2728 }
2729 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002730}