blob: b5a72fafb064239125f84ebfdc3baf1b49fa67da [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
19import java.io.File;
20import java.io.FileDescriptor;
Dianne Hackborn35654b62013-01-14 17:38:02 -080021import java.io.FileInputStream;
22import java.io.FileNotFoundException;
23import java.io.FileOutputStream;
24import java.io.IOException;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080025import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010026import java.nio.charset.StandardCharsets;
Dianne Hackborn35654b62013-01-14 17:38:02 -080027import java.util.ArrayList;
Svetoslav215b44a2015-08-04 19:03:40 -070028import java.util.Collections;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080029import java.util.HashMap;
Dianne Hackbornc2293022013-02-06 23:14:49 -080030import java.util.Iterator;
Dianne Hackborn35654b62013-01-14 17:38:02 -080031import java.util.List;
Dianne Hackborn607b4142013-08-02 18:10:10 -070032import java.util.Map;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080033
Svet Ganov9cea80cd2016-02-16 11:47:00 -080034import android.Manifest;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -080035import android.app.ActivityManager;
Jason Monk1c7c3192014-06-26 12:52:18 -040036import android.app.ActivityThread;
Svet Ganov2af57082015-07-30 08:44:20 -070037import android.app.AppGlobals;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080038import android.app.AppOpsManager;
39import android.content.Context;
Jason Monk1c7c3192014-06-26 12:52:18 -040040import android.content.pm.ApplicationInfo;
41import android.content.pm.IPackageManager;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080042import android.content.pm.PackageManager;
John Spurlock7b414672014-07-18 13:02:39 -040043import android.media.AudioAttributes;
Dianne Hackborn35654b62013-01-14 17:38:02 -080044import android.os.AsyncTask;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080045import android.os.Binder;
Jason Monk62062992014-05-06 09:55:28 -040046import android.os.Bundle;
Dianne Hackborn35654b62013-01-14 17:38:02 -080047import android.os.Handler;
Dianne Hackbornc2293022013-02-06 23:14:49 -080048import android.os.IBinder;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080049import android.os.Process;
Dianne Hackbornc2293022013-02-06 23:14:49 -080050import android.os.RemoteException;
Dianne Hackborn268e4e32015-11-18 16:29:56 -080051import android.os.ResultReceiver;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080052import android.os.ServiceManager;
Dianne Hackborn268e4e32015-11-18 16:29:56 -080053import android.os.ShellCommand;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080054import android.os.UserHandle;
Svet Ganov6ee871e2015-07-10 14:29:33 -070055import android.os.storage.MountServiceInternal;
Dianne Hackborne98f5db2013-07-17 17:23:25 -070056import android.util.ArrayMap;
John Spurlock1af30c72014-03-10 08:33:35 -040057import android.util.ArraySet;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080058import android.util.AtomicFile;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -080059import android.util.Log;
Ruben Brunk29931bc2016-03-11 00:24:26 -080060import android.util.Pair;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080061import android.util.Slog;
62import android.util.SparseArray;
Svet Ganov2af57082015-07-30 08:44:20 -070063import android.util.SparseIntArray;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080064import android.util.TimeUtils;
Dianne Hackborn35654b62013-01-14 17:38:02 -080065import android.util.Xml;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080066
67import com.android.internal.app.IAppOpsService;
Dianne Hackbornc2293022013-02-06 23:14:49 -080068import com.android.internal.app.IAppOpsCallback;
Svet Ganov6ee871e2015-07-10 14:29:33 -070069import com.android.internal.os.Zygote;
Svet Ganov2af57082015-07-30 08:44:20 -070070import com.android.internal.util.ArrayUtils;
Dianne Hackborn35654b62013-01-14 17:38:02 -080071import com.android.internal.util.FastXmlSerializer;
Svet Ganov9cea80cd2016-02-16 11:47:00 -080072import com.android.internal.util.Preconditions;
Dianne Hackborn35654b62013-01-14 17:38:02 -080073import com.android.internal.util.XmlUtils;
74
Svet Ganov2af57082015-07-30 08:44:20 -070075import libcore.util.EmptyArray;
Dianne Hackborn35654b62013-01-14 17:38:02 -080076import org.xmlpull.v1.XmlPullParser;
77import org.xmlpull.v1.XmlPullParserException;
78import org.xmlpull.v1.XmlSerializer;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080079
80public class AppOpsService extends IAppOpsService.Stub {
81 static final String TAG = "AppOps";
Dianne Hackborn35654b62013-01-14 17:38:02 -080082 static final boolean DEBUG = false;
83
84 // Write at most every 30 minutes.
85 static final long WRITE_DELAY = DEBUG ? 1000 : 30*60*1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080086
87 Context mContext;
88 final AtomicFile mFile;
Dianne Hackborn35654b62013-01-14 17:38:02 -080089 final Handler mHandler;
90
91 boolean mWriteScheduled;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -080092 boolean mFastWriteScheduled;
Dianne Hackborn35654b62013-01-14 17:38:02 -080093 final Runnable mWriteRunner = new Runnable() {
94 public void run() {
95 synchronized (AppOpsService.this) {
96 mWriteScheduled = false;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -080097 mFastWriteScheduled = false;
Dianne Hackborn35654b62013-01-14 17:38:02 -080098 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
99 @Override protected Void doInBackground(Void... params) {
100 writeState();
101 return null;
102 }
103 };
104 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
105 }
106 }
107 };
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800108
Svet Ganov9cea80cd2016-02-16 11:47:00 -0800109 private final SparseArray<UidState> mUidStates = new SparseArray<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800110
Ruben Brunk29931bc2016-03-11 00:24:26 -0800111 /*
112 * These are app op restrictions imposed per user from various parties.
113 *
114 * This is organized as follows:
115 *
116 * ArrayMap w/ mapping:
117 * IBinder (for client imposing restriction) --> SparseArray w/ mapping:
118 * User handle --> Pair containing:
119 * - Array w/ index = AppOp code, value = restricted status boolean
120 * - SparseArray w/ mapping:
121 * AppOp code --> Set of packages that are not restricted for this code
122 *
Ruben Brunk32f0fa42016-03-11 19:07:07 -0800123 * For efficiency, a core assumption here is that the number of per-package exemptions stored
124 * here will be relatively small. If this changes, this data structure should be revisited.
Ruben Brunk29931bc2016-03-11 00:24:26 -0800125 */
126 private final ArrayMap<IBinder, SparseArray<Pair<boolean[], SparseArray<ArraySet<String>>>>>
127 mOpUserRestrictions = new ArrayMap<>();
Jason Monk62062992014-05-06 09:55:28 -0400128
Svet Ganov2af57082015-07-30 08:44:20 -0700129 private static final class UidState {
130 public final int uid;
131 public ArrayMap<String, Ops> pkgOps;
132 public SparseIntArray opModes;
133
134 public UidState(int uid) {
135 this.uid = uid;
136 }
137
138 public void clear() {
139 pkgOps = null;
140 opModes = null;
141 }
142
143 public boolean isDefault() {
144 return (pkgOps == null || pkgOps.isEmpty())
145 && (opModes == null || opModes.size() <= 0);
146 }
147 }
148
Dianne Hackbornc2293022013-02-06 23:14:49 -0800149 public final static class Ops extends SparseArray<Op> {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800150 public final String packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700151 public final UidState uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400152 public final boolean isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800153
Svet Ganov2af57082015-07-30 08:44:20 -0700154 public Ops(String _packageName, UidState _uidState, boolean _isPrivileged) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800155 packageName = _packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700156 uidState = _uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400157 isPrivileged = _isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800158 }
159 }
160
Dianne Hackbornc2293022013-02-06 23:14:49 -0800161 public final static class Op {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700162 public final int uid;
163 public final String packageName;
Svet Ganov99b60432015-06-27 13:15:22 -0700164 public int proxyUid = -1;
165 public String proxyPackageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800166 public final int op;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800167 public int mode;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800168 public int duration;
169 public long time;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800170 public long rejectTime;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800171 public int nesting;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800172
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700173 public Op(int _uid, String _packageName, int _op) {
174 uid = _uid;
175 packageName = _packageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800176 op = _op;
David Braunf5d83192013-09-16 13:43:51 -0700177 mode = AppOpsManager.opToDefaultMode(op);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800178 }
179 }
180
Dianne Hackbornc2293022013-02-06 23:14:49 -0800181 final SparseArray<ArrayList<Callback>> mOpModeWatchers
182 = new SparseArray<ArrayList<Callback>>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700183 final ArrayMap<String, ArrayList<Callback>> mPackageModeWatchers
184 = new ArrayMap<String, ArrayList<Callback>>();
185 final ArrayMap<IBinder, Callback> mModeWatchers
186 = new ArrayMap<IBinder, Callback>();
John Spurlock1af30c72014-03-10 08:33:35 -0400187 final SparseArray<SparseArray<Restriction>> mAudioRestrictions
188 = new SparseArray<SparseArray<Restriction>>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800189
190 public final class Callback implements DeathRecipient {
191 final IAppOpsCallback mCallback;
192
193 public Callback(IAppOpsCallback callback) {
194 mCallback = callback;
195 try {
196 mCallback.asBinder().linkToDeath(this, 0);
197 } catch (RemoteException e) {
198 }
199 }
200
201 public void unlinkToDeath() {
202 mCallback.asBinder().unlinkToDeath(this, 0);
203 }
204
205 @Override
206 public void binderDied() {
207 stopWatchingMode(mCallback);
208 }
209 }
210
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700211 final ArrayMap<IBinder, ClientState> mClients = new ArrayMap<IBinder, ClientState>();
212
213 public final class ClientState extends Binder implements DeathRecipient {
214 final IBinder mAppToken;
215 final int mPid;
216 final ArrayList<Op> mStartedOps;
217
218 public ClientState(IBinder appToken) {
219 mAppToken = appToken;
220 mPid = Binder.getCallingPid();
221 if (appToken instanceof Binder) {
222 // For local clients, there is no reason to track them.
223 mStartedOps = null;
224 } else {
225 mStartedOps = new ArrayList<Op>();
226 try {
227 mAppToken.linkToDeath(this, 0);
228 } catch (RemoteException e) {
229 }
230 }
231 }
232
233 @Override
234 public String toString() {
235 return "ClientState{" +
236 "mAppToken=" + mAppToken +
237 ", " + (mStartedOps != null ? ("pid=" + mPid) : "local") +
238 '}';
239 }
240
241 @Override
242 public void binderDied() {
243 synchronized (AppOpsService.this) {
244 for (int i=mStartedOps.size()-1; i>=0; i--) {
245 finishOperationLocked(mStartedOps.get(i));
246 }
247 mClients.remove(mAppToken);
248 }
249 }
250 }
251
Jeff Brown6f357d32014-01-15 20:40:55 -0800252 public AppOpsService(File storagePath, Handler handler) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800253 mFile = new AtomicFile(storagePath);
Jeff Brown6f357d32014-01-15 20:40:55 -0800254 mHandler = handler;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800255 readState();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800256 }
David Braunf5d83192013-09-16 13:43:51 -0700257
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800258 public void publish(Context context) {
259 mContext = context;
260 ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
261 }
262
Dianne Hackborn514074f2013-02-11 10:52:46 -0800263 public void systemReady() {
264 synchronized (this) {
265 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700266 for (int i = mUidStates.size() - 1; i >= 0; i--) {
267 UidState uidState = mUidStates.valueAt(i);
268
269 String[] packageNames = getPackagesForUid(uidState.uid);
270 if (ArrayUtils.isEmpty(packageNames)) {
271 uidState.clear();
272 mUidStates.removeAt(i);
273 changed = true;
274 continue;
275 }
276
277 ArrayMap<String, Ops> pkgs = uidState.pkgOps;
278 if (pkgs == null) {
279 continue;
280 }
281
Dianne Hackborn514074f2013-02-11 10:52:46 -0800282 Iterator<Ops> it = pkgs.values().iterator();
283 while (it.hasNext()) {
284 Ops ops = it.next();
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700285 int curUid = -1;
Dianne Hackborn514074f2013-02-11 10:52:46 -0800286 try {
Jeff Sharkeycd654482016-01-08 17:42:11 -0700287 curUid = AppGlobals.getPackageManager().getPackageUid(ops.packageName,
288 PackageManager.MATCH_UNINSTALLED_PACKAGES,
Svet Ganov2af57082015-07-30 08:44:20 -0700289 UserHandle.getUserId(ops.uidState.uid));
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700290 } catch (RemoteException ignored) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800291 }
Svet Ganov2af57082015-07-30 08:44:20 -0700292 if (curUid != ops.uidState.uid) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800293 Slog.i(TAG, "Pruning old package " + ops.packageName
Svet Ganov2af57082015-07-30 08:44:20 -0700294 + "/" + ops.uidState + ": new uid=" + curUid);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800295 it.remove();
296 changed = true;
297 }
298 }
Svet Ganov2af57082015-07-30 08:44:20 -0700299
300 if (uidState.isDefault()) {
301 mUidStates.removeAt(i);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800302 }
303 }
304 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800305 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800306 }
307 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700308
309 MountServiceInternal mountServiceInternal = LocalServices.getService(
310 MountServiceInternal.class);
311 mountServiceInternal.addExternalStoragePolicy(
312 new MountServiceInternal.ExternalStorageMountPolicy() {
313 @Override
314 public int getMountMode(int uid, String packageName) {
315 if (Process.isIsolated(uid)) {
316 return Zygote.MOUNT_EXTERNAL_NONE;
317 }
318 if (noteOperation(AppOpsManager.OP_READ_EXTERNAL_STORAGE, uid,
319 packageName) != AppOpsManager.MODE_ALLOWED) {
320 return Zygote.MOUNT_EXTERNAL_NONE;
321 }
322 if (noteOperation(AppOpsManager.OP_WRITE_EXTERNAL_STORAGE, uid,
323 packageName) != AppOpsManager.MODE_ALLOWED) {
324 return Zygote.MOUNT_EXTERNAL_READ;
325 }
326 return Zygote.MOUNT_EXTERNAL_WRITE;
327 }
328
329 @Override
330 public boolean hasExternalStorage(int uid, String packageName) {
331 final int mountMode = getMountMode(uid, packageName);
332 return mountMode == Zygote.MOUNT_EXTERNAL_READ
333 || mountMode == Zygote.MOUNT_EXTERNAL_WRITE;
334 }
335 });
Dianne Hackborn514074f2013-02-11 10:52:46 -0800336 }
337
338 public void packageRemoved(int uid, String packageName) {
339 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700340 UidState uidState = mUidStates.get(uid);
341 if (uidState == null) {
342 return;
343 }
344
345 boolean changed = false;
346
347 // Remove any package state if such.
348 if (uidState.pkgOps != null && uidState.pkgOps.remove(packageName) != null) {
349 changed = true;
350 }
351
352 // If we just nuked the last package state check if the UID is valid.
353 if (changed && uidState.pkgOps.isEmpty()
354 && getPackagesForUid(uid).length <= 0) {
355 mUidStates.remove(uid);
356 }
357
358 if (changed) {
359 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800360 }
361 }
362 }
363
364 public void uidRemoved(int uid) {
365 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700366 if (mUidStates.indexOfKey(uid) >= 0) {
367 mUidStates.remove(uid);
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800368 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800369 }
370 }
371 }
372
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800373 public void shutdown() {
374 Slog.w(TAG, "Writing app ops before shutdown...");
Dianne Hackborn35654b62013-01-14 17:38:02 -0800375 boolean doWrite = false;
376 synchronized (this) {
377 if (mWriteScheduled) {
378 mWriteScheduled = false;
379 doWrite = true;
380 }
381 }
382 if (doWrite) {
383 writeState();
384 }
385 }
386
Dianne Hackborn72e39832013-01-18 18:36:09 -0800387 private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
388 ArrayList<AppOpsManager.OpEntry> resOps = null;
389 if (ops == null) {
390 resOps = new ArrayList<AppOpsManager.OpEntry>();
391 for (int j=0; j<pkgOps.size(); j++) {
392 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800393 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Svet Ganov99b60432015-06-27 13:15:22 -0700394 curOp.rejectTime, curOp.duration, curOp.proxyUid,
395 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800396 }
397 } else {
398 for (int j=0; j<ops.length; j++) {
399 Op curOp = pkgOps.get(ops[j]);
400 if (curOp != null) {
401 if (resOps == null) {
402 resOps = new ArrayList<AppOpsManager.OpEntry>();
403 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800404 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Svet Ganov99b60432015-06-27 13:15:22 -0700405 curOp.rejectTime, curOp.duration, curOp.proxyUid,
406 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800407 }
408 }
409 }
410 return resOps;
411 }
412
Dianne Hackborn35654b62013-01-14 17:38:02 -0800413 @Override
414 public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
415 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
416 Binder.getCallingPid(), Binder.getCallingUid(), null);
417 ArrayList<AppOpsManager.PackageOps> res = null;
418 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700419 final int uidStateCount = mUidStates.size();
420 for (int i = 0; i < uidStateCount; i++) {
421 UidState uidState = mUidStates.valueAt(i);
422 if (uidState.pkgOps == null || uidState.pkgOps.isEmpty()) {
423 continue;
424 }
425 ArrayMap<String, Ops> packages = uidState.pkgOps;
426 final int packageCount = packages.size();
427 for (int j = 0; j < packageCount; j++) {
428 Ops pkgOps = packages.valueAt(j);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800429 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800430 if (resOps != null) {
431 if (res == null) {
432 res = new ArrayList<AppOpsManager.PackageOps>();
433 }
434 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700435 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800436 res.add(resPackage);
437 }
438 }
439 }
440 }
441 return res;
442 }
443
444 @Override
Dianne Hackborn72e39832013-01-18 18:36:09 -0800445 public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
446 int[] ops) {
447 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
448 Binder.getCallingPid(), Binder.getCallingUid(), null);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000449 String resolvedPackageName = resolvePackageName(uid, packageName);
450 if (resolvedPackageName == null) {
451 return Collections.emptyList();
452 }
Dianne Hackborn72e39832013-01-18 18:36:09 -0800453 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000454 Ops pkgOps = getOpsRawLocked(uid, resolvedPackageName, false);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800455 if (pkgOps == null) {
456 return null;
457 }
458 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
459 if (resOps == null) {
460 return null;
461 }
462 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
463 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700464 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800465 res.add(resPackage);
466 return res;
467 }
468 }
469
Dianne Hackborn607b4142013-08-02 18:10:10 -0700470 private void pruneOp(Op op, int uid, String packageName) {
471 if (op.time == 0 && op.rejectTime == 0) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000472 Ops ops = getOpsRawLocked(uid, packageName, false);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700473 if (ops != null) {
474 ops.remove(op.op);
475 if (ops.size() <= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -0700476 UidState uidState = ops.uidState;
477 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700478 if (pkgOps != null) {
479 pkgOps.remove(ops.packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700480 if (pkgOps.isEmpty()) {
481 uidState.pkgOps = null;
482 }
483 if (uidState.isDefault()) {
484 mUidStates.remove(uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700485 }
486 }
487 }
488 }
489 }
490 }
491
Dianne Hackborn72e39832013-01-18 18:36:09 -0800492 @Override
Svet Ganov2af57082015-07-30 08:44:20 -0700493 public void setUidMode(int code, int uid, int mode) {
494 if (Binder.getCallingPid() != Process.myPid()) {
495 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
496 Binder.getCallingPid(), Binder.getCallingUid(), null);
497 }
498 verifyIncomingOp(code);
499 code = AppOpsManager.opToSwitch(code);
500
501 synchronized (this) {
502 final int defaultMode = AppOpsManager.opToDefaultMode(code);
503
504 UidState uidState = getUidStateLocked(uid, false);
505 if (uidState == null) {
506 if (mode == defaultMode) {
507 return;
508 }
509 uidState = new UidState(uid);
510 uidState.opModes = new SparseIntArray();
511 uidState.opModes.put(code, mode);
512 mUidStates.put(uid, uidState);
513 scheduleWriteLocked();
514 } else if (uidState.opModes == null) {
515 if (mode != defaultMode) {
516 uidState.opModes = new SparseIntArray();
517 uidState.opModes.put(code, mode);
518 scheduleWriteLocked();
519 }
520 } else {
521 if (uidState.opModes.get(code) == mode) {
522 return;
523 }
524 if (mode == defaultMode) {
525 uidState.opModes.delete(code);
526 if (uidState.opModes.size() <= 0) {
527 uidState.opModes = null;
528 }
529 } else {
530 uidState.opModes.put(code, mode);
531 }
532 scheduleWriteLocked();
533 }
534 }
535
Svetoslav215b44a2015-08-04 19:03:40 -0700536 String[] uidPackageNames = getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -0700537 ArrayMap<Callback, ArraySet<String>> callbackSpecs = null;
538
riddle_hsu40b300f2015-11-23 13:22:03 +0800539 synchronized (this) {
540 ArrayList<Callback> callbacks = mOpModeWatchers.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -0700541 if (callbacks != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700542 final int callbackCount = callbacks.size();
543 for (int i = 0; i < callbackCount; i++) {
544 Callback callback = callbacks.get(i);
riddle_hsu40b300f2015-11-23 13:22:03 +0800545 ArraySet<String> changedPackages = new ArraySet<>();
546 Collections.addAll(changedPackages, uidPackageNames);
547 callbackSpecs = new ArrayMap<>();
548 callbackSpecs.put(callback, changedPackages);
549 }
550 }
551
552 for (String uidPackageName : uidPackageNames) {
553 callbacks = mPackageModeWatchers.get(uidPackageName);
554 if (callbacks != null) {
555 if (callbackSpecs == null) {
556 callbackSpecs = new ArrayMap<>();
Svet Ganov2af57082015-07-30 08:44:20 -0700557 }
riddle_hsu40b300f2015-11-23 13:22:03 +0800558 final int callbackCount = callbacks.size();
559 for (int i = 0; i < callbackCount; i++) {
560 Callback callback = callbacks.get(i);
561 ArraySet<String> changedPackages = callbackSpecs.get(callback);
562 if (changedPackages == null) {
563 changedPackages = new ArraySet<>();
564 callbackSpecs.put(callback, changedPackages);
565 }
566 changedPackages.add(uidPackageName);
567 }
Svet Ganov2af57082015-07-30 08:44:20 -0700568 }
569 }
570 }
571
572 if (callbackSpecs == null) {
573 return;
574 }
575
576 // There are components watching for mode changes such as window manager
577 // and location manager which are in our process. The callbacks in these
578 // components may require permissions our remote caller does not have.
579 final long identity = Binder.clearCallingIdentity();
580 try {
581 for (int i = 0; i < callbackSpecs.size(); i++) {
582 Callback callback = callbackSpecs.keyAt(i);
583 ArraySet<String> reportedPackageNames = callbackSpecs.valueAt(i);
584 try {
585 if (reportedPackageNames == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700586 callback.mCallback.opChanged(code, uid, null);
Svet Ganov2af57082015-07-30 08:44:20 -0700587 } else {
588 final int reportedPackageCount = reportedPackageNames.size();
589 for (int j = 0; j < reportedPackageCount; j++) {
590 String reportedPackageName = reportedPackageNames.valueAt(j);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700591 callback.mCallback.opChanged(code, uid, reportedPackageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700592 }
593 }
594 } catch (RemoteException e) {
595 Log.w(TAG, "Error dispatching op op change", e);
596 }
597 }
598 } finally {
599 Binder.restoreCallingIdentity(identity);
600 }
601 }
602
603 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800604 public void setMode(int code, int uid, String packageName, int mode) {
Dianne Hackbornb64afe12014-07-22 16:29:04 -0700605 if (Binder.getCallingPid() != Process.myPid()) {
606 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
607 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborn133b9df2014-07-01 13:06:10 -0700608 }
Dianne Hackborn961321f2013-02-05 17:22:41 -0800609 verifyIncomingOp(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800610 ArrayList<Callback> repCbs = null;
611 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800612 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700613 UidState uidState = getUidStateLocked(uid, false);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800614 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800615 if (op != null) {
616 if (op.mode != mode) {
617 op.mode = mode;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800618 ArrayList<Callback> cbs = mOpModeWatchers.get(code);
619 if (cbs != null) {
620 if (repCbs == null) {
621 repCbs = new ArrayList<Callback>();
622 }
623 repCbs.addAll(cbs);
624 }
625 cbs = mPackageModeWatchers.get(packageName);
626 if (cbs != null) {
627 if (repCbs == null) {
628 repCbs = new ArrayList<Callback>();
629 }
630 repCbs.addAll(cbs);
631 }
David Braunf5d83192013-09-16 13:43:51 -0700632 if (mode == AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800633 // If going into the default mode, prune this op
634 // if there is nothing else interesting in it.
Dianne Hackborn607b4142013-08-02 18:10:10 -0700635 pruneOp(op, uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800636 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800637 scheduleFastWriteLocked();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800638 }
639 }
640 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800641 if (repCbs != null) {
Svet Ganov38536112015-05-19 12:45:52 -0700642 // There are components watching for mode changes such as window manager
643 // and location manager which are in our process. The callbacks in these
644 // components may require permissions our remote caller does not have.
645 final long identity = Binder.clearCallingIdentity();
646 try {
647 for (int i = 0; i < repCbs.size(); i++) {
648 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700649 repCbs.get(i).mCallback.opChanged(code, uid, packageName);
Svet Ganov38536112015-05-19 12:45:52 -0700650 } catch (RemoteException e) {
651 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800652 }
Svet Ganov38536112015-05-19 12:45:52 -0700653 } finally {
654 Binder.restoreCallingIdentity(identity);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800655 }
656 }
657 }
658
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700659 private static HashMap<Callback, ArrayList<ChangeRec>> addCallbacks(
660 HashMap<Callback, ArrayList<ChangeRec>> callbacks,
661 int op, int uid, String packageName, ArrayList<Callback> cbs) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700662 if (cbs == null) {
663 return callbacks;
664 }
665 if (callbacks == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700666 callbacks = new HashMap<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700667 }
Svet Ganov2af57082015-07-30 08:44:20 -0700668 boolean duplicate = false;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700669 for (int i=0; i<cbs.size(); i++) {
670 Callback cb = cbs.get(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700671 ArrayList<ChangeRec> reports = callbacks.get(cb);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700672 if (reports == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700673 reports = new ArrayList<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700674 callbacks.put(cb, reports);
Svet Ganov2af57082015-07-30 08:44:20 -0700675 } else {
676 final int reportCount = reports.size();
677 for (int j = 0; j < reportCount; j++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700678 ChangeRec report = reports.get(j);
679 if (report.op == op && report.pkg.equals(packageName)) {
Svet Ganov2af57082015-07-30 08:44:20 -0700680 duplicate = true;
681 break;
682 }
683 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700684 }
Svet Ganov2af57082015-07-30 08:44:20 -0700685 if (!duplicate) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700686 reports.add(new ChangeRec(op, uid, packageName));
Svet Ganov2af57082015-07-30 08:44:20 -0700687 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700688 }
689 return callbacks;
690 }
691
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700692 static final class ChangeRec {
693 final int op;
694 final int uid;
695 final String pkg;
696
697 ChangeRec(int _op, int _uid, String _pkg) {
698 op = _op;
699 uid = _uid;
700 pkg = _pkg;
701 }
702 }
703
Dianne Hackborn607b4142013-08-02 18:10:10 -0700704 @Override
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800705 public void resetAllModes(int reqUserId, String reqPackageName) {
706 final int callingPid = Binder.getCallingPid();
707 final int callingUid = Binder.getCallingUid();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700708 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800709 callingPid, callingUid, null);
710 reqUserId = ActivityManager.handleIncomingUser(callingPid, callingUid, reqUserId,
711 true, true, "resetAllModes", null);
Svet Ganov2af57082015-07-30 08:44:20 -0700712
713 int reqUid = -1;
714 if (reqPackageName != null) {
715 try {
716 reqUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -0700717 reqPackageName, PackageManager.MATCH_UNINSTALLED_PACKAGES, reqUserId);
Svet Ganov2af57082015-07-30 08:44:20 -0700718 } catch (RemoteException e) {
719 /* ignore - local call */
720 }
721 }
722
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700723 HashMap<Callback, ArrayList<ChangeRec>> callbacks = null;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700724 synchronized (this) {
725 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700726 for (int i = mUidStates.size() - 1; i >= 0; i--) {
727 UidState uidState = mUidStates.valueAt(i);
728
729 SparseIntArray opModes = uidState.opModes;
730 if (opModes != null && (uidState.uid == reqUid || reqUid == -1)) {
731 final int uidOpCount = opModes.size();
732 for (int j = uidOpCount - 1; j >= 0; j--) {
733 final int code = opModes.keyAt(j);
734 if (AppOpsManager.opAllowsReset(code)) {
735 opModes.removeAt(j);
736 if (opModes.size() <= 0) {
737 uidState.opModes = null;
738 }
739 for (String packageName : getPackagesForUid(uidState.uid)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700740 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700741 mOpModeWatchers.get(code));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700742 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700743 mPackageModeWatchers.get(packageName));
744 }
745 }
746 }
747 }
748
749 if (uidState.pkgOps == null) {
750 continue;
751 }
752
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800753 if (reqUserId != UserHandle.USER_ALL
Svet Ganov2af57082015-07-30 08:44:20 -0700754 && reqUserId != UserHandle.getUserId(uidState.uid)) {
Alexandra Gherghinad6a98972014-08-04 17:05:34 +0100755 // Skip any ops for a different user
756 continue;
757 }
Svet Ganov2af57082015-07-30 08:44:20 -0700758
759 Map<String, Ops> packages = uidState.pkgOps;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700760 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
761 while (it.hasNext()) {
762 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700763 String packageName = ent.getKey();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800764 if (reqPackageName != null && !reqPackageName.equals(packageName)) {
765 // Skip any ops for a different package
766 continue;
767 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700768 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700769 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700770 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -0700771 if (AppOpsManager.opAllowsReset(curOp.op)
772 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -0700773 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700774 changed = true;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700775 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -0700776 mOpModeWatchers.get(curOp.op));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700777 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -0700778 mPackageModeWatchers.get(packageName));
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700779 if (curOp.time == 0 && curOp.rejectTime == 0) {
780 pkgOps.removeAt(j);
781 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700782 }
783 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700784 if (pkgOps.size() == 0) {
785 it.remove();
786 }
787 }
Svet Ganov2af57082015-07-30 08:44:20 -0700788 if (uidState.isDefault()) {
789 mUidStates.remove(uidState.uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700790 }
791 }
Svet Ganov2af57082015-07-30 08:44:20 -0700792
Dianne Hackborn607b4142013-08-02 18:10:10 -0700793 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800794 scheduleFastWriteLocked();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700795 }
796 }
797 if (callbacks != null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700798 for (Map.Entry<Callback, ArrayList<ChangeRec>> ent : callbacks.entrySet()) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700799 Callback cb = ent.getKey();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700800 ArrayList<ChangeRec> reports = ent.getValue();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700801 for (int i=0; i<reports.size(); i++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700802 ChangeRec rep = reports.get(i);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700803 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700804 cb.mCallback.opChanged(rep.op, rep.uid, rep.pkg);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700805 } catch (RemoteException e) {
806 }
807 }
808 }
809 }
810 }
811
Dianne Hackbornc2293022013-02-06 23:14:49 -0800812 @Override
813 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -0800814 if (callback == null) {
815 return;
816 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800817 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700818 op = (op != AppOpsManager.OP_NONE) ? AppOpsManager.opToSwitch(op) : op;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800819 Callback cb = mModeWatchers.get(callback.asBinder());
820 if (cb == null) {
821 cb = new Callback(callback);
822 mModeWatchers.put(callback.asBinder(), cb);
823 }
824 if (op != AppOpsManager.OP_NONE) {
825 ArrayList<Callback> cbs = mOpModeWatchers.get(op);
826 if (cbs == null) {
827 cbs = new ArrayList<Callback>();
828 mOpModeWatchers.put(op, cbs);
829 }
830 cbs.add(cb);
831 }
832 if (packageName != null) {
833 ArrayList<Callback> cbs = mPackageModeWatchers.get(packageName);
834 if (cbs == null) {
835 cbs = new ArrayList<Callback>();
836 mPackageModeWatchers.put(packageName, cbs);
837 }
838 cbs.add(cb);
839 }
840 }
841 }
842
843 @Override
844 public void stopWatchingMode(IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -0800845 if (callback == null) {
846 return;
847 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800848 synchronized (this) {
849 Callback cb = mModeWatchers.remove(callback.asBinder());
850 if (cb != null) {
851 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700852 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800853 ArrayList<Callback> cbs = mOpModeWatchers.valueAt(i);
854 cbs.remove(cb);
855 if (cbs.size() <= 0) {
856 mOpModeWatchers.removeAt(i);
857 }
858 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700859 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
860 ArrayList<Callback> cbs = mPackageModeWatchers.valueAt(i);
861 cbs.remove(cb);
862 if (cbs.size() <= 0) {
863 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800864 }
865 }
866 }
867 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800868 }
869
870 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700871 public IBinder getToken(IBinder clientToken) {
872 synchronized (this) {
873 ClientState cs = mClients.get(clientToken);
874 if (cs == null) {
875 cs = new ClientState(clientToken);
876 mClients.put(clientToken, cs);
877 }
878 return cs;
879 }
880 }
881
882 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800883 public int checkOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800884 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800885 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000886 String resolvedPackageName = resolvePackageName(uid, packageName);
887 if (resolvedPackageName == null) {
888 return AppOpsManager.MODE_IGNORED;
889 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800890 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000891 if (isOpRestricted(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -0400892 return AppOpsManager.MODE_IGNORED;
893 }
Svet Ganov2af57082015-07-30 08:44:20 -0700894 code = AppOpsManager.opToSwitch(code);
895 UidState uidState = getUidStateLocked(uid, false);
896 if (uidState != null && uidState.opModes != null) {
897 final int uidMode = uidState.opModes.get(code);
898 if (uidMode != AppOpsManager.MODE_ALLOWED) {
899 return uidMode;
900 }
901 }
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000902 Op op = getOpLocked(code, uid, resolvedPackageName, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800903 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -0700904 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800905 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800906 return op.mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800907 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800908 }
909
910 @Override
John Spurlock7b414672014-07-18 13:02:39 -0400911 public int checkAudioOperation(int code, int usage, int uid, String packageName) {
Andrei Stingaceanuefc4a342016-03-22 14:43:01 +0000912 boolean suspended;
913 try {
914 suspended = isPackageSuspendedForUser(packageName, uid);
915 } catch (IllegalArgumentException ex) {
916 // Package not found.
917 suspended = false;
918 }
919
920 if (suspended) {
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000921 Log.i(TAG, "Audio disabled for suspended package=" + packageName + " for uid=" + uid);
922 return AppOpsManager.MODE_IGNORED;
923 }
924
John Spurlock1af30c72014-03-10 08:33:35 -0400925 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -0400926 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -0400927 if (mode != AppOpsManager.MODE_ALLOWED) {
928 return mode;
929 }
930 }
931 return checkOperation(code, uid, packageName);
932 }
933
Andrei Stingaceanu355b2322016-02-12 16:43:51 +0000934 private boolean isPackageSuspendedForUser(String pkg, int uid) {
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000935 try {
Andrei Stingaceanu355b2322016-02-12 16:43:51 +0000936 return AppGlobals.getPackageManager().isPackageSuspendedForUser(
937 pkg, UserHandle.getUserId(uid));
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000938 } catch (RemoteException re) {
939 throw new SecurityException("Could not talk to package manager service");
940 }
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +0000941 }
942
John Spurlock7b414672014-07-18 13:02:39 -0400943 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
944 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
945 if (usageRestrictions != null) {
946 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -0400947 if (r != null && !r.exceptionPackages.contains(packageName)) {
948 return r.mode;
949 }
950 }
951 return AppOpsManager.MODE_ALLOWED;
952 }
953
954 @Override
John Spurlock7b414672014-07-18 13:02:39 -0400955 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -0400956 String[] exceptionPackages) {
957 verifyIncomingUid(uid);
958 verifyIncomingOp(code);
959 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -0400960 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
961 if (usageRestrictions == null) {
962 usageRestrictions = new SparseArray<Restriction>();
963 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -0400964 }
John Spurlock7b414672014-07-18 13:02:39 -0400965 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -0400966 if (mode != AppOpsManager.MODE_ALLOWED) {
967 final Restriction r = new Restriction();
968 r.mode = mode;
969 if (exceptionPackages != null) {
970 final int N = exceptionPackages.length;
971 r.exceptionPackages = new ArraySet<String>(N);
972 for (int i = 0; i < N; i++) {
973 final String pkg = exceptionPackages[i];
974 if (pkg != null) {
975 r.exceptionPackages.add(pkg.trim());
976 }
977 }
978 }
John Spurlock7b414672014-07-18 13:02:39 -0400979 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -0400980 }
981 }
Julia Reynoldsbb21c252016-04-05 16:01:49 -0400982 notifyWatchersOfChange(code);
John Spurlock1af30c72014-03-10 08:33:35 -0400983 }
984
985 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700986 public int checkPackage(int uid, String packageName) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000987 Preconditions.checkNotNull(packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700988 synchronized (this) {
Dianne Hackborn0fcef842014-09-12 15:38:33 -0700989 if (getOpsRawLocked(uid, packageName, true) != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700990 return AppOpsManager.MODE_ALLOWED;
991 } else {
992 return AppOpsManager.MODE_ERRORED;
993 }
994 }
995 }
996
997 @Override
Svet Ganov99b60432015-06-27 13:15:22 -0700998 public int noteProxyOperation(int code, String proxyPackageName,
999 int proxiedUid, String proxiedPackageName) {
1000 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001001 final int proxyUid = Binder.getCallingUid();
1002 String resolveProxyPackageName = resolvePackageName(proxyUid, proxyPackageName);
1003 if (resolveProxyPackageName == null) {
1004 return AppOpsManager.MODE_IGNORED;
1005 }
1006 final int proxyMode = noteOperationUnchecked(code, proxyUid,
1007 resolveProxyPackageName, -1, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001008 if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
1009 return proxyMode;
1010 }
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001011 String resolveProxiedPackageName = resolvePackageName(proxiedUid, proxiedPackageName);
1012 if (resolveProxiedPackageName == null) {
1013 return AppOpsManager.MODE_IGNORED;
1014 }
1015 return noteOperationUnchecked(code, proxiedUid, resolveProxiedPackageName,
1016 proxyMode, resolveProxyPackageName);
Svet Ganov99b60432015-06-27 13:15:22 -07001017 }
1018
1019 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001020 public int noteOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001021 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001022 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001023 String resolvedPackageName = resolvePackageName(uid, packageName);
1024 if (resolvedPackageName == null) {
1025 return AppOpsManager.MODE_IGNORED;
1026 }
1027 return noteOperationUnchecked(code, uid, resolvedPackageName, 0, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001028 }
1029
1030 private int noteOperationUnchecked(int code, int uid, String packageName,
1031 int proxyUid, String proxyPackageName) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001032 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001033 Ops ops = getOpsRawLocked(uid, packageName, true);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001034 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001035 if (DEBUG) Log.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
1036 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001037 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001038 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001039 Op op = getOpLocked(ops, code, true);
Jason Monk1c7c3192014-06-26 12:52:18 -04001040 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001041 return AppOpsManager.MODE_IGNORED;
1042 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001043 if (op.duration == -1) {
1044 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
1045 + " code " + code + " time=" + op.time + " duration=" + op.duration);
1046 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001047 op.duration = 0;
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001048 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001049 UidState uidState = ops.uidState;
1050 if (uidState.opModes != null) {
1051 final int uidMode = uidState.opModes.get(switchCode);
1052 if (uidMode != AppOpsManager.MODE_ALLOWED) {
1053 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1054 + switchCode + " (" + code + ") uid " + uid + " package "
1055 + packageName);
1056 op.rejectTime = System.currentTimeMillis();
1057 return uidMode;
1058 }
1059 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001060 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
1061 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
1062 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1063 + switchCode + " (" + code + ") uid " + uid + " package " + packageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001064 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001065 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001066 }
1067 if (DEBUG) Log.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
1068 + " package " + packageName);
1069 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001070 op.rejectTime = 0;
Svet Ganov99b60432015-06-27 13:15:22 -07001071 op.proxyUid = proxyUid;
1072 op.proxyPackageName = proxyPackageName;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001073 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001074 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001075 }
1076
1077 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001078 public int startOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001079 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001080 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001081 String resolvedPackageName = resolvePackageName(uid, packageName);
1082 if (resolvedPackageName == null) {
1083 return AppOpsManager.MODE_IGNORED;
1084 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001085 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001086 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001087 Ops ops = getOpsRawLocked(uid, resolvedPackageName, true);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001088 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001089 if (DEBUG) Log.d(TAG, "startOperation: no op for code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001090 + " package " + resolvedPackageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001091 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001092 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001093 Op op = getOpLocked(ops, code, true);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001094 if (isOpRestricted(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001095 return AppOpsManager.MODE_IGNORED;
1096 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001097 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001098 UidState uidState = ops.uidState;
1099 if (uidState.opModes != null) {
1100 final int uidMode = uidState.opModes.get(switchCode);
1101 if (uidMode != AppOpsManager.MODE_ALLOWED) {
1102 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1103 + switchCode + " (" + code + ") uid " + uid + " package "
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001104 + resolvedPackageName);
Svet Ganov2af57082015-07-30 08:44:20 -07001105 op.rejectTime = System.currentTimeMillis();
1106 return uidMode;
1107 }
1108 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001109 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
1110 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
1111 if (DEBUG) Log.d(TAG, "startOperation: reject #" + op.mode + " for code "
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001112 + switchCode + " (" + code + ") uid " + uid + " package "
1113 + resolvedPackageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001114 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001115 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001116 }
1117 if (DEBUG) Log.d(TAG, "startOperation: allowing code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001118 + " package " + resolvedPackageName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001119 if (op.nesting == 0) {
1120 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001121 op.rejectTime = 0;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001122 op.duration = -1;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001123 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001124 op.nesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001125 if (client.mStartedOps != null) {
1126 client.mStartedOps.add(op);
1127 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001128 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001129 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001130 }
1131
1132 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001133 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001134 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001135 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001136 String resolvedPackageName = resolvePackageName(uid, packageName);
1137 if (resolvedPackageName == null) {
1138 return;
1139 }
1140 if (!(token instanceof ClientState)) {
1141 return;
1142 }
1143 ClientState client = (ClientState) token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001144 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001145 Op op = getOpLocked(code, uid, resolvedPackageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001146 if (op == null) {
1147 return;
1148 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001149 if (client.mStartedOps != null) {
1150 if (!client.mStartedOps.remove(op)) {
1151 throw new IllegalStateException("Operation not started: uid" + op.uid
1152 + " pkg=" + op.packageName + " op=" + op.op);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001153 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001154 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001155 finishOperationLocked(op);
1156 }
1157 }
1158
Svet Ganovb9d71a62015-04-30 10:38:13 -07001159 @Override
1160 public int permissionToOpCode(String permission) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001161 if (permission == null) {
1162 return AppOpsManager.OP_NONE;
1163 }
Svet Ganovb9d71a62015-04-30 10:38:13 -07001164 return AppOpsManager.permissionToOpCode(permission);
1165 }
1166
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001167 void finishOperationLocked(Op op) {
1168 if (op.nesting <= 1) {
1169 if (op.nesting == 1) {
1170 op.duration = (int)(System.currentTimeMillis() - op.time);
1171 op.time += op.duration;
1172 } else {
1173 Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
1174 + op.packageName + " code " + op.op + " time=" + op.time
1175 + " duration=" + op.duration + " nesting=" + op.nesting);
1176 }
1177 op.nesting = 0;
1178 } else {
1179 op.nesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001180 }
1181 }
1182
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001183 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001184 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001185 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001186 }
1187 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001188 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001189 }
1190 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
1191 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001192 }
1193
Dianne Hackborn961321f2013-02-05 17:22:41 -08001194 private void verifyIncomingOp(int op) {
1195 if (op >= 0 && op < AppOpsManager._NUM_OP) {
1196 return;
1197 }
1198 throw new IllegalArgumentException("Bad operation #" + op);
1199 }
1200
Svet Ganov2af57082015-07-30 08:44:20 -07001201 private UidState getUidStateLocked(int uid, boolean edit) {
1202 UidState uidState = mUidStates.get(uid);
1203 if (uidState == null) {
1204 if (!edit) {
1205 return null;
1206 }
1207 uidState = new UidState(uid);
1208 mUidStates.put(uid, uidState);
1209 }
1210 return uidState;
1211 }
1212
Dianne Hackborn0fcef842014-09-12 15:38:33 -07001213 private Ops getOpsRawLocked(int uid, String packageName, boolean edit) {
Svet Ganov2af57082015-07-30 08:44:20 -07001214 UidState uidState = getUidStateLocked(uid, edit);
1215 if (uidState == null) {
1216 return null;
1217 }
1218
1219 if (uidState.pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001220 if (!edit) {
1221 return null;
1222 }
Svet Ganov2af57082015-07-30 08:44:20 -07001223 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001224 }
Svet Ganov2af57082015-07-30 08:44:20 -07001225
1226 Ops ops = uidState.pkgOps.get(packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001227 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001228 if (!edit) {
1229 return null;
1230 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001231 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001232 // This is the first time we have seen this package name under this uid,
1233 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -08001234 if (uid != 0) {
1235 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001236 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001237 int pkgUid = -1;
1238 try {
Jason Monk1c7c3192014-06-26 12:52:18 -04001239 ApplicationInfo appInfo = ActivityThread.getPackageManager()
Jeff Sharkeycd654482016-01-08 17:42:11 -07001240 .getApplicationInfo(packageName,
1241 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1242 UserHandle.getUserId(uid));
Jason Monk1c7c3192014-06-26 12:52:18 -04001243 if (appInfo != null) {
1244 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001245 isPrivileged = (appInfo.privateFlags
1246 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001247 } else {
1248 if ("media".equals(packageName)) {
1249 pkgUid = Process.MEDIA_UID;
1250 isPrivileged = false;
Andy Hunged0ea402015-10-30 14:11:46 -07001251 } else if ("audioserver".equals(packageName)) {
1252 pkgUid = Process.AUDIOSERVER_UID;
1253 isPrivileged = false;
Chien-Yu Chen75cade02016-01-11 10:56:21 -08001254 } else if ("cameraserver".equals(packageName)) {
1255 pkgUid = Process.CAMERASERVER_UID;
1256 isPrivileged = false;
Jason Monk1c7c3192014-06-26 12:52:18 -04001257 }
Dianne Hackborn713df152013-05-17 11:27:57 -07001258 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001259 } catch (RemoteException e) {
1260 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001261 }
1262 if (pkgUid != uid) {
1263 // Oops! The package name is not valid for the uid they are calling
1264 // under. Abort.
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001265 RuntimeException ex = new RuntimeException("here");
1266 ex.fillInStackTrace();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001267 Slog.w(TAG, "Bad call: specified package " + packageName
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001268 + " under uid " + uid + " but it is really " + pkgUid, ex);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001269 return null;
1270 }
1271 } finally {
1272 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001273 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001274 }
Svet Ganov2af57082015-07-30 08:44:20 -07001275 ops = new Ops(packageName, uidState, isPrivileged);
1276 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001277 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08001278 return ops;
1279 }
1280
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001281 private void scheduleWriteLocked() {
1282 if (!mWriteScheduled) {
1283 mWriteScheduled = true;
1284 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
1285 }
1286 }
1287
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001288 private void scheduleFastWriteLocked() {
1289 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001290 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001291 mFastWriteScheduled = true;
1292 mHandler.removeCallbacks(mWriteRunner);
1293 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001294 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001295 }
1296
Dianne Hackborn72e39832013-01-18 18:36:09 -08001297 private Op getOpLocked(int code, int uid, String packageName, boolean edit) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001298 Ops ops = getOpsRawLocked(uid, packageName, edit);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001299 if (ops == null) {
1300 return null;
1301 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001302 return getOpLocked(ops, code, edit);
1303 }
1304
1305 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001306 Op op = ops.get(code);
1307 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001308 if (!edit) {
1309 return null;
1310 }
Svet Ganov2af57082015-07-30 08:44:20 -07001311 op = new Op(ops.uidState.uid, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001312 ops.put(code, op);
1313 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001314 if (edit) {
1315 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001316 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001317 return op;
1318 }
1319
Jason Monk1c7c3192014-06-26 12:52:18 -04001320 private boolean isOpRestricted(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04001321 int userHandle = UserHandle.getUserId(uid);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001322 final int restrictionSetCount = mOpUserRestrictions.size();
Ruben Brunk29931bc2016-03-11 00:24:26 -08001323
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001324 for (int i = 0; i < restrictionSetCount; i++) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08001325 // For each client, check that the given op is not restricted, or that the given
1326 // package is exempt from the restriction.
1327
1328 SparseArray<Pair<boolean[],SparseArray<ArraySet<String>>>> perUserRestrictions =
1329 mOpUserRestrictions.valueAt(i);
1330
1331 Pair<boolean[],SparseArray<ArraySet<String>>> restrictions =
1332 perUserRestrictions.get(userHandle);
1333 if (restrictions == null) {
1334 continue; // No restrictions set by this client
1335 }
1336
1337 boolean[] opRestrictions = restrictions.first;
1338 SparseArray<ArraySet<String>> opExceptions = restrictions.second;
1339
1340 if (opRestrictions == null) {
1341 continue; // No restrictions set by this client
1342 }
1343
1344 if (opRestrictions[code]) {
Ruben Brunk32f0fa42016-03-11 19:07:07 -08001345
1346 if (opExceptions != null) {
1347 ArraySet<String> ex = opExceptions.get(code);
1348 if (ex != null && ex.contains(packageName)) {
1349 continue; // AppOps code is restricted, but this package is exempt
1350 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08001351 }
1352
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001353 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08001354 // If we are the system, bypass user restrictions for certain codes
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001355 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001356 Ops ops = getOpsRawLocked(uid, packageName, true);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001357 if ((ops != null) && ops.isPrivileged) {
1358 return false;
1359 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001360 }
1361 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08001362
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001363 return true;
Jason Monk1c7c3192014-06-26 12:52:18 -04001364 }
Jason Monk62062992014-05-06 09:55:28 -04001365 }
1366 return false;
1367 }
1368
Dianne Hackborn35654b62013-01-14 17:38:02 -08001369 void readState() {
1370 synchronized (mFile) {
1371 synchronized (this) {
1372 FileInputStream stream;
1373 try {
1374 stream = mFile.openRead();
1375 } catch (FileNotFoundException e) {
1376 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
1377 return;
1378 }
1379 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001380 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001381 try {
1382 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001383 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001384 int type;
1385 while ((type = parser.next()) != XmlPullParser.START_TAG
1386 && type != XmlPullParser.END_DOCUMENT) {
1387 ;
1388 }
1389
1390 if (type != XmlPullParser.START_TAG) {
1391 throw new IllegalStateException("no start tag found");
1392 }
1393
1394 int outerDepth = parser.getDepth();
1395 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1396 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1397 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1398 continue;
1399 }
1400
1401 String tagName = parser.getName();
1402 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001403 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07001404 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07001405 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001406 } else {
1407 Slog.w(TAG, "Unknown element under <app-ops>: "
1408 + parser.getName());
1409 XmlUtils.skipCurrentTag(parser);
1410 }
1411 }
1412 success = true;
1413 } catch (IllegalStateException e) {
1414 Slog.w(TAG, "Failed parsing " + e);
1415 } catch (NullPointerException e) {
1416 Slog.w(TAG, "Failed parsing " + e);
1417 } catch (NumberFormatException e) {
1418 Slog.w(TAG, "Failed parsing " + e);
1419 } catch (XmlPullParserException e) {
1420 Slog.w(TAG, "Failed parsing " + e);
1421 } catch (IOException e) {
1422 Slog.w(TAG, "Failed parsing " + e);
1423 } catch (IndexOutOfBoundsException e) {
1424 Slog.w(TAG, "Failed parsing " + e);
1425 } finally {
1426 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07001427 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001428 }
1429 try {
1430 stream.close();
1431 } catch (IOException e) {
1432 }
1433 }
1434 }
1435 }
1436 }
1437
Svet Ganov2af57082015-07-30 08:44:20 -07001438 void readUidOps(XmlPullParser parser) throws NumberFormatException,
1439 XmlPullParserException, IOException {
1440 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
1441 int outerDepth = parser.getDepth();
1442 int type;
1443 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1444 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1445 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1446 continue;
1447 }
1448
1449 String tagName = parser.getName();
1450 if (tagName.equals("op")) {
1451 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
1452 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
1453 UidState uidState = getUidStateLocked(uid, true);
1454 if (uidState.opModes == null) {
1455 uidState.opModes = new SparseIntArray();
1456 }
1457 uidState.opModes.put(code, mode);
1458 } else {
1459 Slog.w(TAG, "Unknown element under <uid-ops>: "
1460 + parser.getName());
1461 XmlUtils.skipCurrentTag(parser);
1462 }
1463 }
1464 }
1465
Dave Burke0997c5bd2013-08-02 20:25:02 +00001466 void readPackage(XmlPullParser parser) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001467 XmlPullParserException, IOException {
1468 String pkgName = parser.getAttributeValue(null, "n");
1469 int outerDepth = parser.getDepth();
1470 int type;
1471 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1472 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1473 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1474 continue;
1475 }
1476
1477 String tagName = parser.getName();
1478 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001479 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001480 } else {
1481 Slog.w(TAG, "Unknown element under <pkg>: "
1482 + parser.getName());
1483 XmlUtils.skipCurrentTag(parser);
1484 }
1485 }
1486 }
1487
Dave Burke0997c5bd2013-08-02 20:25:02 +00001488 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001489 XmlPullParserException, IOException {
1490 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Jason Monk1c7c3192014-06-26 12:52:18 -04001491 String isPrivilegedString = parser.getAttributeValue(null, "p");
1492 boolean isPrivileged = false;
1493 if (isPrivilegedString == null) {
1494 try {
1495 IPackageManager packageManager = ActivityThread.getPackageManager();
1496 if (packageManager != null) {
1497 ApplicationInfo appInfo = ActivityThread.getPackageManager()
1498 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
1499 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001500 isPrivileged = (appInfo.privateFlags
1501 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001502 }
1503 } else {
1504 // Could not load data, don't add to cache so it will be loaded later.
1505 return;
1506 }
1507 } catch (RemoteException e) {
1508 Slog.w(TAG, "Could not contact PackageManager", e);
1509 }
1510 } else {
1511 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
1512 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001513 int outerDepth = parser.getDepth();
1514 int type;
1515 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1516 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1517 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1518 continue;
1519 }
1520
1521 String tagName = parser.getName();
1522 if (tagName.equals("op")) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001523 Op op = new Op(uid, pkgName, Integer.parseInt(parser.getAttributeValue(null, "n")));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001524 String mode = parser.getAttributeValue(null, "m");
1525 if (mode != null) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001526 op.mode = Integer.parseInt(mode);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001527 }
1528 String time = parser.getAttributeValue(null, "t");
1529 if (time != null) {
1530 op.time = Long.parseLong(time);
1531 }
1532 time = parser.getAttributeValue(null, "r");
1533 if (time != null) {
1534 op.rejectTime = Long.parseLong(time);
1535 }
1536 String dur = parser.getAttributeValue(null, "d");
1537 if (dur != null) {
1538 op.duration = Integer.parseInt(dur);
1539 }
Svet Ganov99b60432015-06-27 13:15:22 -07001540 String proxyUid = parser.getAttributeValue(null, "pu");
1541 if (proxyUid != null) {
1542 op.proxyUid = Integer.parseInt(proxyUid);
1543 }
1544 String proxyPackageName = parser.getAttributeValue(null, "pp");
1545 if (proxyPackageName != null) {
1546 op.proxyPackageName = proxyPackageName;
1547 }
Svet Ganov2af57082015-07-30 08:44:20 -07001548
1549 UidState uidState = getUidStateLocked(uid, true);
1550 if (uidState.pkgOps == null) {
1551 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001552 }
Svet Ganov2af57082015-07-30 08:44:20 -07001553
1554 Ops ops = uidState.pkgOps.get(pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001555 if (ops == null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001556 ops = new Ops(pkgName, uidState, isPrivileged);
1557 uidState.pkgOps.put(pkgName, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001558 }
1559 ops.put(op.op, op);
1560 } else {
1561 Slog.w(TAG, "Unknown element under <pkg>: "
1562 + parser.getName());
1563 XmlUtils.skipCurrentTag(parser);
1564 }
1565 }
1566 }
1567
1568 void writeState() {
1569 synchronized (mFile) {
1570 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
1571
1572 FileOutputStream stream;
1573 try {
1574 stream = mFile.startWrite();
1575 } catch (IOException e) {
1576 Slog.w(TAG, "Failed to write state: " + e);
1577 return;
1578 }
1579
1580 try {
1581 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001582 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001583 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001584 out.startTag(null, "app-ops");
Svet Ganov2af57082015-07-30 08:44:20 -07001585
1586 final int uidStateCount = mUidStates.size();
1587 for (int i = 0; i < uidStateCount; i++) {
1588 UidState uidState = mUidStates.valueAt(i);
1589 if (uidState.opModes != null && uidState.opModes.size() > 0) {
1590 out.startTag(null, "uid");
1591 out.attribute(null, "n", Integer.toString(uidState.uid));
1592 SparseIntArray uidOpModes = uidState.opModes;
1593 final int opCount = uidOpModes.size();
1594 for (int j = 0; j < opCount; j++) {
1595 final int op = uidOpModes.keyAt(j);
1596 final int mode = uidOpModes.valueAt(j);
1597 out.startTag(null, "op");
1598 out.attribute(null, "n", Integer.toString(op));
1599 out.attribute(null, "m", Integer.toString(mode));
1600 out.endTag(null, "op");
1601 }
1602 out.endTag(null, "uid");
1603 }
1604 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001605
1606 if (allOps != null) {
1607 String lastPkg = null;
1608 for (int i=0; i<allOps.size(); i++) {
1609 AppOpsManager.PackageOps pkg = allOps.get(i);
1610 if (!pkg.getPackageName().equals(lastPkg)) {
1611 if (lastPkg != null) {
1612 out.endTag(null, "pkg");
1613 }
1614 lastPkg = pkg.getPackageName();
1615 out.startTag(null, "pkg");
1616 out.attribute(null, "n", lastPkg);
1617 }
1618 out.startTag(null, "uid");
1619 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04001620 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001621 Ops ops = getOpsRawLocked(pkg.getUid(), pkg.getPackageName(), false);
Jason Monk1c7c3192014-06-26 12:52:18 -04001622 // Should always be present as the list of PackageOps is generated
1623 // from Ops.
1624 if (ops != null) {
1625 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
1626 } else {
1627 out.attribute(null, "p", Boolean.toString(false));
1628 }
1629 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001630 List<AppOpsManager.OpEntry> ops = pkg.getOps();
1631 for (int j=0; j<ops.size(); j++) {
1632 AppOpsManager.OpEntry op = ops.get(j);
1633 out.startTag(null, "op");
1634 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07001635 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001636 out.attribute(null, "m", Integer.toString(op.getMode()));
1637 }
1638 long time = op.getTime();
1639 if (time != 0) {
1640 out.attribute(null, "t", Long.toString(time));
1641 }
1642 time = op.getRejectTime();
1643 if (time != 0) {
1644 out.attribute(null, "r", Long.toString(time));
1645 }
1646 int dur = op.getDuration();
1647 if (dur != 0) {
1648 out.attribute(null, "d", Integer.toString(dur));
1649 }
Svet Ganov99b60432015-06-27 13:15:22 -07001650 int proxyUid = op.getProxyUid();
1651 if (proxyUid != -1) {
1652 out.attribute(null, "pu", Integer.toString(proxyUid));
1653 }
1654 String proxyPackageName = op.getProxyPackageName();
1655 if (proxyPackageName != null) {
1656 out.attribute(null, "pp", proxyPackageName);
1657 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001658 out.endTag(null, "op");
1659 }
1660 out.endTag(null, "uid");
1661 }
1662 if (lastPkg != null) {
1663 out.endTag(null, "pkg");
1664 }
1665 }
1666
1667 out.endTag(null, "app-ops");
1668 out.endDocument();
1669 mFile.finishWrite(stream);
1670 } catch (IOException e) {
1671 Slog.w(TAG, "Failed to write state, restoring backup.", e);
1672 mFile.failWrite(stream);
1673 }
1674 }
1675 }
1676
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001677 static class Shell extends ShellCommand {
1678 final IAppOpsService mInterface;
1679 final AppOpsService mInternal;
1680
1681 int userId = UserHandle.USER_SYSTEM;
1682 String packageName;
1683 String opStr;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001684 String modeStr;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001685 int op;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001686 int mode;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001687 int packageUid;
1688
1689 Shell(IAppOpsService iface, AppOpsService internal) {
1690 mInterface = iface;
1691 mInternal = internal;
1692 }
1693
1694 @Override
1695 public int onCommand(String cmd) {
1696 return onShellCommand(this, cmd);
1697 }
1698
1699 @Override
1700 public void onHelp() {
1701 PrintWriter pw = getOutPrintWriter();
1702 dumpCommandHelp(pw);
1703 }
1704
1705 private int strOpToOp(String op, PrintWriter err) {
1706 try {
1707 return AppOpsManager.strOpToOp(op);
1708 } catch (IllegalArgumentException e) {
1709 }
1710 try {
1711 return Integer.parseInt(op);
1712 } catch (NumberFormatException e) {
1713 }
1714 try {
1715 return AppOpsManager.strDebugOpToOp(op);
1716 } catch (IllegalArgumentException e) {
1717 err.println("Error: " + e.getMessage());
1718 return -1;
1719 }
1720 }
1721
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001722 int strModeToMode(String modeStr, PrintWriter err) {
1723 switch (modeStr) {
1724 case "allow":
1725 return AppOpsManager.MODE_ALLOWED;
1726 case "deny":
1727 return AppOpsManager.MODE_ERRORED;
1728 case "ignore":
1729 return AppOpsManager.MODE_IGNORED;
1730 case "default":
1731 return AppOpsManager.MODE_DEFAULT;
1732 }
1733 try {
1734 return Integer.parseInt(modeStr);
1735 } catch (NumberFormatException e) {
1736 }
1737 err.println("Error: Mode " + modeStr + " is not valid");
1738 return -1;
1739 }
1740
1741 int parseUserOpMode(int defMode, PrintWriter err) throws RemoteException {
1742 userId = UserHandle.USER_CURRENT;
1743 opStr = null;
1744 modeStr = null;
1745 for (String argument; (argument = getNextArg()) != null;) {
1746 if ("--user".equals(argument)) {
1747 userId = UserHandle.parseUserArg(getNextArgRequired());
1748 } else {
1749 if (opStr == null) {
1750 opStr = argument;
1751 } else if (modeStr == null) {
1752 modeStr = argument;
1753 break;
1754 }
1755 }
1756 }
1757 if (opStr == null) {
1758 err.println("Error: Operation not specified.");
1759 return -1;
1760 }
1761 op = strOpToOp(opStr, err);
1762 if (op < 0) {
1763 return -1;
1764 }
1765 if (modeStr != null) {
1766 if ((mode=strModeToMode(modeStr, err)) < 0) {
1767 return -1;
1768 }
1769 } else {
1770 mode = defMode;
1771 }
1772 return 0;
1773 }
1774
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001775 int parseUserPackageOp(boolean reqOp, PrintWriter err) throws RemoteException {
1776 userId = UserHandle.USER_CURRENT;
1777 packageName = null;
1778 opStr = null;
1779 for (String argument; (argument = getNextArg()) != null;) {
1780 if ("--user".equals(argument)) {
1781 userId = UserHandle.parseUserArg(getNextArgRequired());
1782 } else {
1783 if (packageName == null) {
1784 packageName = argument;
1785 } else if (opStr == null) {
1786 opStr = argument;
1787 break;
1788 }
1789 }
1790 }
1791 if (packageName == null) {
1792 err.println("Error: Package name not specified.");
1793 return -1;
1794 } else if (opStr == null && reqOp) {
1795 err.println("Error: Operation not specified.");
1796 return -1;
1797 }
1798 if (opStr != null) {
1799 op = strOpToOp(opStr, err);
1800 if (op < 0) {
1801 return -1;
1802 }
1803 } else {
1804 op = AppOpsManager.OP_NONE;
1805 }
1806 if (userId == UserHandle.USER_CURRENT) {
1807 userId = ActivityManager.getCurrentUser();
1808 }
1809 if ("root".equals(packageName)) {
1810 packageUid = 0;
1811 } else {
Jeff Sharkeycd654482016-01-08 17:42:11 -07001812 packageUid = AppGlobals.getPackageManager().getPackageUid(packageName,
1813 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001814 }
1815 if (packageUid < 0) {
1816 err.println("Error: No UID for " + packageName + " in user " + userId);
1817 return -1;
1818 }
1819 return 0;
1820 }
1821 }
1822
1823 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
1824 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
1825 (new Shell(this, this)).exec(this, in, out, err, args, resultReceiver);
1826 }
1827
1828 static void dumpCommandHelp(PrintWriter pw) {
1829 pw.println("AppOps service (appops) commands:");
1830 pw.println(" help");
1831 pw.println(" Print this help text.");
1832 pw.println(" set [--user <USER_ID>] <PACKAGE> <OP> <MODE>");
1833 pw.println(" Set the mode for a particular application and operation.");
1834 pw.println(" get [--user <USER_ID>] <PACKAGE> [<OP>]");
1835 pw.println(" Return the mode for a particular application and optional operation.");
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001836 pw.println(" query-op [--user <USER_ID>] <OP> [<MODE>]");
1837 pw.println(" Print all packages that currently have the given op in the given mode.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001838 pw.println(" reset [--user <USER_ID>] [<PACKAGE>]");
1839 pw.println(" Reset the given application or all applications to default modes.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001840 pw.println(" write-settings");
1841 pw.println(" Immediately write pending changes to storage.");
1842 pw.println(" read-settings");
1843 pw.println(" Read the last written settings, replacing current state in RAM.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001844 pw.println(" options:");
1845 pw.println(" <PACKAGE> an Android package name.");
1846 pw.println(" <OP> an AppOps operation.");
1847 pw.println(" <MODE> one of allow, ignore, deny, or default");
1848 pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
1849 pw.println(" specified, the current user is assumed.");
1850 }
1851
1852 static int onShellCommand(Shell shell, String cmd) {
1853 if (cmd == null) {
1854 return shell.handleDefaultCommands(cmd);
1855 }
1856 PrintWriter pw = shell.getOutPrintWriter();
1857 PrintWriter err = shell.getErrPrintWriter();
1858 try {
1859 switch (cmd) {
1860 case "set": {
1861 int res = shell.parseUserPackageOp(true, err);
1862 if (res < 0) {
1863 return res;
1864 }
1865 String modeStr = shell.getNextArg();
1866 if (modeStr == null) {
1867 err.println("Error: Mode not specified.");
1868 return -1;
1869 }
1870
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001871 final int mode = shell.strModeToMode(modeStr, err);
1872 if (mode < 0) {
1873 return -1;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001874 }
1875
1876 shell.mInterface.setMode(shell.op, shell.packageUid, shell.packageName, mode);
1877 return 0;
1878 }
1879 case "get": {
1880 int res = shell.parseUserPackageOp(false, err);
1881 if (res < 0) {
1882 return res;
1883 }
1884
1885 List<AppOpsManager.PackageOps> ops = shell.mInterface.getOpsForPackage(
1886 shell.packageUid, shell.packageName,
1887 shell.op != AppOpsManager.OP_NONE ? new int[] {shell.op} : null);
1888 if (ops == null || ops.size() <= 0) {
1889 pw.println("No operations.");
1890 return 0;
1891 }
1892 final long now = System.currentTimeMillis();
1893 for (int i=0; i<ops.size(); i++) {
1894 List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
1895 for (int j=0; j<entries.size(); j++) {
1896 AppOpsManager.OpEntry ent = entries.get(j);
1897 pw.print(AppOpsManager.opToName(ent.getOp()));
1898 pw.print(": ");
1899 switch (ent.getMode()) {
1900 case AppOpsManager.MODE_ALLOWED:
1901 pw.print("allow");
1902 break;
1903 case AppOpsManager.MODE_IGNORED:
1904 pw.print("ignore");
1905 break;
1906 case AppOpsManager.MODE_ERRORED:
1907 pw.print("deny");
1908 break;
1909 case AppOpsManager.MODE_DEFAULT:
1910 pw.print("default");
1911 break;
1912 default:
1913 pw.print("mode=");
1914 pw.print(ent.getMode());
1915 break;
1916 }
1917 if (ent.getTime() != 0) {
1918 pw.print("; time=");
1919 TimeUtils.formatDuration(now - ent.getTime(), pw);
1920 pw.print(" ago");
1921 }
1922 if (ent.getRejectTime() != 0) {
1923 pw.print("; rejectTime=");
1924 TimeUtils.formatDuration(now - ent.getRejectTime(), pw);
1925 pw.print(" ago");
1926 }
1927 if (ent.getDuration() == -1) {
1928 pw.print(" (running)");
1929 } else if (ent.getDuration() != 0) {
1930 pw.print("; duration=");
1931 TimeUtils.formatDuration(ent.getDuration(), pw);
1932 }
1933 pw.println();
1934 }
1935 }
1936 return 0;
1937 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001938 case "query-op": {
1939 int res = shell.parseUserOpMode(AppOpsManager.MODE_IGNORED, err);
1940 if (res < 0) {
1941 return res;
1942 }
1943 List<AppOpsManager.PackageOps> ops = shell.mInterface.getPackagesForOps(
1944 new int[] {shell.op});
1945 if (ops == null || ops.size() <= 0) {
1946 pw.println("No operations.");
1947 return 0;
1948 }
1949 for (int i=0; i<ops.size(); i++) {
1950 final AppOpsManager.PackageOps pkg = ops.get(i);
1951 boolean hasMatch = false;
1952 final List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
1953 for (int j=0; j<entries.size(); j++) {
1954 AppOpsManager.OpEntry ent = entries.get(j);
1955 if (ent.getOp() == shell.op && ent.getMode() == shell.mode) {
1956 hasMatch = true;
1957 break;
1958 }
1959 }
1960 if (hasMatch) {
1961 pw.println(pkg.getPackageName());
1962 }
1963 }
1964 return 0;
1965 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001966 case "reset": {
1967 String packageName = null;
1968 int userId = UserHandle.USER_CURRENT;
1969 for (String argument; (argument = shell.getNextArg()) != null;) {
1970 if ("--user".equals(argument)) {
1971 String userStr = shell.getNextArgRequired();
1972 userId = UserHandle.parseUserArg(userStr);
1973 } else {
1974 if (packageName == null) {
1975 packageName = argument;
1976 } else {
1977 err.println("Error: Unsupported argument: " + argument);
1978 return -1;
1979 }
1980 }
1981 }
1982
1983 if (userId == UserHandle.USER_CURRENT) {
1984 userId = ActivityManager.getCurrentUser();
1985 }
1986
1987 shell.mInterface.resetAllModes(userId, packageName);
1988 pw.print("Reset all modes for: ");
1989 if (userId == UserHandle.USER_ALL) {
1990 pw.print("all users");
1991 } else {
1992 pw.print("user "); pw.print(userId);
1993 }
1994 pw.print(", ");
1995 if (packageName == null) {
1996 pw.println("all packages");
1997 } else {
1998 pw.print("package "); pw.println(packageName);
1999 }
2000 return 0;
2001 }
2002 case "write-settings": {
2003 shell.mInternal.mContext.enforcePermission(
2004 android.Manifest.permission.UPDATE_APP_OPS_STATS,
2005 Binder.getCallingPid(), Binder.getCallingUid(), null);
2006 long token = Binder.clearCallingIdentity();
2007 try {
2008 synchronized (shell.mInternal) {
2009 shell.mInternal.mHandler.removeCallbacks(shell.mInternal.mWriteRunner);
2010 }
2011 shell.mInternal.writeState();
2012 pw.println("Current settings written.");
2013 } finally {
2014 Binder.restoreCallingIdentity(token);
2015 }
2016 return 0;
2017 }
2018 case "read-settings": {
2019 shell.mInternal.mContext.enforcePermission(
2020 android.Manifest.permission.UPDATE_APP_OPS_STATS,
2021 Binder.getCallingPid(), Binder.getCallingUid(), null);
2022 long token = Binder.clearCallingIdentity();
2023 try {
2024 shell.mInternal.readState();
2025 pw.println("Last settings read.");
2026 } finally {
2027 Binder.restoreCallingIdentity(token);
2028 }
2029 return 0;
2030 }
2031 default:
2032 return shell.handleDefaultCommands(cmd);
2033 }
2034 } catch (RemoteException e) {
2035 pw.println("Remote exception: " + e);
2036 }
2037 return -1;
2038 }
2039
2040 private void dumpHelp(PrintWriter pw) {
2041 pw.println("AppOps service (appops) dump options:");
2042 pw.println(" none");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002043 }
2044
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002045 @Override
2046 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2047 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2048 != PackageManager.PERMISSION_GRANTED) {
2049 pw.println("Permission Denial: can't dump ApOps service from from pid="
2050 + Binder.getCallingPid()
2051 + ", uid=" + Binder.getCallingUid());
2052 return;
2053 }
2054
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002055 if (args != null) {
2056 for (int i=0; i<args.length; i++) {
2057 String arg = args[i];
2058 if ("-h".equals(arg)) {
2059 dumpHelp(pw);
2060 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07002061 } else if ("-a".equals(arg)) {
2062 // dump all data
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002063 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
2064 pw.println("Unknown option: " + arg);
2065 return;
2066 } else {
2067 pw.println("Unknown command: " + arg);
2068 return;
2069 }
2070 }
2071 }
2072
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002073 synchronized (this) {
2074 pw.println("Current AppOps Service state:");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002075 final long now = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002076 boolean needSep = false;
2077 if (mOpModeWatchers.size() > 0) {
2078 needSep = true;
2079 pw.println(" Op mode watchers:");
2080 for (int i=0; i<mOpModeWatchers.size(); i++) {
2081 pw.print(" Op "); pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
2082 pw.println(":");
2083 ArrayList<Callback> callbacks = mOpModeWatchers.valueAt(i);
2084 for (int j=0; j<callbacks.size(); j++) {
2085 pw.print(" #"); pw.print(j); pw.print(": ");
2086 pw.println(callbacks.get(j));
2087 }
2088 }
2089 }
2090 if (mPackageModeWatchers.size() > 0) {
2091 needSep = true;
2092 pw.println(" Package mode watchers:");
2093 for (int i=0; i<mPackageModeWatchers.size(); i++) {
2094 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
2095 pw.println(":");
2096 ArrayList<Callback> callbacks = mPackageModeWatchers.valueAt(i);
2097 for (int j=0; j<callbacks.size(); j++) {
2098 pw.print(" #"); pw.print(j); pw.print(": ");
2099 pw.println(callbacks.get(j));
2100 }
2101 }
2102 }
2103 if (mModeWatchers.size() > 0) {
2104 needSep = true;
2105 pw.println(" All mode watchers:");
2106 for (int i=0; i<mModeWatchers.size(); i++) {
2107 pw.print(" "); pw.print(mModeWatchers.keyAt(i));
2108 pw.print(" -> "); pw.println(mModeWatchers.valueAt(i));
2109 }
2110 }
2111 if (mClients.size() > 0) {
2112 needSep = true;
2113 pw.println(" Clients:");
2114 for (int i=0; i<mClients.size(); i++) {
2115 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
2116 ClientState cs = mClients.valueAt(i);
2117 pw.print(" "); pw.println(cs);
2118 if (cs.mStartedOps != null && cs.mStartedOps.size() > 0) {
2119 pw.println(" Started ops:");
2120 for (int j=0; j<cs.mStartedOps.size(); j++) {
2121 Op op = cs.mStartedOps.get(j);
2122 pw.print(" "); pw.print("uid="); pw.print(op.uid);
2123 pw.print(" pkg="); pw.print(op.packageName);
2124 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
2125 }
2126 }
2127 }
2128 }
John Spurlock1af30c72014-03-10 08:33:35 -04002129 if (mAudioRestrictions.size() > 0) {
2130 boolean printedHeader = false;
2131 for (int o=0; o<mAudioRestrictions.size(); o++) {
2132 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
2133 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
2134 for (int i=0; i<restrictions.size(); i++) {
2135 if (!printedHeader){
2136 pw.println(" Audio Restrictions:");
2137 printedHeader = true;
2138 needSep = true;
2139 }
John Spurlock7b414672014-07-18 13:02:39 -04002140 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04002141 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04002142 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04002143 Restriction r = restrictions.valueAt(i);
2144 pw.print(": mode="); pw.println(r.mode);
2145 if (!r.exceptionPackages.isEmpty()) {
2146 pw.println(" Exceptions:");
2147 for (int j=0; j<r.exceptionPackages.size(); j++) {
2148 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
2149 }
2150 }
2151 }
2152 }
2153 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002154 if (needSep) {
2155 pw.println();
2156 }
Svet Ganov2af57082015-07-30 08:44:20 -07002157 for (int i=0; i<mUidStates.size(); i++) {
2158 UidState uidState = mUidStates.valueAt(i);
2159
2160 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
2161
2162 SparseIntArray opModes = uidState.opModes;
2163 if (opModes != null) {
2164 final int opModeCount = opModes.size();
2165 for (int j = 0; j < opModeCount; j++) {
2166 final int code = opModes.keyAt(j);
2167 final int mode = opModes.valueAt(j);
2168 pw.print(" "); pw.print(AppOpsManager.opToName(code));
2169 pw.print(": mode="); pw.println(mode);
2170 }
2171 }
2172
2173 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
2174 if (pkgOps == null) {
2175 continue;
2176 }
2177
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002178 for (Ops ops : pkgOps.values()) {
2179 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
2180 for (int j=0; j<ops.size(); j++) {
2181 Op op = ops.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002182 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
2183 pw.print(": mode="); pw.print(op.mode);
2184 if (op.time != 0) {
2185 pw.print("; time="); TimeUtils.formatDuration(now-op.time, pw);
2186 pw.print(" ago");
2187 }
2188 if (op.rejectTime != 0) {
2189 pw.print("; rejectTime="); TimeUtils.formatDuration(now-op.rejectTime, pw);
2190 pw.print(" ago");
2191 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002192 if (op.duration == -1) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002193 pw.print(" (running)");
2194 } else if (op.duration != 0) {
2195 pw.print("; duration="); TimeUtils.formatDuration(op.duration, pw);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002196 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002197 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002198 }
2199 }
2200 }
2201 }
2202 }
John Spurlock1af30c72014-03-10 08:33:35 -04002203
2204 private static final class Restriction {
2205 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
2206 int mode;
2207 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
2208 }
Jason Monk62062992014-05-06 09:55:28 -04002209
2210 @Override
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002211 public void setUserRestrictions(Bundle restrictions, IBinder token, int userHandle) {
Jason Monk62062992014-05-06 09:55:28 -04002212 checkSystemUid("setUserRestrictions");
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002213 Preconditions.checkNotNull(restrictions);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002214 Preconditions.checkNotNull(token);
2215 final boolean[] opRestrictions = getOrCreateUserRestrictionsForToken(token, userHandle);
Jason Monk62062992014-05-06 09:55:28 -04002216 for (int i = 0; i < opRestrictions.length; ++i) {
2217 String restriction = AppOpsManager.opToRestriction(i);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002218 final boolean restricted = restriction != null
2219 && restrictions.getBoolean(restriction, false);
2220 setUserRestrictionNoCheck(i, restricted, token, userHandle);
2221 }
2222 }
2223
2224 @Override
Ruben Brunk29931bc2016-03-11 00:24:26 -08002225 public void setUserRestriction(int code, boolean restricted, IBinder token, int userHandle,
2226 String[] exceptionPackages) {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002227 if (Binder.getCallingPid() != Process.myPid()) {
2228 mContext.enforcePermission(Manifest.permission.MANAGE_APP_OPS_RESTRICTIONS,
2229 Binder.getCallingPid(), Binder.getCallingUid(), null);
2230 }
2231 if (userHandle != UserHandle.getCallingUserId()) {
2232 if (mContext.checkCallingOrSelfPermission(Manifest.permission
2233 .INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
2234 && mContext.checkCallingOrSelfPermission(Manifest.permission
2235 .INTERACT_ACROSS_USERS) != PackageManager.PERMISSION_GRANTED) {
2236 throw new SecurityException("Need INTERACT_ACROSS_USERS_FULL or"
2237 + " INTERACT_ACROSS_USERS to interact cross user ");
Jason Monk62062992014-05-06 09:55:28 -04002238 }
2239 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002240 verifyIncomingOp(code);
2241 Preconditions.checkNotNull(token);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002242 setUserRestrictionNoCheck(code, restricted, token, userHandle, exceptionPackages);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002243 }
2244
2245 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
2246 int userHandle) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002247 setUserRestrictionNoCheck(code, restricted, token, userHandle, /*exceptionPackages*/null);
2248 }
2249
2250 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
2251 int userHandle, String[] exceptionPackages) {
2252
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002253 final boolean[] opRestrictions = getOrCreateUserRestrictionsForToken(token, userHandle);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002254
2255 if (restricted) {
2256 final SparseArray<ArraySet<String>> opExceptions =
2257 getUserPackageExemptionsForToken(token, userHandle);
2258
Ruben Brunk29931bc2016-03-11 00:24:26 -08002259 ArraySet<String> exceptions = opExceptions.get(code);
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002260 if (exceptionPackages != null && exceptionPackages.length > 0) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002261 if (exceptions == null) {
2262 exceptions = new ArraySet<>(exceptionPackages.length);
2263 opExceptions.put(code, exceptions);
2264 } else {
2265 exceptions.clear();
2266 }
2267
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002268 for (String p : exceptionPackages) {
2269 exceptions.add(p);
2270 }
2271 } else {
2272 opExceptions.remove(code);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002273 }
2274 }
2275
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002276 if (opRestrictions[code] == restricted) {
2277 return;
2278 }
2279 opRestrictions[code] = restricted;
2280 if (!restricted) {
2281 pruneUserRestrictionsForToken(token, userHandle);
2282 }
2283
Julia Reynoldsbb21c252016-04-05 16:01:49 -04002284 notifyWatchersOfChange(code);
2285 }
2286
2287 private void notifyWatchersOfChange(int code) {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002288 final ArrayList<Callback> clonedCallbacks;
2289 synchronized (this) {
2290 ArrayList<Callback> callbacks = mOpModeWatchers.get(code);
2291 if (callbacks == null) {
2292 return;
2293 }
2294 clonedCallbacks = new ArrayList<>(callbacks);
2295 }
2296
2297 // There are components watching for mode changes such as window manager
2298 // and location manager which are in our process. The callbacks in these
2299 // components may require permissions our remote caller does not have.
2300 final long identity = Binder.clearCallingIdentity();
2301 try {
2302 final int callbackCount = clonedCallbacks.size();
2303 for (int i = 0; i < callbackCount; i++) {
2304 Callback callback = clonedCallbacks.get(i);
2305 try {
2306 callback.mCallback.opChanged(code, -1, null);
2307 } catch (RemoteException e) {
2308 Log.w(TAG, "Error dispatching op op change", e);
2309 }
2310 }
2311 } finally {
2312 Binder.restoreCallingIdentity(identity);
2313 }
Jason Monk62062992014-05-06 09:55:28 -04002314 }
2315
2316 @Override
2317 public void removeUser(int userHandle) throws RemoteException {
2318 checkSystemUid("removeUser");
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002319 final int tokenCount = mOpUserRestrictions.size();
2320 for (int i = tokenCount - 1; i >= 0; i--) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002321 SparseArray<Pair<boolean[], SparseArray<ArraySet<String>>>> opRestrictions =
2322 mOpUserRestrictions.valueAt(i);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002323 if (opRestrictions != null) {
2324 opRestrictions.remove(userHandle);
2325 if (opRestrictions.size() <= 0) {
2326 mOpUserRestrictions.removeAt(i);
2327 }
2328 }
2329 }
2330 }
2331
2332
2333 private void pruneUserRestrictionsForToken(IBinder token, int userHandle) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002334 SparseArray<Pair<boolean[], SparseArray<ArraySet<String>>>> perTokenRestrictions =
2335 mOpUserRestrictions.get(token);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002336 if (perTokenRestrictions != null) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002337 final Pair<boolean[], SparseArray<ArraySet<String>>> restrictions =
2338 perTokenRestrictions.get(userHandle);
2339
2340 if (restrictions != null) {
2341 final boolean[] opRestrictions = restrictions.first;
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002342 final SparseArray<ArraySet<String>> opExceptions = restrictions.second;
2343 boolean stillHasRestrictions = false;
Ruben Brunk29931bc2016-03-11 00:24:26 -08002344 if (opRestrictions != null) {
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002345 for (int i = 0; i < opRestrictions.length; i++) {
2346 boolean restriction = opRestrictions[i];
Ruben Brunk29931bc2016-03-11 00:24:26 -08002347 if (restriction) {
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002348 stillHasRestrictions = true;
2349 } else {
2350 opExceptions.remove(i);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002351 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002352 }
2353 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002354
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002355 if (stillHasRestrictions) {
2356 return;
2357 }
2358
Ruben Brunk29931bc2016-03-11 00:24:26 -08002359 // No restrictions set for this client
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002360 perTokenRestrictions.remove(userHandle);
2361 if (perTokenRestrictions.size() <= 0) {
2362 mOpUserRestrictions.remove(token);
2363 }
2364 }
2365 }
2366 }
2367
Ruben Brunk29931bc2016-03-11 00:24:26 -08002368 /**
2369 * Get or create the user restrictions array for a given client if it doesn't already exist.
2370 *
2371 * @param token the binder client creating the restriction.
2372 * @param userHandle the user handle to create a restriction for.
2373 *
2374 * @return the array of restriction states for each AppOps code.
2375 */
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002376 private boolean[] getOrCreateUserRestrictionsForToken(IBinder token, int userHandle) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002377 SparseArray<Pair<boolean[], SparseArray<ArraySet<String>>>> perTokenRestrictions =
2378 mOpUserRestrictions.get(token);
2379
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002380 if (perTokenRestrictions == null) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002381 perTokenRestrictions =
2382 new SparseArray<Pair<boolean[], SparseArray<ArraySet<String>>>>();
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002383 mOpUserRestrictions.put(token, perTokenRestrictions);
2384 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002385
2386 Pair<boolean[], SparseArray<ArraySet<String>>> restrictions =
2387 perTokenRestrictions.get(userHandle);
2388
2389 if (restrictions == null) {
2390 restrictions = new Pair<boolean[], SparseArray<ArraySet<String>>>(
2391 new boolean[AppOpsManager._NUM_OP], new SparseArray<ArraySet<String>>());
2392 perTokenRestrictions.put(userHandle, restrictions);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002393 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002394
2395 return restrictions.first;
2396 }
2397
2398 /**
2399 * Get the per-package exemptions for each AppOps code for a given client and userHandle.
2400 *
2401 * @param token the binder client to get the exemptions for.
2402 * @param userHandle the user handle to get the exemptions for.
2403 *
2404 * @return a mapping from the AppOps code to a set of packages exempt for that code.
2405 */
2406 private SparseArray<ArraySet<String>> getUserPackageExemptionsForToken(IBinder token,
2407 int userHandle) {
2408 SparseArray<Pair<boolean[], SparseArray<ArraySet<String>>>> perTokenRestrictions =
2409 mOpUserRestrictions.get(token);
2410
2411 if (perTokenRestrictions == null) {
2412 return null; // Don't create user restrictions accidentally
2413 }
2414
2415 Pair<boolean[], SparseArray<ArraySet<String>>> restrictions =
2416 perTokenRestrictions.get(userHandle);
2417
2418 if (restrictions == null) {
2419 return null; // Don't create user restrictions accidentally
2420 }
2421
2422 return restrictions.second;
Jason Monk62062992014-05-06 09:55:28 -04002423 }
2424
2425 private void checkSystemUid(String function) {
2426 int uid = Binder.getCallingUid();
2427 if (uid != Process.SYSTEM_UID) {
2428 throw new SecurityException(function + " must by called by the system");
2429 }
2430 }
2431
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002432 private static String resolvePackageName(int uid, String packageName) {
2433 if (uid == 0) {
2434 return "root";
2435 } else if (uid == Process.SHELL_UID) {
2436 return "com.android.shell";
2437 } else if (uid == Process.SYSTEM_UID && packageName == null) {
2438 return "android";
2439 }
2440 return packageName;
2441 }
2442
Svet Ganov2af57082015-07-30 08:44:20 -07002443 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07002444 String[] packageNames = null;
Svet Ganov2af57082015-07-30 08:44:20 -07002445 try {
riddle_hsu40b300f2015-11-23 13:22:03 +08002446 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -07002447 } catch (RemoteException e) {
2448 /* ignore - local call */
2449 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07002450 if (packageNames == null) {
2451 return EmptyArray.STRING;
2452 }
2453 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07002454 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002455}