blob: 8eb01833d48481ded973f214103980a65eb51a32 [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
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -080034import android.app.ActivityManager;
Jason Monk1c7c3192014-06-26 12:52:18 -040035import android.app.ActivityThread;
Svet Ganov2af57082015-07-30 08:44:20 -070036import android.app.AppGlobals;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080037import android.app.AppOpsManager;
38import android.content.Context;
Jason Monk1c7c3192014-06-26 12:52:18 -040039import android.content.pm.ApplicationInfo;
40import android.content.pm.IPackageManager;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080041import android.content.pm.PackageManager;
42import android.content.pm.PackageManager.NameNotFoundException;
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 Hackborna06de0f2012-12-11 16:34:47 -080051import android.os.ServiceManager;
52import android.os.UserHandle;
Svet Ganov6ee871e2015-07-10 14:29:33 -070053import android.os.storage.MountServiceInternal;
Dianne Hackborne98f5db2013-07-17 17:23:25 -070054import android.util.ArrayMap;
John Spurlock1af30c72014-03-10 08:33:35 -040055import android.util.ArraySet;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080056import android.util.AtomicFile;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -080057import android.util.Log;
Dianne Hackborn607b4142013-08-02 18:10:10 -070058import android.util.Pair;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080059import android.util.Slog;
60import android.util.SparseArray;
Svet Ganov2af57082015-07-30 08:44:20 -070061import android.util.SparseIntArray;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080062import android.util.TimeUtils;
Dianne Hackborn35654b62013-01-14 17:38:02 -080063import android.util.Xml;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080064
65import com.android.internal.app.IAppOpsService;
Dianne Hackbornc2293022013-02-06 23:14:49 -080066import com.android.internal.app.IAppOpsCallback;
Svet Ganov6ee871e2015-07-10 14:29:33 -070067import com.android.internal.os.Zygote;
Svet Ganov2af57082015-07-30 08:44:20 -070068import com.android.internal.util.ArrayUtils;
Dianne Hackborn35654b62013-01-14 17:38:02 -080069import com.android.internal.util.FastXmlSerializer;
70import com.android.internal.util.XmlUtils;
71
Svet Ganov2af57082015-07-30 08:44:20 -070072import libcore.util.EmptyArray;
Dianne Hackborn35654b62013-01-14 17:38:02 -080073import org.xmlpull.v1.XmlPullParser;
74import org.xmlpull.v1.XmlPullParserException;
75import org.xmlpull.v1.XmlSerializer;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080076
77public class AppOpsService extends IAppOpsService.Stub {
78 static final String TAG = "AppOps";
Dianne Hackborn35654b62013-01-14 17:38:02 -080079 static final boolean DEBUG = false;
80
81 // Write at most every 30 minutes.
82 static final long WRITE_DELAY = DEBUG ? 1000 : 30*60*1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080083
84 Context mContext;
85 final AtomicFile mFile;
Dianne Hackborn35654b62013-01-14 17:38:02 -080086 final Handler mHandler;
87
88 boolean mWriteScheduled;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -080089 boolean mFastWriteScheduled;
Dianne Hackborn35654b62013-01-14 17:38:02 -080090 final Runnable mWriteRunner = new Runnable() {
91 public void run() {
92 synchronized (AppOpsService.this) {
93 mWriteScheduled = false;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -080094 mFastWriteScheduled = false;
Dianne Hackborn35654b62013-01-14 17:38:02 -080095 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
96 @Override protected Void doInBackground(Void... params) {
97 writeState();
98 return null;
99 }
100 };
101 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
102 }
103 }
104 };
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800105
Svet Ganov2af57082015-07-30 08:44:20 -0700106 final SparseArray<UidState> mUidStates = new SparseArray<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800107
Jason Monk62062992014-05-06 09:55:28 -0400108 private final SparseArray<boolean[]> mOpRestrictions = new SparseArray<boolean[]>();
109
Svet Ganov2af57082015-07-30 08:44:20 -0700110 private static final class UidState {
111 public final int uid;
112 public ArrayMap<String, Ops> pkgOps;
113 public SparseIntArray opModes;
114
115 public UidState(int uid) {
116 this.uid = uid;
117 }
118
119 public void clear() {
120 pkgOps = null;
121 opModes = null;
122 }
123
124 public boolean isDefault() {
125 return (pkgOps == null || pkgOps.isEmpty())
126 && (opModes == null || opModes.size() <= 0);
127 }
128 }
129
Dianne Hackbornc2293022013-02-06 23:14:49 -0800130 public final static class Ops extends SparseArray<Op> {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800131 public final String packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700132 public final UidState uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400133 public final boolean isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800134
Svet Ganov2af57082015-07-30 08:44:20 -0700135 public Ops(String _packageName, UidState _uidState, boolean _isPrivileged) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800136 packageName = _packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700137 uidState = _uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400138 isPrivileged = _isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800139 }
140 }
141
Dianne Hackbornc2293022013-02-06 23:14:49 -0800142 public final static class Op {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700143 public final int uid;
144 public final String packageName;
Svet Ganov99b60432015-06-27 13:15:22 -0700145 public int proxyUid = -1;
146 public String proxyPackageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800147 public final int op;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800148 public int mode;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800149 public int duration;
150 public long time;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800151 public long rejectTime;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800152 public int nesting;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800153
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700154 public Op(int _uid, String _packageName, int _op) {
155 uid = _uid;
156 packageName = _packageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800157 op = _op;
David Braunf5d83192013-09-16 13:43:51 -0700158 mode = AppOpsManager.opToDefaultMode(op);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800159 }
160 }
161
Dianne Hackbornc2293022013-02-06 23:14:49 -0800162 final SparseArray<ArrayList<Callback>> mOpModeWatchers
163 = new SparseArray<ArrayList<Callback>>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700164 final ArrayMap<String, ArrayList<Callback>> mPackageModeWatchers
165 = new ArrayMap<String, ArrayList<Callback>>();
166 final ArrayMap<IBinder, Callback> mModeWatchers
167 = new ArrayMap<IBinder, Callback>();
John Spurlock1af30c72014-03-10 08:33:35 -0400168 final SparseArray<SparseArray<Restriction>> mAudioRestrictions
169 = new SparseArray<SparseArray<Restriction>>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800170
171 public final class Callback implements DeathRecipient {
172 final IAppOpsCallback mCallback;
173
174 public Callback(IAppOpsCallback callback) {
175 mCallback = callback;
176 try {
177 mCallback.asBinder().linkToDeath(this, 0);
178 } catch (RemoteException e) {
179 }
180 }
181
182 public void unlinkToDeath() {
183 mCallback.asBinder().unlinkToDeath(this, 0);
184 }
185
186 @Override
187 public void binderDied() {
188 stopWatchingMode(mCallback);
189 }
190 }
191
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700192 final ArrayMap<IBinder, ClientState> mClients = new ArrayMap<IBinder, ClientState>();
193
194 public final class ClientState extends Binder implements DeathRecipient {
195 final IBinder mAppToken;
196 final int mPid;
197 final ArrayList<Op> mStartedOps;
198
199 public ClientState(IBinder appToken) {
200 mAppToken = appToken;
201 mPid = Binder.getCallingPid();
202 if (appToken instanceof Binder) {
203 // For local clients, there is no reason to track them.
204 mStartedOps = null;
205 } else {
206 mStartedOps = new ArrayList<Op>();
207 try {
208 mAppToken.linkToDeath(this, 0);
209 } catch (RemoteException e) {
210 }
211 }
212 }
213
214 @Override
215 public String toString() {
216 return "ClientState{" +
217 "mAppToken=" + mAppToken +
218 ", " + (mStartedOps != null ? ("pid=" + mPid) : "local") +
219 '}';
220 }
221
222 @Override
223 public void binderDied() {
224 synchronized (AppOpsService.this) {
225 for (int i=mStartedOps.size()-1; i>=0; i--) {
226 finishOperationLocked(mStartedOps.get(i));
227 }
228 mClients.remove(mAppToken);
229 }
230 }
231 }
232
Jeff Brown6f357d32014-01-15 20:40:55 -0800233 public AppOpsService(File storagePath, Handler handler) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800234 mFile = new AtomicFile(storagePath);
Jeff Brown6f357d32014-01-15 20:40:55 -0800235 mHandler = handler;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800236 readState();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800237 }
David Braunf5d83192013-09-16 13:43:51 -0700238
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800239 public void publish(Context context) {
240 mContext = context;
241 ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
242 }
243
Dianne Hackborn514074f2013-02-11 10:52:46 -0800244 public void systemReady() {
245 synchronized (this) {
246 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700247 for (int i = mUidStates.size() - 1; i >= 0; i--) {
248 UidState uidState = mUidStates.valueAt(i);
249
250 String[] packageNames = getPackagesForUid(uidState.uid);
251 if (ArrayUtils.isEmpty(packageNames)) {
252 uidState.clear();
253 mUidStates.removeAt(i);
254 changed = true;
255 continue;
256 }
257
258 ArrayMap<String, Ops> pkgs = uidState.pkgOps;
259 if (pkgs == null) {
260 continue;
261 }
262
Dianne Hackborn514074f2013-02-11 10:52:46 -0800263 Iterator<Ops> it = pkgs.values().iterator();
264 while (it.hasNext()) {
265 Ops ops = it.next();
266 int curUid;
267 try {
268 curUid = mContext.getPackageManager().getPackageUid(ops.packageName,
Svet Ganov2af57082015-07-30 08:44:20 -0700269 UserHandle.getUserId(ops.uidState.uid));
Dianne Hackborn514074f2013-02-11 10:52:46 -0800270 } catch (NameNotFoundException e) {
271 curUid = -1;
272 }
Svet Ganov2af57082015-07-30 08:44:20 -0700273 if (curUid != ops.uidState.uid) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800274 Slog.i(TAG, "Pruning old package " + ops.packageName
Svet Ganov2af57082015-07-30 08:44:20 -0700275 + "/" + ops.uidState + ": new uid=" + curUid);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800276 it.remove();
277 changed = true;
278 }
279 }
Svet Ganov2af57082015-07-30 08:44:20 -0700280
281 if (uidState.isDefault()) {
282 mUidStates.removeAt(i);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800283 }
284 }
285 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800286 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800287 }
288 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700289
290 MountServiceInternal mountServiceInternal = LocalServices.getService(
291 MountServiceInternal.class);
292 mountServiceInternal.addExternalStoragePolicy(
293 new MountServiceInternal.ExternalStorageMountPolicy() {
294 @Override
295 public int getMountMode(int uid, String packageName) {
296 if (Process.isIsolated(uid)) {
297 return Zygote.MOUNT_EXTERNAL_NONE;
298 }
299 if (noteOperation(AppOpsManager.OP_READ_EXTERNAL_STORAGE, uid,
300 packageName) != AppOpsManager.MODE_ALLOWED) {
301 return Zygote.MOUNT_EXTERNAL_NONE;
302 }
303 if (noteOperation(AppOpsManager.OP_WRITE_EXTERNAL_STORAGE, uid,
304 packageName) != AppOpsManager.MODE_ALLOWED) {
305 return Zygote.MOUNT_EXTERNAL_READ;
306 }
307 return Zygote.MOUNT_EXTERNAL_WRITE;
308 }
309
310 @Override
311 public boolean hasExternalStorage(int uid, String packageName) {
312 final int mountMode = getMountMode(uid, packageName);
313 return mountMode == Zygote.MOUNT_EXTERNAL_READ
314 || mountMode == Zygote.MOUNT_EXTERNAL_WRITE;
315 }
316 });
Dianne Hackborn514074f2013-02-11 10:52:46 -0800317 }
318
319 public void packageRemoved(int uid, String packageName) {
320 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700321 UidState uidState = mUidStates.get(uid);
322 if (uidState == null) {
323 return;
324 }
325
326 boolean changed = false;
327
328 // Remove any package state if such.
329 if (uidState.pkgOps != null && uidState.pkgOps.remove(packageName) != null) {
330 changed = true;
331 }
332
333 // If we just nuked the last package state check if the UID is valid.
334 if (changed && uidState.pkgOps.isEmpty()
335 && getPackagesForUid(uid).length <= 0) {
336 mUidStates.remove(uid);
337 }
338
339 if (changed) {
340 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800341 }
342 }
343 }
344
345 public void uidRemoved(int uid) {
346 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700347 if (mUidStates.indexOfKey(uid) >= 0) {
348 mUidStates.remove(uid);
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800349 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800350 }
351 }
352 }
353
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800354 public void shutdown() {
355 Slog.w(TAG, "Writing app ops before shutdown...");
Dianne Hackborn35654b62013-01-14 17:38:02 -0800356 boolean doWrite = false;
357 synchronized (this) {
358 if (mWriteScheduled) {
359 mWriteScheduled = false;
360 doWrite = true;
361 }
362 }
363 if (doWrite) {
364 writeState();
365 }
366 }
367
Dianne Hackborn72e39832013-01-18 18:36:09 -0800368 private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
369 ArrayList<AppOpsManager.OpEntry> resOps = null;
370 if (ops == null) {
371 resOps = new ArrayList<AppOpsManager.OpEntry>();
372 for (int j=0; j<pkgOps.size(); j++) {
373 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800374 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Svet Ganov99b60432015-06-27 13:15:22 -0700375 curOp.rejectTime, curOp.duration, curOp.proxyUid,
376 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800377 }
378 } else {
379 for (int j=0; j<ops.length; j++) {
380 Op curOp = pkgOps.get(ops[j]);
381 if (curOp != null) {
382 if (resOps == null) {
383 resOps = new ArrayList<AppOpsManager.OpEntry>();
384 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800385 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Svet Ganov99b60432015-06-27 13:15:22 -0700386 curOp.rejectTime, curOp.duration, curOp.proxyUid,
387 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800388 }
389 }
390 }
391 return resOps;
392 }
393
Dianne Hackborn35654b62013-01-14 17:38:02 -0800394 @Override
395 public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
396 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
397 Binder.getCallingPid(), Binder.getCallingUid(), null);
398 ArrayList<AppOpsManager.PackageOps> res = null;
399 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700400 final int uidStateCount = mUidStates.size();
401 for (int i = 0; i < uidStateCount; i++) {
402 UidState uidState = mUidStates.valueAt(i);
403 if (uidState.pkgOps == null || uidState.pkgOps.isEmpty()) {
404 continue;
405 }
406 ArrayMap<String, Ops> packages = uidState.pkgOps;
407 final int packageCount = packages.size();
408 for (int j = 0; j < packageCount; j++) {
409 Ops pkgOps = packages.valueAt(j);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800410 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800411 if (resOps != null) {
412 if (res == null) {
413 res = new ArrayList<AppOpsManager.PackageOps>();
414 }
415 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700416 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800417 res.add(resPackage);
418 }
419 }
420 }
421 }
422 return res;
423 }
424
425 @Override
Dianne Hackborn72e39832013-01-18 18:36:09 -0800426 public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
427 int[] ops) {
428 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
429 Binder.getCallingPid(), Binder.getCallingUid(), null);
430 synchronized (this) {
431 Ops pkgOps = getOpsLocked(uid, packageName, false);
432 if (pkgOps == null) {
433 return null;
434 }
435 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
436 if (resOps == null) {
437 return null;
438 }
439 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
440 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700441 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800442 res.add(resPackage);
443 return res;
444 }
445 }
446
Dianne Hackborn607b4142013-08-02 18:10:10 -0700447 private void pruneOp(Op op, int uid, String packageName) {
448 if (op.time == 0 && op.rejectTime == 0) {
449 Ops ops = getOpsLocked(uid, packageName, false);
450 if (ops != null) {
451 ops.remove(op.op);
452 if (ops.size() <= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -0700453 UidState uidState = ops.uidState;
454 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700455 if (pkgOps != null) {
456 pkgOps.remove(ops.packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700457 if (pkgOps.isEmpty()) {
458 uidState.pkgOps = null;
459 }
460 if (uidState.isDefault()) {
461 mUidStates.remove(uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700462 }
463 }
464 }
465 }
466 }
467 }
468
Dianne Hackborn72e39832013-01-18 18:36:09 -0800469 @Override
Svet Ganov2af57082015-07-30 08:44:20 -0700470 public void setUidMode(int code, int uid, int mode) {
471 if (Binder.getCallingPid() != Process.myPid()) {
472 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
473 Binder.getCallingPid(), Binder.getCallingUid(), null);
474 }
475 verifyIncomingOp(code);
476 code = AppOpsManager.opToSwitch(code);
477
478 synchronized (this) {
479 final int defaultMode = AppOpsManager.opToDefaultMode(code);
480
481 UidState uidState = getUidStateLocked(uid, false);
482 if (uidState == null) {
483 if (mode == defaultMode) {
484 return;
485 }
486 uidState = new UidState(uid);
487 uidState.opModes = new SparseIntArray();
488 uidState.opModes.put(code, mode);
489 mUidStates.put(uid, uidState);
490 scheduleWriteLocked();
491 } else if (uidState.opModes == null) {
492 if (mode != defaultMode) {
493 uidState.opModes = new SparseIntArray();
494 uidState.opModes.put(code, mode);
495 scheduleWriteLocked();
496 }
497 } else {
498 if (uidState.opModes.get(code) == mode) {
499 return;
500 }
501 if (mode == defaultMode) {
502 uidState.opModes.delete(code);
503 if (uidState.opModes.size() <= 0) {
504 uidState.opModes = null;
505 }
506 } else {
507 uidState.opModes.put(code, mode);
508 }
509 scheduleWriteLocked();
510 }
511 }
512
Svetoslav215b44a2015-08-04 19:03:40 -0700513 String[] uidPackageNames = getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -0700514 ArrayMap<Callback, ArraySet<String>> callbackSpecs = null;
515
riddle_hsu40b300f2015-11-23 13:22:03 +0800516 synchronized (this) {
517 ArrayList<Callback> callbacks = mOpModeWatchers.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -0700518 if (callbacks != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700519 final int callbackCount = callbacks.size();
520 for (int i = 0; i < callbackCount; i++) {
521 Callback callback = callbacks.get(i);
riddle_hsu40b300f2015-11-23 13:22:03 +0800522 ArraySet<String> changedPackages = new ArraySet<>();
523 Collections.addAll(changedPackages, uidPackageNames);
524 callbackSpecs = new ArrayMap<>();
525 callbackSpecs.put(callback, changedPackages);
526 }
527 }
528
529 for (String uidPackageName : uidPackageNames) {
530 callbacks = mPackageModeWatchers.get(uidPackageName);
531 if (callbacks != null) {
532 if (callbackSpecs == null) {
533 callbackSpecs = new ArrayMap<>();
Svet Ganov2af57082015-07-30 08:44:20 -0700534 }
riddle_hsu40b300f2015-11-23 13:22:03 +0800535 final int callbackCount = callbacks.size();
536 for (int i = 0; i < callbackCount; i++) {
537 Callback callback = callbacks.get(i);
538 ArraySet<String> changedPackages = callbackSpecs.get(callback);
539 if (changedPackages == null) {
540 changedPackages = new ArraySet<>();
541 callbackSpecs.put(callback, changedPackages);
542 }
543 changedPackages.add(uidPackageName);
544 }
Svet Ganov2af57082015-07-30 08:44:20 -0700545 }
546 }
547 }
548
549 if (callbackSpecs == null) {
550 return;
551 }
552
553 // There are components watching for mode changes such as window manager
554 // and location manager which are in our process. The callbacks in these
555 // components may require permissions our remote caller does not have.
556 final long identity = Binder.clearCallingIdentity();
557 try {
558 for (int i = 0; i < callbackSpecs.size(); i++) {
559 Callback callback = callbackSpecs.keyAt(i);
560 ArraySet<String> reportedPackageNames = callbackSpecs.valueAt(i);
561 try {
562 if (reportedPackageNames == null) {
563 callback.mCallback.opChanged(code, null);
564 } else {
565 final int reportedPackageCount = reportedPackageNames.size();
566 for (int j = 0; j < reportedPackageCount; j++) {
567 String reportedPackageName = reportedPackageNames.valueAt(j);
568 callback.mCallback.opChanged(code, reportedPackageName);
569 }
570 }
571 } catch (RemoteException e) {
572 Log.w(TAG, "Error dispatching op op change", e);
573 }
574 }
575 } finally {
576 Binder.restoreCallingIdentity(identity);
577 }
578 }
579
580 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800581 public void setMode(int code, int uid, String packageName, int mode) {
Dianne Hackbornb64afe12014-07-22 16:29:04 -0700582 if (Binder.getCallingPid() != Process.myPid()) {
583 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
584 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborn133b9df2014-07-01 13:06:10 -0700585 }
Dianne Hackborn961321f2013-02-05 17:22:41 -0800586 verifyIncomingOp(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800587 ArrayList<Callback> repCbs = null;
588 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800589 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700590 UidState uidState = getUidStateLocked(uid, false);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800591 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800592 if (op != null) {
593 if (op.mode != mode) {
594 op.mode = mode;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800595 ArrayList<Callback> cbs = mOpModeWatchers.get(code);
596 if (cbs != null) {
597 if (repCbs == null) {
598 repCbs = new ArrayList<Callback>();
599 }
600 repCbs.addAll(cbs);
601 }
602 cbs = mPackageModeWatchers.get(packageName);
603 if (cbs != null) {
604 if (repCbs == null) {
605 repCbs = new ArrayList<Callback>();
606 }
607 repCbs.addAll(cbs);
608 }
David Braunf5d83192013-09-16 13:43:51 -0700609 if (mode == AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800610 // If going into the default mode, prune this op
611 // if there is nothing else interesting in it.
Dianne Hackborn607b4142013-08-02 18:10:10 -0700612 pruneOp(op, uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800613 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800614 scheduleFastWriteLocked();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800615 }
616 }
617 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800618 if (repCbs != null) {
Svet Ganov38536112015-05-19 12:45:52 -0700619 // There are components watching for mode changes such as window manager
620 // and location manager which are in our process. The callbacks in these
621 // components may require permissions our remote caller does not have.
622 final long identity = Binder.clearCallingIdentity();
623 try {
624 for (int i = 0; i < repCbs.size(); i++) {
625 try {
626 repCbs.get(i).mCallback.opChanged(code, packageName);
627 } catch (RemoteException e) {
628 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800629 }
Svet Ganov38536112015-05-19 12:45:52 -0700630 } finally {
631 Binder.restoreCallingIdentity(identity);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800632 }
633 }
634 }
635
Dianne Hackborn607b4142013-08-02 18:10:10 -0700636 private static HashMap<Callback, ArrayList<Pair<String, Integer>>> addCallbacks(
637 HashMap<Callback, ArrayList<Pair<String, Integer>>> callbacks,
638 String packageName, int op, ArrayList<Callback> cbs) {
639 if (cbs == null) {
640 return callbacks;
641 }
642 if (callbacks == null) {
643 callbacks = new HashMap<Callback, ArrayList<Pair<String, Integer>>>();
644 }
Svet Ganov2af57082015-07-30 08:44:20 -0700645 boolean duplicate = false;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700646 for (int i=0; i<cbs.size(); i++) {
647 Callback cb = cbs.get(i);
648 ArrayList<Pair<String, Integer>> reports = callbacks.get(cb);
649 if (reports == null) {
650 reports = new ArrayList<Pair<String, Integer>>();
651 callbacks.put(cb, reports);
Svet Ganov2af57082015-07-30 08:44:20 -0700652 } else {
653 final int reportCount = reports.size();
654 for (int j = 0; j < reportCount; j++) {
655 Pair<String, Integer> report = reports.get(j);
656 if (report.second == op && report.first.equals(packageName)) {
657 duplicate = true;
658 break;
659 }
660 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700661 }
Svet Ganov2af57082015-07-30 08:44:20 -0700662 if (!duplicate) {
663 reports.add(new Pair<>(packageName, op));
664 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700665 }
666 return callbacks;
667 }
668
669 @Override
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800670 public void resetAllModes(int reqUserId, String reqPackageName) {
671 final int callingPid = Binder.getCallingPid();
672 final int callingUid = Binder.getCallingUid();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700673 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800674 callingPid, callingUid, null);
675 reqUserId = ActivityManager.handleIncomingUser(callingPid, callingUid, reqUserId,
676 true, true, "resetAllModes", null);
Svet Ganov2af57082015-07-30 08:44:20 -0700677
678 int reqUid = -1;
679 if (reqPackageName != null) {
680 try {
681 reqUid = AppGlobals.getPackageManager().getPackageUid(
682 reqPackageName, reqUserId);
683 } catch (RemoteException e) {
684 /* ignore - local call */
685 }
686 }
687
Dianne Hackborn607b4142013-08-02 18:10:10 -0700688 HashMap<Callback, ArrayList<Pair<String, Integer>>> callbacks = null;
689 synchronized (this) {
690 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700691 for (int i = mUidStates.size() - 1; i >= 0; i--) {
692 UidState uidState = mUidStates.valueAt(i);
693
694 SparseIntArray opModes = uidState.opModes;
695 if (opModes != null && (uidState.uid == reqUid || reqUid == -1)) {
696 final int uidOpCount = opModes.size();
697 for (int j = uidOpCount - 1; j >= 0; j--) {
698 final int code = opModes.keyAt(j);
699 if (AppOpsManager.opAllowsReset(code)) {
700 opModes.removeAt(j);
701 if (opModes.size() <= 0) {
702 uidState.opModes = null;
703 }
704 for (String packageName : getPackagesForUid(uidState.uid)) {
705 callbacks = addCallbacks(callbacks, packageName, code,
706 mOpModeWatchers.get(code));
707 callbacks = addCallbacks(callbacks, packageName, code,
708 mPackageModeWatchers.get(packageName));
709 }
710 }
711 }
712 }
713
714 if (uidState.pkgOps == null) {
715 continue;
716 }
717
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800718 if (reqUserId != UserHandle.USER_ALL
Svet Ganov2af57082015-07-30 08:44:20 -0700719 && reqUserId != UserHandle.getUserId(uidState.uid)) {
Alexandra Gherghinad6a98972014-08-04 17:05:34 +0100720 // Skip any ops for a different user
721 continue;
722 }
Svet Ganov2af57082015-07-30 08:44:20 -0700723
724 Map<String, Ops> packages = uidState.pkgOps;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700725 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
726 while (it.hasNext()) {
727 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700728 String packageName = ent.getKey();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800729 if (reqPackageName != null && !reqPackageName.equals(packageName)) {
730 // Skip any ops for a different package
731 continue;
732 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700733 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700734 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700735 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -0700736 if (AppOpsManager.opAllowsReset(curOp.op)
737 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -0700738 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700739 changed = true;
740 callbacks = addCallbacks(callbacks, packageName, curOp.op,
741 mOpModeWatchers.get(curOp.op));
742 callbacks = addCallbacks(callbacks, packageName, curOp.op,
743 mPackageModeWatchers.get(packageName));
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700744 if (curOp.time == 0 && curOp.rejectTime == 0) {
745 pkgOps.removeAt(j);
746 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700747 }
748 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700749 if (pkgOps.size() == 0) {
750 it.remove();
751 }
752 }
Svet Ganov2af57082015-07-30 08:44:20 -0700753 if (uidState.isDefault()) {
754 mUidStates.remove(uidState.uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700755 }
756 }
Svet Ganov2af57082015-07-30 08:44:20 -0700757
Dianne Hackborn607b4142013-08-02 18:10:10 -0700758 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800759 scheduleFastWriteLocked();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700760 }
761 }
762 if (callbacks != null) {
763 for (Map.Entry<Callback, ArrayList<Pair<String, Integer>>> ent : callbacks.entrySet()) {
764 Callback cb = ent.getKey();
765 ArrayList<Pair<String, Integer>> reports = ent.getValue();
766 for (int i=0; i<reports.size(); i++) {
767 Pair<String, Integer> rep = reports.get(i);
768 try {
769 cb.mCallback.opChanged(rep.second, rep.first);
770 } catch (RemoteException e) {
771 }
772 }
773 }
774 }
775 }
776
Dianne Hackbornc2293022013-02-06 23:14:49 -0800777 @Override
778 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
779 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700780 op = (op != AppOpsManager.OP_NONE) ? AppOpsManager.opToSwitch(op) : op;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800781 Callback cb = mModeWatchers.get(callback.asBinder());
782 if (cb == null) {
783 cb = new Callback(callback);
784 mModeWatchers.put(callback.asBinder(), cb);
785 }
786 if (op != AppOpsManager.OP_NONE) {
787 ArrayList<Callback> cbs = mOpModeWatchers.get(op);
788 if (cbs == null) {
789 cbs = new ArrayList<Callback>();
790 mOpModeWatchers.put(op, cbs);
791 }
792 cbs.add(cb);
793 }
794 if (packageName != null) {
795 ArrayList<Callback> cbs = mPackageModeWatchers.get(packageName);
796 if (cbs == null) {
797 cbs = new ArrayList<Callback>();
798 mPackageModeWatchers.put(packageName, cbs);
799 }
800 cbs.add(cb);
801 }
802 }
803 }
804
805 @Override
806 public void stopWatchingMode(IAppOpsCallback callback) {
807 synchronized (this) {
808 Callback cb = mModeWatchers.remove(callback.asBinder());
809 if (cb != null) {
810 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700811 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800812 ArrayList<Callback> cbs = mOpModeWatchers.valueAt(i);
813 cbs.remove(cb);
814 if (cbs.size() <= 0) {
815 mOpModeWatchers.removeAt(i);
816 }
817 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700818 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
819 ArrayList<Callback> cbs = mPackageModeWatchers.valueAt(i);
820 cbs.remove(cb);
821 if (cbs.size() <= 0) {
822 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800823 }
824 }
825 }
826 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800827 }
828
829 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700830 public IBinder getToken(IBinder clientToken) {
831 synchronized (this) {
832 ClientState cs = mClients.get(clientToken);
833 if (cs == null) {
834 cs = new ClientState(clientToken);
835 mClients.put(clientToken, cs);
836 }
837 return cs;
838 }
839 }
840
841 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800842 public int checkOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800843 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800844 verifyIncomingOp(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800845 synchronized (this) {
Jason Monk1c7c3192014-06-26 12:52:18 -0400846 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -0400847 return AppOpsManager.MODE_IGNORED;
848 }
Svet Ganov2af57082015-07-30 08:44:20 -0700849 code = AppOpsManager.opToSwitch(code);
850 UidState uidState = getUidStateLocked(uid, false);
851 if (uidState != null && uidState.opModes != null) {
852 final int uidMode = uidState.opModes.get(code);
853 if (uidMode != AppOpsManager.MODE_ALLOWED) {
854 return uidMode;
855 }
856 }
857 Op op = getOpLocked(code, uid, packageName, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800858 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -0700859 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800860 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800861 return op.mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800862 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800863 }
864
865 @Override
John Spurlock7b414672014-07-18 13:02:39 -0400866 public int checkAudioOperation(int code, int usage, int uid, String packageName) {
John Spurlock1af30c72014-03-10 08:33:35 -0400867 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -0400868 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -0400869 if (mode != AppOpsManager.MODE_ALLOWED) {
870 return mode;
871 }
872 }
873 return checkOperation(code, uid, packageName);
874 }
875
John Spurlock7b414672014-07-18 13:02:39 -0400876 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
877 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
878 if (usageRestrictions != null) {
879 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -0400880 if (r != null && !r.exceptionPackages.contains(packageName)) {
881 return r.mode;
882 }
883 }
884 return AppOpsManager.MODE_ALLOWED;
885 }
886
887 @Override
John Spurlock7b414672014-07-18 13:02:39 -0400888 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -0400889 String[] exceptionPackages) {
890 verifyIncomingUid(uid);
891 verifyIncomingOp(code);
892 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -0400893 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
894 if (usageRestrictions == null) {
895 usageRestrictions = new SparseArray<Restriction>();
896 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -0400897 }
John Spurlock7b414672014-07-18 13:02:39 -0400898 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -0400899 if (mode != AppOpsManager.MODE_ALLOWED) {
900 final Restriction r = new Restriction();
901 r.mode = mode;
902 if (exceptionPackages != null) {
903 final int N = exceptionPackages.length;
904 r.exceptionPackages = new ArraySet<String>(N);
905 for (int i = 0; i < N; i++) {
906 final String pkg = exceptionPackages[i];
907 if (pkg != null) {
908 r.exceptionPackages.add(pkg.trim());
909 }
910 }
911 }
John Spurlock7b414672014-07-18 13:02:39 -0400912 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -0400913 }
914 }
915 }
916
917 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700918 public int checkPackage(int uid, String packageName) {
919 synchronized (this) {
Dianne Hackborn0fcef842014-09-12 15:38:33 -0700920 if (getOpsRawLocked(uid, packageName, true) != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700921 return AppOpsManager.MODE_ALLOWED;
922 } else {
923 return AppOpsManager.MODE_ERRORED;
924 }
925 }
926 }
927
928 @Override
Svet Ganov99b60432015-06-27 13:15:22 -0700929 public int noteProxyOperation(int code, String proxyPackageName,
930 int proxiedUid, String proxiedPackageName) {
931 verifyIncomingOp(code);
932 final int proxyMode = noteOperationUnchecked(code, Binder.getCallingUid(),
933 proxyPackageName, -1, null);
934 if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
935 return proxyMode;
936 }
937 return noteOperationUnchecked(code, proxiedUid, proxiedPackageName,
938 Binder.getCallingUid(), proxyPackageName);
Svet Ganov99b60432015-06-27 13:15:22 -0700939 }
940
941 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800942 public int noteOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800943 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800944 verifyIncomingOp(code);
Svet Ganov99b60432015-06-27 13:15:22 -0700945 return noteOperationUnchecked(code, uid, packageName, 0, null);
946 }
947
948 private int noteOperationUnchecked(int code, int uid, String packageName,
949 int proxyUid, String proxyPackageName) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800950 synchronized (this) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800951 Ops ops = getOpsLocked(uid, packageName, true);
952 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800953 if (DEBUG) Log.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
954 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700955 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800956 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800957 Op op = getOpLocked(ops, code, true);
Jason Monk1c7c3192014-06-26 12:52:18 -0400958 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -0400959 return AppOpsManager.MODE_IGNORED;
960 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800961 if (op.duration == -1) {
962 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
963 + " code " + code + " time=" + op.time + " duration=" + op.duration);
964 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800965 op.duration = 0;
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800966 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -0700967 UidState uidState = ops.uidState;
968 if (uidState.opModes != null) {
969 final int uidMode = uidState.opModes.get(switchCode);
970 if (uidMode != AppOpsManager.MODE_ALLOWED) {
971 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
972 + switchCode + " (" + code + ") uid " + uid + " package "
973 + packageName);
974 op.rejectTime = System.currentTimeMillis();
975 return uidMode;
976 }
977 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800978 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
979 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
980 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
981 + switchCode + " (" + code + ") uid " + uid + " package " + packageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800982 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800983 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800984 }
985 if (DEBUG) Log.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
986 + " package " + packageName);
987 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800988 op.rejectTime = 0;
Svet Ganov99b60432015-06-27 13:15:22 -0700989 op.proxyUid = proxyUid;
990 op.proxyPackageName = proxyPackageName;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800991 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800992 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800993 }
994
995 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700996 public int startOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800997 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800998 verifyIncomingOp(code);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700999 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001000 synchronized (this) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001001 Ops ops = getOpsLocked(uid, packageName, true);
1002 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001003 if (DEBUG) Log.d(TAG, "startOperation: no op for code " + code + " uid " + uid
1004 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001005 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001006 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001007 Op op = getOpLocked(ops, code, true);
Jason Monk1c7c3192014-06-26 12:52:18 -04001008 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001009 return AppOpsManager.MODE_IGNORED;
1010 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001011 final int switchCode = AppOpsManager.opToSwitch(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001012 UidState uidState = ops.uidState;
1013 if (uidState.opModes != null) {
1014 final int uidMode = uidState.opModes.get(switchCode);
1015 if (uidMode != AppOpsManager.MODE_ALLOWED) {
1016 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
1017 + switchCode + " (" + code + ") uid " + uid + " package "
1018 + packageName);
1019 op.rejectTime = System.currentTimeMillis();
1020 return uidMode;
1021 }
1022 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001023 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
1024 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
1025 if (DEBUG) Log.d(TAG, "startOperation: reject #" + op.mode + " for code "
1026 + switchCode + " (" + code + ") uid " + uid + " package " + packageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001027 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001028 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001029 }
1030 if (DEBUG) Log.d(TAG, "startOperation: allowing code " + code + " uid " + uid
1031 + " package " + packageName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001032 if (op.nesting == 0) {
1033 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -08001034 op.rejectTime = 0;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001035 op.duration = -1;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001036 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001037 op.nesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001038 if (client.mStartedOps != null) {
1039 client.mStartedOps.add(op);
1040 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001041 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001042 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001043 }
1044
1045 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001046 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001047 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001048 verifyIncomingOp(code);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001049 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001050 synchronized (this) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001051 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001052 if (op == null) {
1053 return;
1054 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001055 if (client.mStartedOps != null) {
1056 if (!client.mStartedOps.remove(op)) {
1057 throw new IllegalStateException("Operation not started: uid" + op.uid
1058 + " pkg=" + op.packageName + " op=" + op.op);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001059 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001060 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001061 finishOperationLocked(op);
1062 }
1063 }
1064
Svet Ganovb9d71a62015-04-30 10:38:13 -07001065 @Override
1066 public int permissionToOpCode(String permission) {
1067 return AppOpsManager.permissionToOpCode(permission);
1068 }
1069
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001070 void finishOperationLocked(Op op) {
1071 if (op.nesting <= 1) {
1072 if (op.nesting == 1) {
1073 op.duration = (int)(System.currentTimeMillis() - op.time);
1074 op.time += op.duration;
1075 } else {
1076 Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
1077 + op.packageName + " code " + op.op + " time=" + op.time
1078 + " duration=" + op.duration + " nesting=" + op.nesting);
1079 }
1080 op.nesting = 0;
1081 } else {
1082 op.nesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001083 }
1084 }
1085
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001086 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001087 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001088 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001089 }
1090 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001091 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001092 }
1093 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
1094 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001095 }
1096
Dianne Hackborn961321f2013-02-05 17:22:41 -08001097 private void verifyIncomingOp(int op) {
1098 if (op >= 0 && op < AppOpsManager._NUM_OP) {
1099 return;
1100 }
1101 throw new IllegalArgumentException("Bad operation #" + op);
1102 }
1103
Svet Ganov2af57082015-07-30 08:44:20 -07001104 private UidState getUidStateLocked(int uid, boolean edit) {
1105 UidState uidState = mUidStates.get(uid);
1106 if (uidState == null) {
1107 if (!edit) {
1108 return null;
1109 }
1110 uidState = new UidState(uid);
1111 mUidStates.put(uid, uidState);
1112 }
1113 return uidState;
1114 }
1115
Dianne Hackborn72e39832013-01-18 18:36:09 -08001116 private Ops getOpsLocked(int uid, String packageName, boolean edit) {
Dianne Hackborn0fcef842014-09-12 15:38:33 -07001117 if (uid == 0) {
1118 packageName = "root";
1119 } else if (uid == Process.SHELL_UID) {
1120 packageName = "com.android.shell";
1121 }
1122 return getOpsRawLocked(uid, packageName, edit);
1123 }
1124
1125 private Ops getOpsRawLocked(int uid, String packageName, boolean edit) {
Svet Ganov2af57082015-07-30 08:44:20 -07001126 UidState uidState = getUidStateLocked(uid, edit);
1127 if (uidState == null) {
1128 return null;
1129 }
1130
1131 if (uidState.pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001132 if (!edit) {
1133 return null;
1134 }
Svet Ganov2af57082015-07-30 08:44:20 -07001135 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001136 }
Svet Ganov2af57082015-07-30 08:44:20 -07001137
1138 Ops ops = uidState.pkgOps.get(packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001139 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001140 if (!edit) {
1141 return null;
1142 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001143 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001144 // This is the first time we have seen this package name under this uid,
1145 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -08001146 if (uid != 0) {
1147 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001148 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001149 int pkgUid = -1;
1150 try {
Jason Monk1c7c3192014-06-26 12:52:18 -04001151 ApplicationInfo appInfo = ActivityThread.getPackageManager()
1152 .getApplicationInfo(packageName, 0, UserHandle.getUserId(uid));
1153 if (appInfo != null) {
1154 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001155 isPrivileged = (appInfo.privateFlags
1156 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001157 } else {
1158 if ("media".equals(packageName)) {
1159 pkgUid = Process.MEDIA_UID;
1160 isPrivileged = false;
1161 }
Dianne Hackborn713df152013-05-17 11:27:57 -07001162 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001163 } catch (RemoteException e) {
1164 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001165 }
1166 if (pkgUid != uid) {
1167 // Oops! The package name is not valid for the uid they are calling
1168 // under. Abort.
1169 Slog.w(TAG, "Bad call: specified package " + packageName
1170 + " under uid " + uid + " but it is really " + pkgUid);
1171 return null;
1172 }
1173 } finally {
1174 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001175 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001176 }
Svet Ganov2af57082015-07-30 08:44:20 -07001177 ops = new Ops(packageName, uidState, isPrivileged);
1178 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001179 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08001180 return ops;
1181 }
1182
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001183 private void scheduleWriteLocked() {
1184 if (!mWriteScheduled) {
1185 mWriteScheduled = true;
1186 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
1187 }
1188 }
1189
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001190 private void scheduleFastWriteLocked() {
1191 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001192 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001193 mFastWriteScheduled = true;
1194 mHandler.removeCallbacks(mWriteRunner);
1195 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001196 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001197 }
1198
Dianne Hackborn72e39832013-01-18 18:36:09 -08001199 private Op getOpLocked(int code, int uid, String packageName, boolean edit) {
1200 Ops ops = getOpsLocked(uid, packageName, edit);
1201 if (ops == null) {
1202 return null;
1203 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001204 return getOpLocked(ops, code, edit);
1205 }
1206
1207 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001208 Op op = ops.get(code);
1209 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001210 if (!edit) {
1211 return null;
1212 }
Svet Ganov2af57082015-07-30 08:44:20 -07001213 op = new Op(ops.uidState.uid, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001214 ops.put(code, op);
1215 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001216 if (edit) {
1217 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001218 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001219 return op;
1220 }
1221
Jason Monk1c7c3192014-06-26 12:52:18 -04001222 private boolean isOpRestricted(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04001223 int userHandle = UserHandle.getUserId(uid);
1224 boolean[] opRestrictions = mOpRestrictions.get(userHandle);
1225 if ((opRestrictions != null) && opRestrictions[code]) {
Jason Monk1c7c3192014-06-26 12:52:18 -04001226 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
1227 synchronized (this) {
1228 Ops ops = getOpsLocked(uid, packageName, true);
1229 if ((ops != null) && ops.isPrivileged) {
1230 return false;
1231 }
1232 }
1233 }
Julia Reynolds401de172014-07-24 18:21:29 -04001234 return true;
Jason Monk62062992014-05-06 09:55:28 -04001235 }
1236 return false;
1237 }
1238
Dianne Hackborn35654b62013-01-14 17:38:02 -08001239 void readState() {
1240 synchronized (mFile) {
1241 synchronized (this) {
1242 FileInputStream stream;
1243 try {
1244 stream = mFile.openRead();
1245 } catch (FileNotFoundException e) {
1246 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
1247 return;
1248 }
1249 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001250 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001251 try {
1252 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001253 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001254 int type;
1255 while ((type = parser.next()) != XmlPullParser.START_TAG
1256 && type != XmlPullParser.END_DOCUMENT) {
1257 ;
1258 }
1259
1260 if (type != XmlPullParser.START_TAG) {
1261 throw new IllegalStateException("no start tag found");
1262 }
1263
1264 int outerDepth = parser.getDepth();
1265 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1266 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1267 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1268 continue;
1269 }
1270
1271 String tagName = parser.getName();
1272 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001273 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07001274 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07001275 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001276 } else {
1277 Slog.w(TAG, "Unknown element under <app-ops>: "
1278 + parser.getName());
1279 XmlUtils.skipCurrentTag(parser);
1280 }
1281 }
1282 success = true;
1283 } catch (IllegalStateException e) {
1284 Slog.w(TAG, "Failed parsing " + e);
1285 } catch (NullPointerException e) {
1286 Slog.w(TAG, "Failed parsing " + e);
1287 } catch (NumberFormatException e) {
1288 Slog.w(TAG, "Failed parsing " + e);
1289 } catch (XmlPullParserException e) {
1290 Slog.w(TAG, "Failed parsing " + e);
1291 } catch (IOException e) {
1292 Slog.w(TAG, "Failed parsing " + e);
1293 } catch (IndexOutOfBoundsException e) {
1294 Slog.w(TAG, "Failed parsing " + e);
1295 } finally {
1296 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07001297 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001298 }
1299 try {
1300 stream.close();
1301 } catch (IOException e) {
1302 }
1303 }
1304 }
1305 }
1306 }
1307
Svet Ganov2af57082015-07-30 08:44:20 -07001308 void readUidOps(XmlPullParser parser) throws NumberFormatException,
1309 XmlPullParserException, IOException {
1310 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
1311 int outerDepth = parser.getDepth();
1312 int type;
1313 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1314 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1315 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1316 continue;
1317 }
1318
1319 String tagName = parser.getName();
1320 if (tagName.equals("op")) {
1321 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
1322 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
1323 UidState uidState = getUidStateLocked(uid, true);
1324 if (uidState.opModes == null) {
1325 uidState.opModes = new SparseIntArray();
1326 }
1327 uidState.opModes.put(code, mode);
1328 } else {
1329 Slog.w(TAG, "Unknown element under <uid-ops>: "
1330 + parser.getName());
1331 XmlUtils.skipCurrentTag(parser);
1332 }
1333 }
1334 }
1335
Dave Burke0997c5bd2013-08-02 20:25:02 +00001336 void readPackage(XmlPullParser parser) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001337 XmlPullParserException, IOException {
1338 String pkgName = parser.getAttributeValue(null, "n");
1339 int outerDepth = parser.getDepth();
1340 int type;
1341 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1342 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1343 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1344 continue;
1345 }
1346
1347 String tagName = parser.getName();
1348 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001349 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001350 } else {
1351 Slog.w(TAG, "Unknown element under <pkg>: "
1352 + parser.getName());
1353 XmlUtils.skipCurrentTag(parser);
1354 }
1355 }
1356 }
1357
Dave Burke0997c5bd2013-08-02 20:25:02 +00001358 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001359 XmlPullParserException, IOException {
1360 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Jason Monk1c7c3192014-06-26 12:52:18 -04001361 String isPrivilegedString = parser.getAttributeValue(null, "p");
1362 boolean isPrivileged = false;
1363 if (isPrivilegedString == null) {
1364 try {
1365 IPackageManager packageManager = ActivityThread.getPackageManager();
1366 if (packageManager != null) {
1367 ApplicationInfo appInfo = ActivityThread.getPackageManager()
1368 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
1369 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001370 isPrivileged = (appInfo.privateFlags
1371 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001372 }
1373 } else {
1374 // Could not load data, don't add to cache so it will be loaded later.
1375 return;
1376 }
1377 } catch (RemoteException e) {
1378 Slog.w(TAG, "Could not contact PackageManager", e);
1379 }
1380 } else {
1381 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
1382 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001383 int outerDepth = parser.getDepth();
1384 int type;
1385 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1386 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1387 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1388 continue;
1389 }
1390
1391 String tagName = parser.getName();
1392 if (tagName.equals("op")) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001393 Op op = new Op(uid, pkgName, Integer.parseInt(parser.getAttributeValue(null, "n")));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001394 String mode = parser.getAttributeValue(null, "m");
1395 if (mode != null) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001396 op.mode = Integer.parseInt(mode);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001397 }
1398 String time = parser.getAttributeValue(null, "t");
1399 if (time != null) {
1400 op.time = Long.parseLong(time);
1401 }
1402 time = parser.getAttributeValue(null, "r");
1403 if (time != null) {
1404 op.rejectTime = Long.parseLong(time);
1405 }
1406 String dur = parser.getAttributeValue(null, "d");
1407 if (dur != null) {
1408 op.duration = Integer.parseInt(dur);
1409 }
Svet Ganov99b60432015-06-27 13:15:22 -07001410 String proxyUid = parser.getAttributeValue(null, "pu");
1411 if (proxyUid != null) {
1412 op.proxyUid = Integer.parseInt(proxyUid);
1413 }
1414 String proxyPackageName = parser.getAttributeValue(null, "pp");
1415 if (proxyPackageName != null) {
1416 op.proxyPackageName = proxyPackageName;
1417 }
Svet Ganov2af57082015-07-30 08:44:20 -07001418
1419 UidState uidState = getUidStateLocked(uid, true);
1420 if (uidState.pkgOps == null) {
1421 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001422 }
Svet Ganov2af57082015-07-30 08:44:20 -07001423
1424 Ops ops = uidState.pkgOps.get(pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001425 if (ops == null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001426 ops = new Ops(pkgName, uidState, isPrivileged);
1427 uidState.pkgOps.put(pkgName, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001428 }
1429 ops.put(op.op, op);
1430 } else {
1431 Slog.w(TAG, "Unknown element under <pkg>: "
1432 + parser.getName());
1433 XmlUtils.skipCurrentTag(parser);
1434 }
1435 }
1436 }
1437
1438 void writeState() {
1439 synchronized (mFile) {
1440 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
1441
1442 FileOutputStream stream;
1443 try {
1444 stream = mFile.startWrite();
1445 } catch (IOException e) {
1446 Slog.w(TAG, "Failed to write state: " + e);
1447 return;
1448 }
1449
1450 try {
1451 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001452 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001453 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001454 out.startTag(null, "app-ops");
Svet Ganov2af57082015-07-30 08:44:20 -07001455
1456 final int uidStateCount = mUidStates.size();
1457 for (int i = 0; i < uidStateCount; i++) {
1458 UidState uidState = mUidStates.valueAt(i);
1459 if (uidState.opModes != null && uidState.opModes.size() > 0) {
1460 out.startTag(null, "uid");
1461 out.attribute(null, "n", Integer.toString(uidState.uid));
1462 SparseIntArray uidOpModes = uidState.opModes;
1463 final int opCount = uidOpModes.size();
1464 for (int j = 0; j < opCount; j++) {
1465 final int op = uidOpModes.keyAt(j);
1466 final int mode = uidOpModes.valueAt(j);
1467 out.startTag(null, "op");
1468 out.attribute(null, "n", Integer.toString(op));
1469 out.attribute(null, "m", Integer.toString(mode));
1470 out.endTag(null, "op");
1471 }
1472 out.endTag(null, "uid");
1473 }
1474 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001475
1476 if (allOps != null) {
1477 String lastPkg = null;
1478 for (int i=0; i<allOps.size(); i++) {
1479 AppOpsManager.PackageOps pkg = allOps.get(i);
1480 if (!pkg.getPackageName().equals(lastPkg)) {
1481 if (lastPkg != null) {
1482 out.endTag(null, "pkg");
1483 }
1484 lastPkg = pkg.getPackageName();
1485 out.startTag(null, "pkg");
1486 out.attribute(null, "n", lastPkg);
1487 }
1488 out.startTag(null, "uid");
1489 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04001490 synchronized (this) {
1491 Ops ops = getOpsLocked(pkg.getUid(), pkg.getPackageName(), false);
1492 // Should always be present as the list of PackageOps is generated
1493 // from Ops.
1494 if (ops != null) {
1495 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
1496 } else {
1497 out.attribute(null, "p", Boolean.toString(false));
1498 }
1499 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001500 List<AppOpsManager.OpEntry> ops = pkg.getOps();
1501 for (int j=0; j<ops.size(); j++) {
1502 AppOpsManager.OpEntry op = ops.get(j);
1503 out.startTag(null, "op");
1504 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07001505 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001506 out.attribute(null, "m", Integer.toString(op.getMode()));
1507 }
1508 long time = op.getTime();
1509 if (time != 0) {
1510 out.attribute(null, "t", Long.toString(time));
1511 }
1512 time = op.getRejectTime();
1513 if (time != 0) {
1514 out.attribute(null, "r", Long.toString(time));
1515 }
1516 int dur = op.getDuration();
1517 if (dur != 0) {
1518 out.attribute(null, "d", Integer.toString(dur));
1519 }
Svet Ganov99b60432015-06-27 13:15:22 -07001520 int proxyUid = op.getProxyUid();
1521 if (proxyUid != -1) {
1522 out.attribute(null, "pu", Integer.toString(proxyUid));
1523 }
1524 String proxyPackageName = op.getProxyPackageName();
1525 if (proxyPackageName != null) {
1526 out.attribute(null, "pp", proxyPackageName);
1527 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001528 out.endTag(null, "op");
1529 }
1530 out.endTag(null, "uid");
1531 }
1532 if (lastPkg != null) {
1533 out.endTag(null, "pkg");
1534 }
1535 }
1536
1537 out.endTag(null, "app-ops");
1538 out.endDocument();
1539 mFile.finishWrite(stream);
1540 } catch (IOException e) {
1541 Slog.w(TAG, "Failed to write state, restoring backup.", e);
1542 mFile.failWrite(stream);
1543 }
1544 }
1545 }
1546
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001547 private void dumpHelp(PrintWriter pw) {
1548 pw.println("AppOps service (appops) dump options:");
1549 pw.println(" [-h] [CMD]");
1550 pw.println(" -h: print this help text.");
1551 pw.println("Commands:");
1552 pw.println(" write-settings");
1553 pw.println(" Immediately write pending changes to storage.");
1554 pw.println(" read-settings");
1555 pw.println(" Read the last written settings, replacing current state in RAM.");
1556 }
1557
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001558 @Override
1559 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1560 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1561 != PackageManager.PERMISSION_GRANTED) {
1562 pw.println("Permission Denial: can't dump ApOps service from from pid="
1563 + Binder.getCallingPid()
1564 + ", uid=" + Binder.getCallingUid());
1565 return;
1566 }
1567
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001568 if (args != null) {
1569 for (int i=0; i<args.length; i++) {
1570 String arg = args[i];
1571 if ("-h".equals(arg)) {
1572 dumpHelp(pw);
1573 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07001574 } else if ("-a".equals(arg)) {
1575 // dump all data
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07001576 } else if ("write-settings".equals(arg)) {
1577 long token = Binder.clearCallingIdentity();
1578 try {
1579 synchronized (this) {
1580 mHandler.removeCallbacks(mWriteRunner);
1581 }
1582 writeState();
1583 pw.println("Current settings written.");
1584 } finally {
1585 Binder.restoreCallingIdentity(token);
1586 }
1587 return;
1588 } else if ("read-settings".equals(arg)) {
1589 long token = Binder.clearCallingIdentity();
1590 try {
1591 readState();
1592 pw.println("Last settings read.");
1593 } finally {
1594 Binder.restoreCallingIdentity(token);
1595 }
1596 return;
1597 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
1598 pw.println("Unknown option: " + arg);
1599 return;
1600 } else {
1601 pw.println("Unknown command: " + arg);
1602 return;
1603 }
1604 }
1605 }
1606
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001607 synchronized (this) {
1608 pw.println("Current AppOps Service state:");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001609 final long now = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001610 boolean needSep = false;
1611 if (mOpModeWatchers.size() > 0) {
1612 needSep = true;
1613 pw.println(" Op mode watchers:");
1614 for (int i=0; i<mOpModeWatchers.size(); i++) {
1615 pw.print(" Op "); pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
1616 pw.println(":");
1617 ArrayList<Callback> callbacks = mOpModeWatchers.valueAt(i);
1618 for (int j=0; j<callbacks.size(); j++) {
1619 pw.print(" #"); pw.print(j); pw.print(": ");
1620 pw.println(callbacks.get(j));
1621 }
1622 }
1623 }
1624 if (mPackageModeWatchers.size() > 0) {
1625 needSep = true;
1626 pw.println(" Package mode watchers:");
1627 for (int i=0; i<mPackageModeWatchers.size(); i++) {
1628 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
1629 pw.println(":");
1630 ArrayList<Callback> callbacks = mPackageModeWatchers.valueAt(i);
1631 for (int j=0; j<callbacks.size(); j++) {
1632 pw.print(" #"); pw.print(j); pw.print(": ");
1633 pw.println(callbacks.get(j));
1634 }
1635 }
1636 }
1637 if (mModeWatchers.size() > 0) {
1638 needSep = true;
1639 pw.println(" All mode watchers:");
1640 for (int i=0; i<mModeWatchers.size(); i++) {
1641 pw.print(" "); pw.print(mModeWatchers.keyAt(i));
1642 pw.print(" -> "); pw.println(mModeWatchers.valueAt(i));
1643 }
1644 }
1645 if (mClients.size() > 0) {
1646 needSep = true;
1647 pw.println(" Clients:");
1648 for (int i=0; i<mClients.size(); i++) {
1649 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
1650 ClientState cs = mClients.valueAt(i);
1651 pw.print(" "); pw.println(cs);
1652 if (cs.mStartedOps != null && cs.mStartedOps.size() > 0) {
1653 pw.println(" Started ops:");
1654 for (int j=0; j<cs.mStartedOps.size(); j++) {
1655 Op op = cs.mStartedOps.get(j);
1656 pw.print(" "); pw.print("uid="); pw.print(op.uid);
1657 pw.print(" pkg="); pw.print(op.packageName);
1658 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
1659 }
1660 }
1661 }
1662 }
John Spurlock1af30c72014-03-10 08:33:35 -04001663 if (mAudioRestrictions.size() > 0) {
1664 boolean printedHeader = false;
1665 for (int o=0; o<mAudioRestrictions.size(); o++) {
1666 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
1667 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
1668 for (int i=0; i<restrictions.size(); i++) {
1669 if (!printedHeader){
1670 pw.println(" Audio Restrictions:");
1671 printedHeader = true;
1672 needSep = true;
1673 }
John Spurlock7b414672014-07-18 13:02:39 -04001674 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04001675 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04001676 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04001677 Restriction r = restrictions.valueAt(i);
1678 pw.print(": mode="); pw.println(r.mode);
1679 if (!r.exceptionPackages.isEmpty()) {
1680 pw.println(" Exceptions:");
1681 for (int j=0; j<r.exceptionPackages.size(); j++) {
1682 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
1683 }
1684 }
1685 }
1686 }
1687 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001688 if (needSep) {
1689 pw.println();
1690 }
Svet Ganov2af57082015-07-30 08:44:20 -07001691 for (int i=0; i<mUidStates.size(); i++) {
1692 UidState uidState = mUidStates.valueAt(i);
1693
1694 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
1695
1696 SparseIntArray opModes = uidState.opModes;
1697 if (opModes != null) {
1698 final int opModeCount = opModes.size();
1699 for (int j = 0; j < opModeCount; j++) {
1700 final int code = opModes.keyAt(j);
1701 final int mode = opModes.valueAt(j);
1702 pw.print(" "); pw.print(AppOpsManager.opToName(code));
1703 pw.print(": mode="); pw.println(mode);
1704 }
1705 }
1706
1707 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
1708 if (pkgOps == null) {
1709 continue;
1710 }
1711
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001712 for (Ops ops : pkgOps.values()) {
1713 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
1714 for (int j=0; j<ops.size(); j++) {
1715 Op op = ops.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001716 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
1717 pw.print(": mode="); pw.print(op.mode);
1718 if (op.time != 0) {
1719 pw.print("; time="); TimeUtils.formatDuration(now-op.time, pw);
1720 pw.print(" ago");
1721 }
1722 if (op.rejectTime != 0) {
1723 pw.print("; rejectTime="); TimeUtils.formatDuration(now-op.rejectTime, pw);
1724 pw.print(" ago");
1725 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001726 if (op.duration == -1) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001727 pw.print(" (running)");
1728 } else if (op.duration != 0) {
1729 pw.print("; duration="); TimeUtils.formatDuration(op.duration, pw);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001730 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001731 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001732 }
1733 }
1734 }
1735 }
1736 }
John Spurlock1af30c72014-03-10 08:33:35 -04001737
1738 private static final class Restriction {
1739 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
1740 int mode;
1741 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
1742 }
Jason Monk62062992014-05-06 09:55:28 -04001743
1744 @Override
Jason Monk62062992014-05-06 09:55:28 -04001745 public void setUserRestrictions(Bundle restrictions, int userHandle) throws RemoteException {
1746 checkSystemUid("setUserRestrictions");
1747 boolean[] opRestrictions = mOpRestrictions.get(userHandle);
1748 if (opRestrictions == null) {
1749 opRestrictions = new boolean[AppOpsManager._NUM_OP];
1750 mOpRestrictions.put(userHandle, opRestrictions);
1751 }
1752 for (int i = 0; i < opRestrictions.length; ++i) {
1753 String restriction = AppOpsManager.opToRestriction(i);
1754 if (restriction != null) {
1755 opRestrictions[i] = restrictions.getBoolean(restriction, false);
1756 } else {
1757 opRestrictions[i] = false;
1758 }
1759 }
1760 }
1761
1762 @Override
1763 public void removeUser(int userHandle) throws RemoteException {
1764 checkSystemUid("removeUser");
1765 mOpRestrictions.remove(userHandle);
Jason Monk62062992014-05-06 09:55:28 -04001766 }
1767
1768 private void checkSystemUid(String function) {
1769 int uid = Binder.getCallingUid();
1770 if (uid != Process.SYSTEM_UID) {
1771 throw new SecurityException(function + " must by called by the system");
1772 }
1773 }
1774
Svet Ganov2af57082015-07-30 08:44:20 -07001775 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07001776 String[] packageNames = null;
Svet Ganov2af57082015-07-30 08:44:20 -07001777 try {
riddle_hsu40b300f2015-11-23 13:22:03 +08001778 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -07001779 } catch (RemoteException e) {
1780 /* ignore - local call */
1781 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07001782 if (packageNames == null) {
1783 return EmptyArray.STRING;
1784 }
1785 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07001786 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001787}