blob: 0a2153e9f31beb1f07358c2abfb27d34b3427f3d [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;
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001050 // If there is a non-default per UID policy (we set UID op mode only if
1051 // non-default) it takes over, otherwise use the per package policy.
1052 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -07001053 final int uidMode = uidState.opModes.get(switchCode);
1054 if (uidMode != AppOpsManager.MODE_ALLOWED) {
1055 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1056 + switchCode + " (" + code + ") uid " + uid + " package "
1057 + packageName);
1058 op.rejectTime = System.currentTimeMillis();
1059 return uidMode;
1060 }
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001061 } else {
1062 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
1063 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
1064 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1065 + switchCode + " (" + code + ") uid " + uid + " package "
1066 + packageName);
1067 op.rejectTime = System.currentTimeMillis();
1068 return switchOp.mode;
1069 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001070 }
1071 if (DEBUG) Log.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
1072 + " package " + packageName);
1073 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001074 op.rejectTime = 0;
Svet Ganov99b60432015-06-27 13:15:22 -07001075 op.proxyUid = proxyUid;
1076 op.proxyPackageName = proxyPackageName;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001077 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001078 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001079 }
1080
1081 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001082 public int startOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001083 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001084 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001085 String resolvedPackageName = resolvePackageName(uid, packageName);
1086 if (resolvedPackageName == null) {
1087 return AppOpsManager.MODE_IGNORED;
1088 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001089 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001090 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001091 Ops ops = getOpsRawLocked(uid, resolvedPackageName, true);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001092 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001093 if (DEBUG) Log.d(TAG, "startOperation: no op for code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001094 + " package " + resolvedPackageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001095 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001096 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001097 Op op = getOpLocked(ops, code, true);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001098 if (isOpRestricted(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001099 return AppOpsManager.MODE_IGNORED;
1100 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001101 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001102 UidState uidState = ops.uidState;
1103 if (uidState.opModes != null) {
1104 final int uidMode = uidState.opModes.get(switchCode);
1105 if (uidMode != AppOpsManager.MODE_ALLOWED) {
1106 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1107 + switchCode + " (" + code + ") uid " + uid + " package "
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001108 + resolvedPackageName);
Svet Ganov2af57082015-07-30 08:44:20 -07001109 op.rejectTime = System.currentTimeMillis();
1110 return uidMode;
1111 }
1112 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001113 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
1114 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
1115 if (DEBUG) Log.d(TAG, "startOperation: reject #" + op.mode + " for code "
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001116 + switchCode + " (" + code + ") uid " + uid + " package "
1117 + resolvedPackageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001118 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001119 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001120 }
1121 if (DEBUG) Log.d(TAG, "startOperation: allowing code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001122 + " package " + resolvedPackageName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001123 if (op.nesting == 0) {
1124 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001125 op.rejectTime = 0;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001126 op.duration = -1;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001127 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001128 op.nesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001129 if (client.mStartedOps != null) {
1130 client.mStartedOps.add(op);
1131 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001132 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001133 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001134 }
1135
1136 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001137 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001138 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001139 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001140 String resolvedPackageName = resolvePackageName(uid, packageName);
1141 if (resolvedPackageName == null) {
1142 return;
1143 }
1144 if (!(token instanceof ClientState)) {
1145 return;
1146 }
1147 ClientState client = (ClientState) token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001148 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001149 Op op = getOpLocked(code, uid, resolvedPackageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001150 if (op == null) {
1151 return;
1152 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001153 if (client.mStartedOps != null) {
1154 if (!client.mStartedOps.remove(op)) {
1155 throw new IllegalStateException("Operation not started: uid" + op.uid
1156 + " pkg=" + op.packageName + " op=" + op.op);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001157 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001158 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001159 finishOperationLocked(op);
1160 }
1161 }
1162
Svet Ganovb9d71a62015-04-30 10:38:13 -07001163 @Override
1164 public int permissionToOpCode(String permission) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001165 if (permission == null) {
1166 return AppOpsManager.OP_NONE;
1167 }
Svet Ganovb9d71a62015-04-30 10:38:13 -07001168 return AppOpsManager.permissionToOpCode(permission);
1169 }
1170
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001171 void finishOperationLocked(Op op) {
1172 if (op.nesting <= 1) {
1173 if (op.nesting == 1) {
1174 op.duration = (int)(System.currentTimeMillis() - op.time);
1175 op.time += op.duration;
1176 } else {
1177 Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
1178 + op.packageName + " code " + op.op + " time=" + op.time
1179 + " duration=" + op.duration + " nesting=" + op.nesting);
1180 }
1181 op.nesting = 0;
1182 } else {
1183 op.nesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001184 }
1185 }
1186
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001187 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001188 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001189 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001190 }
1191 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001192 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001193 }
1194 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
1195 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001196 }
1197
Dianne Hackborn961321f2013-02-05 17:22:41 -08001198 private void verifyIncomingOp(int op) {
1199 if (op >= 0 && op < AppOpsManager._NUM_OP) {
1200 return;
1201 }
1202 throw new IllegalArgumentException("Bad operation #" + op);
1203 }
1204
Svet Ganov2af57082015-07-30 08:44:20 -07001205 private UidState getUidStateLocked(int uid, boolean edit) {
1206 UidState uidState = mUidStates.get(uid);
1207 if (uidState == null) {
1208 if (!edit) {
1209 return null;
1210 }
1211 uidState = new UidState(uid);
1212 mUidStates.put(uid, uidState);
1213 }
1214 return uidState;
1215 }
1216
Dianne Hackborn0fcef842014-09-12 15:38:33 -07001217 private Ops getOpsRawLocked(int uid, String packageName, boolean edit) {
Svet Ganov2af57082015-07-30 08:44:20 -07001218 UidState uidState = getUidStateLocked(uid, edit);
1219 if (uidState == null) {
1220 return null;
1221 }
1222
1223 if (uidState.pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001224 if (!edit) {
1225 return null;
1226 }
Svet Ganov2af57082015-07-30 08:44:20 -07001227 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001228 }
Svet Ganov2af57082015-07-30 08:44:20 -07001229
1230 Ops ops = uidState.pkgOps.get(packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001231 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001232 if (!edit) {
1233 return null;
1234 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001235 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001236 // This is the first time we have seen this package name under this uid,
1237 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -08001238 if (uid != 0) {
1239 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001240 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001241 int pkgUid = -1;
1242 try {
Jason Monk1c7c3192014-06-26 12:52:18 -04001243 ApplicationInfo appInfo = ActivityThread.getPackageManager()
Jeff Sharkeycd654482016-01-08 17:42:11 -07001244 .getApplicationInfo(packageName,
1245 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1246 UserHandle.getUserId(uid));
Jason Monk1c7c3192014-06-26 12:52:18 -04001247 if (appInfo != null) {
1248 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001249 isPrivileged = (appInfo.privateFlags
1250 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001251 } else {
1252 if ("media".equals(packageName)) {
1253 pkgUid = Process.MEDIA_UID;
1254 isPrivileged = false;
Andy Hunged0ea402015-10-30 14:11:46 -07001255 } else if ("audioserver".equals(packageName)) {
1256 pkgUid = Process.AUDIOSERVER_UID;
1257 isPrivileged = false;
Chien-Yu Chen75cade02016-01-11 10:56:21 -08001258 } else if ("cameraserver".equals(packageName)) {
1259 pkgUid = Process.CAMERASERVER_UID;
1260 isPrivileged = false;
Jason Monk1c7c3192014-06-26 12:52:18 -04001261 }
Dianne Hackborn713df152013-05-17 11:27:57 -07001262 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001263 } catch (RemoteException e) {
1264 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001265 }
1266 if (pkgUid != uid) {
1267 // Oops! The package name is not valid for the uid they are calling
1268 // under. Abort.
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001269 RuntimeException ex = new RuntimeException("here");
1270 ex.fillInStackTrace();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001271 Slog.w(TAG, "Bad call: specified package " + packageName
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001272 + " under uid " + uid + " but it is really " + pkgUid, ex);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001273 return null;
1274 }
1275 } finally {
1276 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001277 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001278 }
Svet Ganov2af57082015-07-30 08:44:20 -07001279 ops = new Ops(packageName, uidState, isPrivileged);
1280 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001281 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08001282 return ops;
1283 }
1284
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001285 private void scheduleWriteLocked() {
1286 if (!mWriteScheduled) {
1287 mWriteScheduled = true;
1288 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
1289 }
1290 }
1291
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001292 private void scheduleFastWriteLocked() {
1293 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001294 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001295 mFastWriteScheduled = true;
1296 mHandler.removeCallbacks(mWriteRunner);
1297 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001298 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001299 }
1300
Dianne Hackborn72e39832013-01-18 18:36:09 -08001301 private Op getOpLocked(int code, int uid, String packageName, boolean edit) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001302 Ops ops = getOpsRawLocked(uid, packageName, edit);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001303 if (ops == null) {
1304 return null;
1305 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001306 return getOpLocked(ops, code, edit);
1307 }
1308
1309 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001310 Op op = ops.get(code);
1311 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001312 if (!edit) {
1313 return null;
1314 }
Svet Ganov2af57082015-07-30 08:44:20 -07001315 op = new Op(ops.uidState.uid, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001316 ops.put(code, op);
1317 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001318 if (edit) {
1319 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001320 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001321 return op;
1322 }
1323
Jason Monk1c7c3192014-06-26 12:52:18 -04001324 private boolean isOpRestricted(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04001325 int userHandle = UserHandle.getUserId(uid);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001326 final int restrictionSetCount = mOpUserRestrictions.size();
Ruben Brunk29931bc2016-03-11 00:24:26 -08001327
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001328 for (int i = 0; i < restrictionSetCount; i++) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08001329 // For each client, check that the given op is not restricted, or that the given
1330 // package is exempt from the restriction.
1331
1332 SparseArray<Pair<boolean[],SparseArray<ArraySet<String>>>> perUserRestrictions =
1333 mOpUserRestrictions.valueAt(i);
1334
1335 Pair<boolean[],SparseArray<ArraySet<String>>> restrictions =
1336 perUserRestrictions.get(userHandle);
1337 if (restrictions == null) {
1338 continue; // No restrictions set by this client
1339 }
1340
1341 boolean[] opRestrictions = restrictions.first;
1342 SparseArray<ArraySet<String>> opExceptions = restrictions.second;
1343
1344 if (opRestrictions == null) {
1345 continue; // No restrictions set by this client
1346 }
1347
1348 if (opRestrictions[code]) {
Ruben Brunk32f0fa42016-03-11 19:07:07 -08001349
1350 if (opExceptions != null) {
1351 ArraySet<String> ex = opExceptions.get(code);
1352 if (ex != null && ex.contains(packageName)) {
1353 continue; // AppOps code is restricted, but this package is exempt
1354 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08001355 }
1356
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001357 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08001358 // If we are the system, bypass user restrictions for certain codes
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001359 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001360 Ops ops = getOpsRawLocked(uid, packageName, true);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001361 if ((ops != null) && ops.isPrivileged) {
1362 return false;
1363 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001364 }
1365 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08001366
Svet Ganov9cea80cd2016-02-16 11:47:00 -08001367 return true;
Jason Monk1c7c3192014-06-26 12:52:18 -04001368 }
Jason Monk62062992014-05-06 09:55:28 -04001369 }
1370 return false;
1371 }
1372
Dianne Hackborn35654b62013-01-14 17:38:02 -08001373 void readState() {
1374 synchronized (mFile) {
1375 synchronized (this) {
1376 FileInputStream stream;
1377 try {
1378 stream = mFile.openRead();
1379 } catch (FileNotFoundException e) {
1380 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
1381 return;
1382 }
1383 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001384 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001385 try {
1386 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001387 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001388 int type;
1389 while ((type = parser.next()) != XmlPullParser.START_TAG
1390 && type != XmlPullParser.END_DOCUMENT) {
1391 ;
1392 }
1393
1394 if (type != XmlPullParser.START_TAG) {
1395 throw new IllegalStateException("no start tag found");
1396 }
1397
1398 int outerDepth = parser.getDepth();
1399 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1400 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1401 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1402 continue;
1403 }
1404
1405 String tagName = parser.getName();
1406 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001407 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07001408 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07001409 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001410 } else {
1411 Slog.w(TAG, "Unknown element under <app-ops>: "
1412 + parser.getName());
1413 XmlUtils.skipCurrentTag(parser);
1414 }
1415 }
1416 success = true;
1417 } catch (IllegalStateException e) {
1418 Slog.w(TAG, "Failed parsing " + e);
1419 } catch (NullPointerException e) {
1420 Slog.w(TAG, "Failed parsing " + e);
1421 } catch (NumberFormatException e) {
1422 Slog.w(TAG, "Failed parsing " + e);
1423 } catch (XmlPullParserException e) {
1424 Slog.w(TAG, "Failed parsing " + e);
1425 } catch (IOException e) {
1426 Slog.w(TAG, "Failed parsing " + e);
1427 } catch (IndexOutOfBoundsException e) {
1428 Slog.w(TAG, "Failed parsing " + e);
1429 } finally {
1430 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07001431 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001432 }
1433 try {
1434 stream.close();
1435 } catch (IOException e) {
1436 }
1437 }
1438 }
1439 }
1440 }
1441
Svet Ganov2af57082015-07-30 08:44:20 -07001442 void readUidOps(XmlPullParser parser) throws NumberFormatException,
1443 XmlPullParserException, IOException {
1444 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
1445 int outerDepth = parser.getDepth();
1446 int type;
1447 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1448 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1449 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1450 continue;
1451 }
1452
1453 String tagName = parser.getName();
1454 if (tagName.equals("op")) {
1455 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
1456 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
1457 UidState uidState = getUidStateLocked(uid, true);
1458 if (uidState.opModes == null) {
1459 uidState.opModes = new SparseIntArray();
1460 }
1461 uidState.opModes.put(code, mode);
1462 } else {
1463 Slog.w(TAG, "Unknown element under <uid-ops>: "
1464 + parser.getName());
1465 XmlUtils.skipCurrentTag(parser);
1466 }
1467 }
1468 }
1469
Dave Burke0997c5bd2013-08-02 20:25:02 +00001470 void readPackage(XmlPullParser parser) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001471 XmlPullParserException, IOException {
1472 String pkgName = parser.getAttributeValue(null, "n");
1473 int outerDepth = parser.getDepth();
1474 int type;
1475 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1476 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1477 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1478 continue;
1479 }
1480
1481 String tagName = parser.getName();
1482 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001483 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001484 } else {
1485 Slog.w(TAG, "Unknown element under <pkg>: "
1486 + parser.getName());
1487 XmlUtils.skipCurrentTag(parser);
1488 }
1489 }
1490 }
1491
Dave Burke0997c5bd2013-08-02 20:25:02 +00001492 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001493 XmlPullParserException, IOException {
1494 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Jason Monk1c7c3192014-06-26 12:52:18 -04001495 String isPrivilegedString = parser.getAttributeValue(null, "p");
1496 boolean isPrivileged = false;
1497 if (isPrivilegedString == null) {
1498 try {
1499 IPackageManager packageManager = ActivityThread.getPackageManager();
1500 if (packageManager != null) {
1501 ApplicationInfo appInfo = ActivityThread.getPackageManager()
1502 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
1503 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001504 isPrivileged = (appInfo.privateFlags
1505 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001506 }
1507 } else {
1508 // Could not load data, don't add to cache so it will be loaded later.
1509 return;
1510 }
1511 } catch (RemoteException e) {
1512 Slog.w(TAG, "Could not contact PackageManager", e);
1513 }
1514 } else {
1515 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
1516 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001517 int outerDepth = parser.getDepth();
1518 int type;
1519 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1520 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1521 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1522 continue;
1523 }
1524
1525 String tagName = parser.getName();
1526 if (tagName.equals("op")) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001527 Op op = new Op(uid, pkgName, Integer.parseInt(parser.getAttributeValue(null, "n")));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001528 String mode = parser.getAttributeValue(null, "m");
1529 if (mode != null) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001530 op.mode = Integer.parseInt(mode);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001531 }
1532 String time = parser.getAttributeValue(null, "t");
1533 if (time != null) {
1534 op.time = Long.parseLong(time);
1535 }
1536 time = parser.getAttributeValue(null, "r");
1537 if (time != null) {
1538 op.rejectTime = Long.parseLong(time);
1539 }
1540 String dur = parser.getAttributeValue(null, "d");
1541 if (dur != null) {
1542 op.duration = Integer.parseInt(dur);
1543 }
Svet Ganov99b60432015-06-27 13:15:22 -07001544 String proxyUid = parser.getAttributeValue(null, "pu");
1545 if (proxyUid != null) {
1546 op.proxyUid = Integer.parseInt(proxyUid);
1547 }
1548 String proxyPackageName = parser.getAttributeValue(null, "pp");
1549 if (proxyPackageName != null) {
1550 op.proxyPackageName = proxyPackageName;
1551 }
Svet Ganov2af57082015-07-30 08:44:20 -07001552
1553 UidState uidState = getUidStateLocked(uid, true);
1554 if (uidState.pkgOps == null) {
1555 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001556 }
Svet Ganov2af57082015-07-30 08:44:20 -07001557
1558 Ops ops = uidState.pkgOps.get(pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001559 if (ops == null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001560 ops = new Ops(pkgName, uidState, isPrivileged);
1561 uidState.pkgOps.put(pkgName, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001562 }
1563 ops.put(op.op, op);
1564 } else {
1565 Slog.w(TAG, "Unknown element under <pkg>: "
1566 + parser.getName());
1567 XmlUtils.skipCurrentTag(parser);
1568 }
1569 }
1570 }
1571
1572 void writeState() {
1573 synchronized (mFile) {
1574 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
1575
1576 FileOutputStream stream;
1577 try {
1578 stream = mFile.startWrite();
1579 } catch (IOException e) {
1580 Slog.w(TAG, "Failed to write state: " + e);
1581 return;
1582 }
1583
1584 try {
1585 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001586 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001587 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001588 out.startTag(null, "app-ops");
Svet Ganov2af57082015-07-30 08:44:20 -07001589
1590 final int uidStateCount = mUidStates.size();
1591 for (int i = 0; i < uidStateCount; i++) {
1592 UidState uidState = mUidStates.valueAt(i);
1593 if (uidState.opModes != null && uidState.opModes.size() > 0) {
1594 out.startTag(null, "uid");
1595 out.attribute(null, "n", Integer.toString(uidState.uid));
1596 SparseIntArray uidOpModes = uidState.opModes;
1597 final int opCount = uidOpModes.size();
1598 for (int j = 0; j < opCount; j++) {
1599 final int op = uidOpModes.keyAt(j);
1600 final int mode = uidOpModes.valueAt(j);
1601 out.startTag(null, "op");
1602 out.attribute(null, "n", Integer.toString(op));
1603 out.attribute(null, "m", Integer.toString(mode));
1604 out.endTag(null, "op");
1605 }
1606 out.endTag(null, "uid");
1607 }
1608 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001609
1610 if (allOps != null) {
1611 String lastPkg = null;
1612 for (int i=0; i<allOps.size(); i++) {
1613 AppOpsManager.PackageOps pkg = allOps.get(i);
1614 if (!pkg.getPackageName().equals(lastPkg)) {
1615 if (lastPkg != null) {
1616 out.endTag(null, "pkg");
1617 }
1618 lastPkg = pkg.getPackageName();
1619 out.startTag(null, "pkg");
1620 out.attribute(null, "n", lastPkg);
1621 }
1622 out.startTag(null, "uid");
1623 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04001624 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001625 Ops ops = getOpsRawLocked(pkg.getUid(), pkg.getPackageName(), false);
Jason Monk1c7c3192014-06-26 12:52:18 -04001626 // Should always be present as the list of PackageOps is generated
1627 // from Ops.
1628 if (ops != null) {
1629 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
1630 } else {
1631 out.attribute(null, "p", Boolean.toString(false));
1632 }
1633 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001634 List<AppOpsManager.OpEntry> ops = pkg.getOps();
1635 for (int j=0; j<ops.size(); j++) {
1636 AppOpsManager.OpEntry op = ops.get(j);
1637 out.startTag(null, "op");
1638 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07001639 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001640 out.attribute(null, "m", Integer.toString(op.getMode()));
1641 }
1642 long time = op.getTime();
1643 if (time != 0) {
1644 out.attribute(null, "t", Long.toString(time));
1645 }
1646 time = op.getRejectTime();
1647 if (time != 0) {
1648 out.attribute(null, "r", Long.toString(time));
1649 }
1650 int dur = op.getDuration();
1651 if (dur != 0) {
1652 out.attribute(null, "d", Integer.toString(dur));
1653 }
Svet Ganov99b60432015-06-27 13:15:22 -07001654 int proxyUid = op.getProxyUid();
1655 if (proxyUid != -1) {
1656 out.attribute(null, "pu", Integer.toString(proxyUid));
1657 }
1658 String proxyPackageName = op.getProxyPackageName();
1659 if (proxyPackageName != null) {
1660 out.attribute(null, "pp", proxyPackageName);
1661 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001662 out.endTag(null, "op");
1663 }
1664 out.endTag(null, "uid");
1665 }
1666 if (lastPkg != null) {
1667 out.endTag(null, "pkg");
1668 }
1669 }
1670
1671 out.endTag(null, "app-ops");
1672 out.endDocument();
1673 mFile.finishWrite(stream);
1674 } catch (IOException e) {
1675 Slog.w(TAG, "Failed to write state, restoring backup.", e);
1676 mFile.failWrite(stream);
1677 }
1678 }
1679 }
1680
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001681 static class Shell extends ShellCommand {
1682 final IAppOpsService mInterface;
1683 final AppOpsService mInternal;
1684
1685 int userId = UserHandle.USER_SYSTEM;
1686 String packageName;
1687 String opStr;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001688 String modeStr;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001689 int op;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001690 int mode;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001691 int packageUid;
1692
1693 Shell(IAppOpsService iface, AppOpsService internal) {
1694 mInterface = iface;
1695 mInternal = internal;
1696 }
1697
1698 @Override
1699 public int onCommand(String cmd) {
1700 return onShellCommand(this, cmd);
1701 }
1702
1703 @Override
1704 public void onHelp() {
1705 PrintWriter pw = getOutPrintWriter();
1706 dumpCommandHelp(pw);
1707 }
1708
1709 private int strOpToOp(String op, PrintWriter err) {
1710 try {
1711 return AppOpsManager.strOpToOp(op);
1712 } catch (IllegalArgumentException e) {
1713 }
1714 try {
1715 return Integer.parseInt(op);
1716 } catch (NumberFormatException e) {
1717 }
1718 try {
1719 return AppOpsManager.strDebugOpToOp(op);
1720 } catch (IllegalArgumentException e) {
1721 err.println("Error: " + e.getMessage());
1722 return -1;
1723 }
1724 }
1725
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001726 int strModeToMode(String modeStr, PrintWriter err) {
1727 switch (modeStr) {
1728 case "allow":
1729 return AppOpsManager.MODE_ALLOWED;
1730 case "deny":
1731 return AppOpsManager.MODE_ERRORED;
1732 case "ignore":
1733 return AppOpsManager.MODE_IGNORED;
1734 case "default":
1735 return AppOpsManager.MODE_DEFAULT;
1736 }
1737 try {
1738 return Integer.parseInt(modeStr);
1739 } catch (NumberFormatException e) {
1740 }
1741 err.println("Error: Mode " + modeStr + " is not valid");
1742 return -1;
1743 }
1744
1745 int parseUserOpMode(int defMode, PrintWriter err) throws RemoteException {
1746 userId = UserHandle.USER_CURRENT;
1747 opStr = null;
1748 modeStr = null;
1749 for (String argument; (argument = getNextArg()) != null;) {
1750 if ("--user".equals(argument)) {
1751 userId = UserHandle.parseUserArg(getNextArgRequired());
1752 } else {
1753 if (opStr == null) {
1754 opStr = argument;
1755 } else if (modeStr == null) {
1756 modeStr = argument;
1757 break;
1758 }
1759 }
1760 }
1761 if (opStr == null) {
1762 err.println("Error: Operation not specified.");
1763 return -1;
1764 }
1765 op = strOpToOp(opStr, err);
1766 if (op < 0) {
1767 return -1;
1768 }
1769 if (modeStr != null) {
1770 if ((mode=strModeToMode(modeStr, err)) < 0) {
1771 return -1;
1772 }
1773 } else {
1774 mode = defMode;
1775 }
1776 return 0;
1777 }
1778
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001779 int parseUserPackageOp(boolean reqOp, PrintWriter err) throws RemoteException {
1780 userId = UserHandle.USER_CURRENT;
1781 packageName = null;
1782 opStr = null;
1783 for (String argument; (argument = getNextArg()) != null;) {
1784 if ("--user".equals(argument)) {
1785 userId = UserHandle.parseUserArg(getNextArgRequired());
1786 } else {
1787 if (packageName == null) {
1788 packageName = argument;
1789 } else if (opStr == null) {
1790 opStr = argument;
1791 break;
1792 }
1793 }
1794 }
1795 if (packageName == null) {
1796 err.println("Error: Package name not specified.");
1797 return -1;
1798 } else if (opStr == null && reqOp) {
1799 err.println("Error: Operation not specified.");
1800 return -1;
1801 }
1802 if (opStr != null) {
1803 op = strOpToOp(opStr, err);
1804 if (op < 0) {
1805 return -1;
1806 }
1807 } else {
1808 op = AppOpsManager.OP_NONE;
1809 }
1810 if (userId == UserHandle.USER_CURRENT) {
1811 userId = ActivityManager.getCurrentUser();
1812 }
1813 if ("root".equals(packageName)) {
1814 packageUid = 0;
1815 } else {
Jeff Sharkeycd654482016-01-08 17:42:11 -07001816 packageUid = AppGlobals.getPackageManager().getPackageUid(packageName,
1817 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001818 }
1819 if (packageUid < 0) {
1820 err.println("Error: No UID for " + packageName + " in user " + userId);
1821 return -1;
1822 }
1823 return 0;
1824 }
1825 }
1826
1827 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
1828 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
1829 (new Shell(this, this)).exec(this, in, out, err, args, resultReceiver);
1830 }
1831
1832 static void dumpCommandHelp(PrintWriter pw) {
1833 pw.println("AppOps service (appops) commands:");
1834 pw.println(" help");
1835 pw.println(" Print this help text.");
1836 pw.println(" set [--user <USER_ID>] <PACKAGE> <OP> <MODE>");
1837 pw.println(" Set the mode for a particular application and operation.");
1838 pw.println(" get [--user <USER_ID>] <PACKAGE> [<OP>]");
1839 pw.println(" Return the mode for a particular application and optional operation.");
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001840 pw.println(" query-op [--user <USER_ID>] <OP> [<MODE>]");
1841 pw.println(" Print all packages that currently have the given op in the given mode.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001842 pw.println(" reset [--user <USER_ID>] [<PACKAGE>]");
1843 pw.println(" Reset the given application or all applications to default modes.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001844 pw.println(" write-settings");
1845 pw.println(" Immediately write pending changes to storage.");
1846 pw.println(" read-settings");
1847 pw.println(" Read the last written settings, replacing current state in RAM.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001848 pw.println(" options:");
1849 pw.println(" <PACKAGE> an Android package name.");
1850 pw.println(" <OP> an AppOps operation.");
1851 pw.println(" <MODE> one of allow, ignore, deny, or default");
1852 pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
1853 pw.println(" specified, the current user is assumed.");
1854 }
1855
1856 static int onShellCommand(Shell shell, String cmd) {
1857 if (cmd == null) {
1858 return shell.handleDefaultCommands(cmd);
1859 }
1860 PrintWriter pw = shell.getOutPrintWriter();
1861 PrintWriter err = shell.getErrPrintWriter();
1862 try {
1863 switch (cmd) {
1864 case "set": {
1865 int res = shell.parseUserPackageOp(true, err);
1866 if (res < 0) {
1867 return res;
1868 }
1869 String modeStr = shell.getNextArg();
1870 if (modeStr == null) {
1871 err.println("Error: Mode not specified.");
1872 return -1;
1873 }
1874
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001875 final int mode = shell.strModeToMode(modeStr, err);
1876 if (mode < 0) {
1877 return -1;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001878 }
1879
1880 shell.mInterface.setMode(shell.op, shell.packageUid, shell.packageName, mode);
1881 return 0;
1882 }
1883 case "get": {
1884 int res = shell.parseUserPackageOp(false, err);
1885 if (res < 0) {
1886 return res;
1887 }
1888
1889 List<AppOpsManager.PackageOps> ops = shell.mInterface.getOpsForPackage(
1890 shell.packageUid, shell.packageName,
1891 shell.op != AppOpsManager.OP_NONE ? new int[] {shell.op} : null);
1892 if (ops == null || ops.size() <= 0) {
1893 pw.println("No operations.");
1894 return 0;
1895 }
1896 final long now = System.currentTimeMillis();
1897 for (int i=0; i<ops.size(); i++) {
1898 List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
1899 for (int j=0; j<entries.size(); j++) {
1900 AppOpsManager.OpEntry ent = entries.get(j);
1901 pw.print(AppOpsManager.opToName(ent.getOp()));
1902 pw.print(": ");
1903 switch (ent.getMode()) {
1904 case AppOpsManager.MODE_ALLOWED:
1905 pw.print("allow");
1906 break;
1907 case AppOpsManager.MODE_IGNORED:
1908 pw.print("ignore");
1909 break;
1910 case AppOpsManager.MODE_ERRORED:
1911 pw.print("deny");
1912 break;
1913 case AppOpsManager.MODE_DEFAULT:
1914 pw.print("default");
1915 break;
1916 default:
1917 pw.print("mode=");
1918 pw.print(ent.getMode());
1919 break;
1920 }
1921 if (ent.getTime() != 0) {
1922 pw.print("; time=");
1923 TimeUtils.formatDuration(now - ent.getTime(), pw);
1924 pw.print(" ago");
1925 }
1926 if (ent.getRejectTime() != 0) {
1927 pw.print("; rejectTime=");
1928 TimeUtils.formatDuration(now - ent.getRejectTime(), pw);
1929 pw.print(" ago");
1930 }
1931 if (ent.getDuration() == -1) {
1932 pw.print(" (running)");
1933 } else if (ent.getDuration() != 0) {
1934 pw.print("; duration=");
1935 TimeUtils.formatDuration(ent.getDuration(), pw);
1936 }
1937 pw.println();
1938 }
1939 }
1940 return 0;
1941 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07001942 case "query-op": {
1943 int res = shell.parseUserOpMode(AppOpsManager.MODE_IGNORED, err);
1944 if (res < 0) {
1945 return res;
1946 }
1947 List<AppOpsManager.PackageOps> ops = shell.mInterface.getPackagesForOps(
1948 new int[] {shell.op});
1949 if (ops == null || ops.size() <= 0) {
1950 pw.println("No operations.");
1951 return 0;
1952 }
1953 for (int i=0; i<ops.size(); i++) {
1954 final AppOpsManager.PackageOps pkg = ops.get(i);
1955 boolean hasMatch = false;
1956 final List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
1957 for (int j=0; j<entries.size(); j++) {
1958 AppOpsManager.OpEntry ent = entries.get(j);
1959 if (ent.getOp() == shell.op && ent.getMode() == shell.mode) {
1960 hasMatch = true;
1961 break;
1962 }
1963 }
1964 if (hasMatch) {
1965 pw.println(pkg.getPackageName());
1966 }
1967 }
1968 return 0;
1969 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08001970 case "reset": {
1971 String packageName = null;
1972 int userId = UserHandle.USER_CURRENT;
1973 for (String argument; (argument = shell.getNextArg()) != null;) {
1974 if ("--user".equals(argument)) {
1975 String userStr = shell.getNextArgRequired();
1976 userId = UserHandle.parseUserArg(userStr);
1977 } else {
1978 if (packageName == null) {
1979 packageName = argument;
1980 } else {
1981 err.println("Error: Unsupported argument: " + argument);
1982 return -1;
1983 }
1984 }
1985 }
1986
1987 if (userId == UserHandle.USER_CURRENT) {
1988 userId = ActivityManager.getCurrentUser();
1989 }
1990
1991 shell.mInterface.resetAllModes(userId, packageName);
1992 pw.print("Reset all modes for: ");
1993 if (userId == UserHandle.USER_ALL) {
1994 pw.print("all users");
1995 } else {
1996 pw.print("user "); pw.print(userId);
1997 }
1998 pw.print(", ");
1999 if (packageName == null) {
2000 pw.println("all packages");
2001 } else {
2002 pw.print("package "); pw.println(packageName);
2003 }
2004 return 0;
2005 }
2006 case "write-settings": {
2007 shell.mInternal.mContext.enforcePermission(
2008 android.Manifest.permission.UPDATE_APP_OPS_STATS,
2009 Binder.getCallingPid(), Binder.getCallingUid(), null);
2010 long token = Binder.clearCallingIdentity();
2011 try {
2012 synchronized (shell.mInternal) {
2013 shell.mInternal.mHandler.removeCallbacks(shell.mInternal.mWriteRunner);
2014 }
2015 shell.mInternal.writeState();
2016 pw.println("Current settings written.");
2017 } finally {
2018 Binder.restoreCallingIdentity(token);
2019 }
2020 return 0;
2021 }
2022 case "read-settings": {
2023 shell.mInternal.mContext.enforcePermission(
2024 android.Manifest.permission.UPDATE_APP_OPS_STATS,
2025 Binder.getCallingPid(), Binder.getCallingUid(), null);
2026 long token = Binder.clearCallingIdentity();
2027 try {
2028 shell.mInternal.readState();
2029 pw.println("Last settings read.");
2030 } finally {
2031 Binder.restoreCallingIdentity(token);
2032 }
2033 return 0;
2034 }
2035 default:
2036 return shell.handleDefaultCommands(cmd);
2037 }
2038 } catch (RemoteException e) {
2039 pw.println("Remote exception: " + e);
2040 }
2041 return -1;
2042 }
2043
2044 private void dumpHelp(PrintWriter pw) {
2045 pw.println("AppOps service (appops) dump options:");
2046 pw.println(" none");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002047 }
2048
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002049 @Override
2050 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2051 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2052 != PackageManager.PERMISSION_GRANTED) {
2053 pw.println("Permission Denial: can't dump ApOps service from from pid="
2054 + Binder.getCallingPid()
2055 + ", uid=" + Binder.getCallingUid());
2056 return;
2057 }
2058
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002059 if (args != null) {
2060 for (int i=0; i<args.length; i++) {
2061 String arg = args[i];
2062 if ("-h".equals(arg)) {
2063 dumpHelp(pw);
2064 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07002065 } else if ("-a".equals(arg)) {
2066 // dump all data
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002067 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
2068 pw.println("Unknown option: " + arg);
2069 return;
2070 } else {
2071 pw.println("Unknown command: " + arg);
2072 return;
2073 }
2074 }
2075 }
2076
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002077 synchronized (this) {
2078 pw.println("Current AppOps Service state:");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002079 final long now = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002080 boolean needSep = false;
2081 if (mOpModeWatchers.size() > 0) {
2082 needSep = true;
2083 pw.println(" Op mode watchers:");
2084 for (int i=0; i<mOpModeWatchers.size(); i++) {
2085 pw.print(" Op "); pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
2086 pw.println(":");
2087 ArrayList<Callback> callbacks = mOpModeWatchers.valueAt(i);
2088 for (int j=0; j<callbacks.size(); j++) {
2089 pw.print(" #"); pw.print(j); pw.print(": ");
2090 pw.println(callbacks.get(j));
2091 }
2092 }
2093 }
2094 if (mPackageModeWatchers.size() > 0) {
2095 needSep = true;
2096 pw.println(" Package mode watchers:");
2097 for (int i=0; i<mPackageModeWatchers.size(); i++) {
2098 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
2099 pw.println(":");
2100 ArrayList<Callback> callbacks = mPackageModeWatchers.valueAt(i);
2101 for (int j=0; j<callbacks.size(); j++) {
2102 pw.print(" #"); pw.print(j); pw.print(": ");
2103 pw.println(callbacks.get(j));
2104 }
2105 }
2106 }
2107 if (mModeWatchers.size() > 0) {
2108 needSep = true;
2109 pw.println(" All mode watchers:");
2110 for (int i=0; i<mModeWatchers.size(); i++) {
2111 pw.print(" "); pw.print(mModeWatchers.keyAt(i));
2112 pw.print(" -> "); pw.println(mModeWatchers.valueAt(i));
2113 }
2114 }
2115 if (mClients.size() > 0) {
2116 needSep = true;
2117 pw.println(" Clients:");
2118 for (int i=0; i<mClients.size(); i++) {
2119 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
2120 ClientState cs = mClients.valueAt(i);
2121 pw.print(" "); pw.println(cs);
2122 if (cs.mStartedOps != null && cs.mStartedOps.size() > 0) {
2123 pw.println(" Started ops:");
2124 for (int j=0; j<cs.mStartedOps.size(); j++) {
2125 Op op = cs.mStartedOps.get(j);
2126 pw.print(" "); pw.print("uid="); pw.print(op.uid);
2127 pw.print(" pkg="); pw.print(op.packageName);
2128 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
2129 }
2130 }
2131 }
2132 }
John Spurlock1af30c72014-03-10 08:33:35 -04002133 if (mAudioRestrictions.size() > 0) {
2134 boolean printedHeader = false;
2135 for (int o=0; o<mAudioRestrictions.size(); o++) {
2136 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
2137 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
2138 for (int i=0; i<restrictions.size(); i++) {
2139 if (!printedHeader){
2140 pw.println(" Audio Restrictions:");
2141 printedHeader = true;
2142 needSep = true;
2143 }
John Spurlock7b414672014-07-18 13:02:39 -04002144 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04002145 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04002146 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04002147 Restriction r = restrictions.valueAt(i);
2148 pw.print(": mode="); pw.println(r.mode);
2149 if (!r.exceptionPackages.isEmpty()) {
2150 pw.println(" Exceptions:");
2151 for (int j=0; j<r.exceptionPackages.size(); j++) {
2152 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
2153 }
2154 }
2155 }
2156 }
2157 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002158 if (needSep) {
2159 pw.println();
2160 }
Svet Ganov2af57082015-07-30 08:44:20 -07002161 for (int i=0; i<mUidStates.size(); i++) {
2162 UidState uidState = mUidStates.valueAt(i);
2163
2164 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
2165
2166 SparseIntArray opModes = uidState.opModes;
2167 if (opModes != null) {
2168 final int opModeCount = opModes.size();
2169 for (int j = 0; j < opModeCount; j++) {
2170 final int code = opModes.keyAt(j);
2171 final int mode = opModes.valueAt(j);
2172 pw.print(" "); pw.print(AppOpsManager.opToName(code));
2173 pw.print(": mode="); pw.println(mode);
2174 }
2175 }
2176
2177 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
2178 if (pkgOps == null) {
2179 continue;
2180 }
2181
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002182 for (Ops ops : pkgOps.values()) {
2183 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
2184 for (int j=0; j<ops.size(); j++) {
2185 Op op = ops.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002186 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
2187 pw.print(": mode="); pw.print(op.mode);
2188 if (op.time != 0) {
2189 pw.print("; time="); TimeUtils.formatDuration(now-op.time, pw);
2190 pw.print(" ago");
2191 }
2192 if (op.rejectTime != 0) {
2193 pw.print("; rejectTime="); TimeUtils.formatDuration(now-op.rejectTime, pw);
2194 pw.print(" ago");
2195 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002196 if (op.duration == -1) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002197 pw.print(" (running)");
2198 } else if (op.duration != 0) {
2199 pw.print("; duration="); TimeUtils.formatDuration(op.duration, pw);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002200 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002201 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002202 }
2203 }
2204 }
2205 }
2206 }
John Spurlock1af30c72014-03-10 08:33:35 -04002207
2208 private static final class Restriction {
2209 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
2210 int mode;
2211 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
2212 }
Jason Monk62062992014-05-06 09:55:28 -04002213
2214 @Override
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002215 public void setUserRestrictions(Bundle restrictions, IBinder token, int userHandle) {
Jason Monk62062992014-05-06 09:55:28 -04002216 checkSystemUid("setUserRestrictions");
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002217 Preconditions.checkNotNull(restrictions);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002218 Preconditions.checkNotNull(token);
2219 final boolean[] opRestrictions = getOrCreateUserRestrictionsForToken(token, userHandle);
Jason Monk62062992014-05-06 09:55:28 -04002220 for (int i = 0; i < opRestrictions.length; ++i) {
2221 String restriction = AppOpsManager.opToRestriction(i);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002222 final boolean restricted = restriction != null
2223 && restrictions.getBoolean(restriction, false);
2224 setUserRestrictionNoCheck(i, restricted, token, userHandle);
2225 }
2226 }
2227
2228 @Override
Ruben Brunk29931bc2016-03-11 00:24:26 -08002229 public void setUserRestriction(int code, boolean restricted, IBinder token, int userHandle,
2230 String[] exceptionPackages) {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002231 if (Binder.getCallingPid() != Process.myPid()) {
2232 mContext.enforcePermission(Manifest.permission.MANAGE_APP_OPS_RESTRICTIONS,
2233 Binder.getCallingPid(), Binder.getCallingUid(), null);
2234 }
2235 if (userHandle != UserHandle.getCallingUserId()) {
2236 if (mContext.checkCallingOrSelfPermission(Manifest.permission
2237 .INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
2238 && mContext.checkCallingOrSelfPermission(Manifest.permission
2239 .INTERACT_ACROSS_USERS) != PackageManager.PERMISSION_GRANTED) {
2240 throw new SecurityException("Need INTERACT_ACROSS_USERS_FULL or"
2241 + " INTERACT_ACROSS_USERS to interact cross user ");
Jason Monk62062992014-05-06 09:55:28 -04002242 }
2243 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002244 verifyIncomingOp(code);
2245 Preconditions.checkNotNull(token);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002246 setUserRestrictionNoCheck(code, restricted, token, userHandle, exceptionPackages);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002247 }
2248
2249 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
2250 int userHandle) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002251 setUserRestrictionNoCheck(code, restricted, token, userHandle, /*exceptionPackages*/null);
2252 }
2253
2254 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
2255 int userHandle, String[] exceptionPackages) {
2256
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002257 final boolean[] opRestrictions = getOrCreateUserRestrictionsForToken(token, userHandle);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002258
2259 if (restricted) {
2260 final SparseArray<ArraySet<String>> opExceptions =
2261 getUserPackageExemptionsForToken(token, userHandle);
2262
Ruben Brunk29931bc2016-03-11 00:24:26 -08002263 ArraySet<String> exceptions = opExceptions.get(code);
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002264 if (exceptionPackages != null && exceptionPackages.length > 0) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002265 if (exceptions == null) {
2266 exceptions = new ArraySet<>(exceptionPackages.length);
2267 opExceptions.put(code, exceptions);
2268 } else {
2269 exceptions.clear();
2270 }
2271
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002272 for (String p : exceptionPackages) {
2273 exceptions.add(p);
2274 }
2275 } else {
2276 opExceptions.remove(code);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002277 }
2278 }
2279
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002280 if (opRestrictions[code] == restricted) {
2281 return;
2282 }
2283 opRestrictions[code] = restricted;
2284 if (!restricted) {
2285 pruneUserRestrictionsForToken(token, userHandle);
2286 }
2287
Julia Reynoldsbb21c252016-04-05 16:01:49 -04002288 notifyWatchersOfChange(code);
2289 }
2290
2291 private void notifyWatchersOfChange(int code) {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002292 final ArrayList<Callback> clonedCallbacks;
2293 synchronized (this) {
2294 ArrayList<Callback> callbacks = mOpModeWatchers.get(code);
2295 if (callbacks == null) {
2296 return;
2297 }
2298 clonedCallbacks = new ArrayList<>(callbacks);
2299 }
2300
2301 // There are components watching for mode changes such as window manager
2302 // and location manager which are in our process. The callbacks in these
2303 // components may require permissions our remote caller does not have.
2304 final long identity = Binder.clearCallingIdentity();
2305 try {
2306 final int callbackCount = clonedCallbacks.size();
2307 for (int i = 0; i < callbackCount; i++) {
2308 Callback callback = clonedCallbacks.get(i);
2309 try {
2310 callback.mCallback.opChanged(code, -1, null);
2311 } catch (RemoteException e) {
2312 Log.w(TAG, "Error dispatching op op change", e);
2313 }
2314 }
2315 } finally {
2316 Binder.restoreCallingIdentity(identity);
2317 }
Jason Monk62062992014-05-06 09:55:28 -04002318 }
2319
2320 @Override
2321 public void removeUser(int userHandle) throws RemoteException {
2322 checkSystemUid("removeUser");
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002323 final int tokenCount = mOpUserRestrictions.size();
2324 for (int i = tokenCount - 1; i >= 0; i--) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002325 SparseArray<Pair<boolean[], SparseArray<ArraySet<String>>>> opRestrictions =
2326 mOpUserRestrictions.valueAt(i);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002327 if (opRestrictions != null) {
2328 opRestrictions.remove(userHandle);
2329 if (opRestrictions.size() <= 0) {
2330 mOpUserRestrictions.removeAt(i);
2331 }
2332 }
2333 }
2334 }
2335
2336
2337 private void pruneUserRestrictionsForToken(IBinder token, int userHandle) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002338 SparseArray<Pair<boolean[], SparseArray<ArraySet<String>>>> perTokenRestrictions =
2339 mOpUserRestrictions.get(token);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002340 if (perTokenRestrictions != null) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002341 final Pair<boolean[], SparseArray<ArraySet<String>>> restrictions =
2342 perTokenRestrictions.get(userHandle);
2343
2344 if (restrictions != null) {
2345 final boolean[] opRestrictions = restrictions.first;
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002346 final SparseArray<ArraySet<String>> opExceptions = restrictions.second;
2347 boolean stillHasRestrictions = false;
Ruben Brunk29931bc2016-03-11 00:24:26 -08002348 if (opRestrictions != null) {
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002349 for (int i = 0; i < opRestrictions.length; i++) {
2350 boolean restriction = opRestrictions[i];
Ruben Brunk29931bc2016-03-11 00:24:26 -08002351 if (restriction) {
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002352 stillHasRestrictions = true;
2353 } else {
2354 opExceptions.remove(i);
Ruben Brunk29931bc2016-03-11 00:24:26 -08002355 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002356 }
2357 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002358
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002359 if (stillHasRestrictions) {
2360 return;
2361 }
2362
Ruben Brunk29931bc2016-03-11 00:24:26 -08002363 // No restrictions set for this client
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002364 perTokenRestrictions.remove(userHandle);
2365 if (perTokenRestrictions.size() <= 0) {
2366 mOpUserRestrictions.remove(token);
2367 }
2368 }
2369 }
2370 }
2371
Ruben Brunk29931bc2016-03-11 00:24:26 -08002372 /**
2373 * Get or create the user restrictions array for a given client if it doesn't already exist.
2374 *
2375 * @param token the binder client creating the restriction.
2376 * @param userHandle the user handle to create a restriction for.
2377 *
2378 * @return the array of restriction states for each AppOps code.
2379 */
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002380 private boolean[] getOrCreateUserRestrictionsForToken(IBinder token, int userHandle) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002381 SparseArray<Pair<boolean[], SparseArray<ArraySet<String>>>> perTokenRestrictions =
2382 mOpUserRestrictions.get(token);
2383
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002384 if (perTokenRestrictions == null) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002385 perTokenRestrictions =
2386 new SparseArray<Pair<boolean[], SparseArray<ArraySet<String>>>>();
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002387 mOpUserRestrictions.put(token, perTokenRestrictions);
2388 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002389
2390 Pair<boolean[], SparseArray<ArraySet<String>>> restrictions =
2391 perTokenRestrictions.get(userHandle);
2392
2393 if (restrictions == null) {
2394 restrictions = new Pair<boolean[], SparseArray<ArraySet<String>>>(
2395 new boolean[AppOpsManager._NUM_OP], new SparseArray<ArraySet<String>>());
2396 perTokenRestrictions.put(userHandle, restrictions);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002397 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002398
2399 return restrictions.first;
2400 }
2401
2402 /**
2403 * Get the per-package exemptions for each AppOps code for a given client and userHandle.
2404 *
2405 * @param token the binder client to get the exemptions for.
2406 * @param userHandle the user handle to get the exemptions for.
2407 *
2408 * @return a mapping from the AppOps code to a set of packages exempt for that code.
2409 */
2410 private SparseArray<ArraySet<String>> getUserPackageExemptionsForToken(IBinder token,
2411 int userHandle) {
2412 SparseArray<Pair<boolean[], SparseArray<ArraySet<String>>>> perTokenRestrictions =
2413 mOpUserRestrictions.get(token);
2414
2415 if (perTokenRestrictions == null) {
2416 return null; // Don't create user restrictions accidentally
2417 }
2418
2419 Pair<boolean[], SparseArray<ArraySet<String>>> restrictions =
2420 perTokenRestrictions.get(userHandle);
2421
2422 if (restrictions == null) {
2423 return null; // Don't create user restrictions accidentally
2424 }
2425
2426 return restrictions.second;
Jason Monk62062992014-05-06 09:55:28 -04002427 }
2428
2429 private void checkSystemUid(String function) {
2430 int uid = Binder.getCallingUid();
2431 if (uid != Process.SYSTEM_UID) {
2432 throw new SecurityException(function + " must by called by the system");
2433 }
2434 }
2435
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002436 private static String resolvePackageName(int uid, String packageName) {
2437 if (uid == 0) {
2438 return "root";
2439 } else if (uid == Process.SHELL_UID) {
2440 return "com.android.shell";
2441 } else if (uid == Process.SYSTEM_UID && packageName == null) {
2442 return "android";
2443 }
2444 return packageName;
2445 }
2446
Svet Ganov2af57082015-07-30 08:44:20 -07002447 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07002448 String[] packageNames = null;
Svet Ganov2af57082015-07-30 08:44:20 -07002449 try {
riddle_hsu40b300f2015-11-23 13:22:03 +08002450 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -07002451 } catch (RemoteException e) {
2452 /* ignore - local call */
2453 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07002454 if (packageNames == null) {
2455 return EmptyArray.STRING;
2456 }
2457 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07002458 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002459}