blob: 42a5195ac6467f812f5012d6959d10ec1b46d99d [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;
Dianne Hackborn35654b62013-01-14 17:38:02 -080026import java.util.ArrayList;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080027import java.util.HashMap;
Dianne Hackbornc2293022013-02-06 23:14:49 -080028import java.util.Iterator;
Dianne Hackborn35654b62013-01-14 17:38:02 -080029import java.util.List;
Dianne Hackborn607b4142013-08-02 18:10:10 -070030import java.util.Map;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080031
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -080032import android.app.ActivityManager;
Jason Monk1c7c3192014-06-26 12:52:18 -040033import android.app.ActivityThread;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080034import android.app.AppOpsManager;
35import android.content.Context;
Jason Monk1c7c3192014-06-26 12:52:18 -040036import android.content.pm.ApplicationInfo;
37import android.content.pm.IPackageManager;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080038import android.content.pm.PackageManager;
39import android.content.pm.PackageManager.NameNotFoundException;
John Spurlock7b414672014-07-18 13:02:39 -040040import android.media.AudioAttributes;
Dianne Hackborn35654b62013-01-14 17:38:02 -080041import android.os.AsyncTask;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080042import android.os.Binder;
Jason Monk62062992014-05-06 09:55:28 -040043import android.os.Bundle;
Dianne Hackborn35654b62013-01-14 17:38:02 -080044import android.os.Handler;
Dianne Hackbornc2293022013-02-06 23:14:49 -080045import android.os.IBinder;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080046import android.os.Process;
Dianne Hackbornc2293022013-02-06 23:14:49 -080047import android.os.RemoteException;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080048import android.os.ServiceManager;
49import android.os.UserHandle;
Dianne Hackborne98f5db2013-07-17 17:23:25 -070050import android.util.ArrayMap;
John Spurlock1af30c72014-03-10 08:33:35 -040051import android.util.ArraySet;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080052import android.util.AtomicFile;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -080053import android.util.Log;
Dianne Hackborn607b4142013-08-02 18:10:10 -070054import android.util.Pair;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080055import android.util.Slog;
56import android.util.SparseArray;
57import android.util.TimeUtils;
Dianne Hackborn35654b62013-01-14 17:38:02 -080058import android.util.Xml;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080059
60import com.android.internal.app.IAppOpsService;
Dianne Hackbornc2293022013-02-06 23:14:49 -080061import com.android.internal.app.IAppOpsCallback;
Dianne Hackborn35654b62013-01-14 17:38:02 -080062import com.android.internal.util.FastXmlSerializer;
63import com.android.internal.util.XmlUtils;
64
65import org.xmlpull.v1.XmlPullParser;
66import org.xmlpull.v1.XmlPullParserException;
67import org.xmlpull.v1.XmlSerializer;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080068
69public class AppOpsService extends IAppOpsService.Stub {
70 static final String TAG = "AppOps";
Dianne Hackborn35654b62013-01-14 17:38:02 -080071 static final boolean DEBUG = false;
72
73 // Write at most every 30 minutes.
74 static final long WRITE_DELAY = DEBUG ? 1000 : 30*60*1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080075
76 Context mContext;
77 final AtomicFile mFile;
Dianne Hackborn35654b62013-01-14 17:38:02 -080078 final Handler mHandler;
79
80 boolean mWriteScheduled;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -080081 boolean mFastWriteScheduled;
Dianne Hackborn35654b62013-01-14 17:38:02 -080082 final Runnable mWriteRunner = new Runnable() {
83 public void run() {
84 synchronized (AppOpsService.this) {
85 mWriteScheduled = false;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -080086 mFastWriteScheduled = false;
Dianne Hackborn35654b62013-01-14 17:38:02 -080087 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
88 @Override protected Void doInBackground(Void... params) {
89 writeState();
90 return null;
91 }
92 };
93 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
94 }
95 }
96 };
Dianne Hackborna06de0f2012-12-11 16:34:47 -080097
98 final SparseArray<HashMap<String, Ops>> mUidOps
99 = new SparseArray<HashMap<String, Ops>>();
100
Jason Monk62062992014-05-06 09:55:28 -0400101 private final SparseArray<boolean[]> mOpRestrictions = new SparseArray<boolean[]>();
102
Dianne Hackbornc2293022013-02-06 23:14:49 -0800103 public final static class Ops extends SparseArray<Op> {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800104 public final String packageName;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800105 public final int uid;
Jason Monk1c7c3192014-06-26 12:52:18 -0400106 public final boolean isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800107
Jason Monk1c7c3192014-06-26 12:52:18 -0400108 public Ops(String _packageName, int _uid, boolean _isPrivileged) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800109 packageName = _packageName;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800110 uid = _uid;
Jason Monk1c7c3192014-06-26 12:52:18 -0400111 isPrivileged = _isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800112 }
113 }
114
Dianne Hackbornc2293022013-02-06 23:14:49 -0800115 public final static class Op {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700116 public final int uid;
117 public final String packageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800118 public final int op;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800119 public int mode;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800120 public int duration;
121 public long time;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800122 public long rejectTime;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800123 public int nesting;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800124
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700125 public Op(int _uid, String _packageName, int _op) {
126 uid = _uid;
127 packageName = _packageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800128 op = _op;
David Braunf5d83192013-09-16 13:43:51 -0700129 mode = AppOpsManager.opToDefaultMode(op);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800130 }
131 }
132
Dianne Hackbornc2293022013-02-06 23:14:49 -0800133 final SparseArray<ArrayList<Callback>> mOpModeWatchers
134 = new SparseArray<ArrayList<Callback>>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700135 final ArrayMap<String, ArrayList<Callback>> mPackageModeWatchers
136 = new ArrayMap<String, ArrayList<Callback>>();
137 final ArrayMap<IBinder, Callback> mModeWatchers
138 = new ArrayMap<IBinder, Callback>();
John Spurlock1af30c72014-03-10 08:33:35 -0400139 final SparseArray<SparseArray<Restriction>> mAudioRestrictions
140 = new SparseArray<SparseArray<Restriction>>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800141
142 public final class Callback implements DeathRecipient {
143 final IAppOpsCallback mCallback;
144
145 public Callback(IAppOpsCallback callback) {
146 mCallback = callback;
147 try {
148 mCallback.asBinder().linkToDeath(this, 0);
149 } catch (RemoteException e) {
150 }
151 }
152
153 public void unlinkToDeath() {
154 mCallback.asBinder().unlinkToDeath(this, 0);
155 }
156
157 @Override
158 public void binderDied() {
159 stopWatchingMode(mCallback);
160 }
161 }
162
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700163 final ArrayMap<IBinder, ClientState> mClients = new ArrayMap<IBinder, ClientState>();
164
165 public final class ClientState extends Binder implements DeathRecipient {
166 final IBinder mAppToken;
167 final int mPid;
168 final ArrayList<Op> mStartedOps;
169
170 public ClientState(IBinder appToken) {
171 mAppToken = appToken;
172 mPid = Binder.getCallingPid();
173 if (appToken instanceof Binder) {
174 // For local clients, there is no reason to track them.
175 mStartedOps = null;
176 } else {
177 mStartedOps = new ArrayList<Op>();
178 try {
179 mAppToken.linkToDeath(this, 0);
180 } catch (RemoteException e) {
181 }
182 }
183 }
184
185 @Override
186 public String toString() {
187 return "ClientState{" +
188 "mAppToken=" + mAppToken +
189 ", " + (mStartedOps != null ? ("pid=" + mPid) : "local") +
190 '}';
191 }
192
193 @Override
194 public void binderDied() {
195 synchronized (AppOpsService.this) {
196 for (int i=mStartedOps.size()-1; i>=0; i--) {
197 finishOperationLocked(mStartedOps.get(i));
198 }
199 mClients.remove(mAppToken);
200 }
201 }
202 }
203
Jeff Brown6f357d32014-01-15 20:40:55 -0800204 public AppOpsService(File storagePath, Handler handler) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800205 mFile = new AtomicFile(storagePath);
Jeff Brown6f357d32014-01-15 20:40:55 -0800206 mHandler = handler;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800207 readState();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800208 }
David Braunf5d83192013-09-16 13:43:51 -0700209
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800210 public void publish(Context context) {
211 mContext = context;
212 ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
213 }
214
Dianne Hackborn514074f2013-02-11 10:52:46 -0800215 public void systemReady() {
216 synchronized (this) {
217 boolean changed = false;
218 for (int i=0; i<mUidOps.size(); i++) {
219 HashMap<String, Ops> pkgs = mUidOps.valueAt(i);
220 Iterator<Ops> it = pkgs.values().iterator();
221 while (it.hasNext()) {
222 Ops ops = it.next();
223 int curUid;
224 try {
225 curUid = mContext.getPackageManager().getPackageUid(ops.packageName,
226 UserHandle.getUserId(ops.uid));
227 } catch (NameNotFoundException e) {
228 curUid = -1;
229 }
230 if (curUid != ops.uid) {
231 Slog.i(TAG, "Pruning old package " + ops.packageName
232 + "/" + ops.uid + ": new uid=" + curUid);
233 it.remove();
234 changed = true;
235 }
236 }
237 if (pkgs.size() <= 0) {
238 mUidOps.removeAt(i);
239 }
240 }
241 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800242 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800243 }
244 }
245 }
246
247 public void packageRemoved(int uid, String packageName) {
248 synchronized (this) {
249 HashMap<String, Ops> pkgs = mUidOps.get(uid);
250 if (pkgs != null) {
251 if (pkgs.remove(packageName) != null) {
252 if (pkgs.size() <= 0) {
253 mUidOps.remove(uid);
254 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800255 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800256 }
257 }
258 }
259 }
260
261 public void uidRemoved(int uid) {
262 synchronized (this) {
263 if (mUidOps.indexOfKey(uid) >= 0) {
264 mUidOps.remove(uid);
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800265 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800266 }
267 }
268 }
269
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800270 public void shutdown() {
271 Slog.w(TAG, "Writing app ops before shutdown...");
Dianne Hackborn35654b62013-01-14 17:38:02 -0800272 boolean doWrite = false;
273 synchronized (this) {
274 if (mWriteScheduled) {
275 mWriteScheduled = false;
276 doWrite = true;
277 }
278 }
279 if (doWrite) {
280 writeState();
281 }
282 }
283
Dianne Hackborn72e39832013-01-18 18:36:09 -0800284 private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
285 ArrayList<AppOpsManager.OpEntry> resOps = null;
286 if (ops == null) {
287 resOps = new ArrayList<AppOpsManager.OpEntry>();
288 for (int j=0; j<pkgOps.size(); j++) {
289 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800290 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
291 curOp.rejectTime, curOp.duration));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800292 }
293 } else {
294 for (int j=0; j<ops.length; j++) {
295 Op curOp = pkgOps.get(ops[j]);
296 if (curOp != null) {
297 if (resOps == null) {
298 resOps = new ArrayList<AppOpsManager.OpEntry>();
299 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800300 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
301 curOp.rejectTime, curOp.duration));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800302 }
303 }
304 }
305 return resOps;
306 }
307
Dianne Hackborn35654b62013-01-14 17:38:02 -0800308 @Override
309 public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
310 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
311 Binder.getCallingPid(), Binder.getCallingUid(), null);
312 ArrayList<AppOpsManager.PackageOps> res = null;
313 synchronized (this) {
314 for (int i=0; i<mUidOps.size(); i++) {
315 HashMap<String, Ops> packages = mUidOps.valueAt(i);
316 for (Ops pkgOps : packages.values()) {
Dianne Hackborn72e39832013-01-18 18:36:09 -0800317 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800318 if (resOps != null) {
319 if (res == null) {
320 res = new ArrayList<AppOpsManager.PackageOps>();
321 }
322 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
323 pkgOps.packageName, pkgOps.uid, resOps);
324 res.add(resPackage);
325 }
326 }
327 }
328 }
329 return res;
330 }
331
332 @Override
Dianne Hackborn72e39832013-01-18 18:36:09 -0800333 public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
334 int[] ops) {
335 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
336 Binder.getCallingPid(), Binder.getCallingUid(), null);
337 synchronized (this) {
338 Ops pkgOps = getOpsLocked(uid, packageName, false);
339 if (pkgOps == null) {
340 return null;
341 }
342 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
343 if (resOps == null) {
344 return null;
345 }
346 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
347 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
348 pkgOps.packageName, pkgOps.uid, resOps);
349 res.add(resPackage);
350 return res;
351 }
352 }
353
Dianne Hackborn607b4142013-08-02 18:10:10 -0700354 private void pruneOp(Op op, int uid, String packageName) {
355 if (op.time == 0 && op.rejectTime == 0) {
356 Ops ops = getOpsLocked(uid, packageName, false);
357 if (ops != null) {
358 ops.remove(op.op);
359 if (ops.size() <= 0) {
360 HashMap<String, Ops> pkgOps = mUidOps.get(uid);
361 if (pkgOps != null) {
362 pkgOps.remove(ops.packageName);
363 if (pkgOps.size() <= 0) {
364 mUidOps.remove(uid);
365 }
366 }
367 }
368 }
369 }
370 }
371
Dianne Hackborn72e39832013-01-18 18:36:09 -0800372 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800373 public void setMode(int code, int uid, String packageName, int mode) {
Dianne Hackbornb64afe12014-07-22 16:29:04 -0700374 if (Binder.getCallingPid() != Process.myPid()) {
375 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
376 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborn133b9df2014-07-01 13:06:10 -0700377 }
Dianne Hackborn961321f2013-02-05 17:22:41 -0800378 verifyIncomingOp(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800379 ArrayList<Callback> repCbs = null;
380 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800381 synchronized (this) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800382 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800383 if (op != null) {
384 if (op.mode != mode) {
385 op.mode = mode;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800386 ArrayList<Callback> cbs = mOpModeWatchers.get(code);
387 if (cbs != null) {
388 if (repCbs == null) {
389 repCbs = new ArrayList<Callback>();
390 }
391 repCbs.addAll(cbs);
392 }
393 cbs = mPackageModeWatchers.get(packageName);
394 if (cbs != null) {
395 if (repCbs == null) {
396 repCbs = new ArrayList<Callback>();
397 }
398 repCbs.addAll(cbs);
399 }
David Braunf5d83192013-09-16 13:43:51 -0700400 if (mode == AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800401 // If going into the default mode, prune this op
402 // if there is nothing else interesting in it.
Dianne Hackborn607b4142013-08-02 18:10:10 -0700403 pruneOp(op, uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800404 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800405 scheduleFastWriteLocked();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800406 }
407 }
408 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800409 if (repCbs != null) {
410 for (int i=0; i<repCbs.size(); i++) {
411 try {
412 repCbs.get(i).mCallback.opChanged(code, packageName);
413 } catch (RemoteException e) {
414 }
415 }
416 }
417 }
418
Dianne Hackborn607b4142013-08-02 18:10:10 -0700419 private static HashMap<Callback, ArrayList<Pair<String, Integer>>> addCallbacks(
420 HashMap<Callback, ArrayList<Pair<String, Integer>>> callbacks,
421 String packageName, int op, ArrayList<Callback> cbs) {
422 if (cbs == null) {
423 return callbacks;
424 }
425 if (callbacks == null) {
426 callbacks = new HashMap<Callback, ArrayList<Pair<String, Integer>>>();
427 }
428 for (int i=0; i<cbs.size(); i++) {
429 Callback cb = cbs.get(i);
430 ArrayList<Pair<String, Integer>> reports = callbacks.get(cb);
431 if (reports == null) {
432 reports = new ArrayList<Pair<String, Integer>>();
433 callbacks.put(cb, reports);
434 }
435 reports.add(new Pair<String, Integer>(packageName, op));
436 }
437 return callbacks;
438 }
439
440 @Override
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800441 public void resetAllModes(int reqUserId, String reqPackageName) {
442 final int callingPid = Binder.getCallingPid();
443 final int callingUid = Binder.getCallingUid();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700444 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800445 callingPid, callingUid, null);
446 reqUserId = ActivityManager.handleIncomingUser(callingPid, callingUid, reqUserId,
447 true, true, "resetAllModes", null);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700448 HashMap<Callback, ArrayList<Pair<String, Integer>>> callbacks = null;
449 synchronized (this) {
450 boolean changed = false;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700451 for (int i=mUidOps.size()-1; i>=0; i--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700452 HashMap<String, Ops> packages = mUidOps.valueAt(i);
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800453 if (reqUserId != UserHandle.USER_ALL
454 && reqUserId != UserHandle.getUserId(mUidOps.keyAt(i))) {
Alexandra Gherghinad6a98972014-08-04 17:05:34 +0100455 // Skip any ops for a different user
456 continue;
457 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700458 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
459 while (it.hasNext()) {
460 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700461 String packageName = ent.getKey();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800462 if (reqPackageName != null && !reqPackageName.equals(packageName)) {
463 // Skip any ops for a different package
464 continue;
465 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700466 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700467 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700468 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -0700469 if (AppOpsManager.opAllowsReset(curOp.op)
470 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -0700471 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700472 changed = true;
473 callbacks = addCallbacks(callbacks, packageName, curOp.op,
474 mOpModeWatchers.get(curOp.op));
475 callbacks = addCallbacks(callbacks, packageName, curOp.op,
476 mPackageModeWatchers.get(packageName));
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700477 if (curOp.time == 0 && curOp.rejectTime == 0) {
478 pkgOps.removeAt(j);
479 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700480 }
481 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700482 if (pkgOps.size() == 0) {
483 it.remove();
484 }
485 }
486 if (packages.size() == 0) {
487 mUidOps.removeAt(i);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700488 }
489 }
490 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800491 scheduleFastWriteLocked();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700492 }
493 }
494 if (callbacks != null) {
495 for (Map.Entry<Callback, ArrayList<Pair<String, Integer>>> ent : callbacks.entrySet()) {
496 Callback cb = ent.getKey();
497 ArrayList<Pair<String, Integer>> reports = ent.getValue();
498 for (int i=0; i<reports.size(); i++) {
499 Pair<String, Integer> rep = reports.get(i);
500 try {
501 cb.mCallback.opChanged(rep.second, rep.first);
502 } catch (RemoteException e) {
503 }
504 }
505 }
506 }
507 }
508
Dianne Hackbornc2293022013-02-06 23:14:49 -0800509 @Override
510 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
511 synchronized (this) {
512 op = AppOpsManager.opToSwitch(op);
513 Callback cb = mModeWatchers.get(callback.asBinder());
514 if (cb == null) {
515 cb = new Callback(callback);
516 mModeWatchers.put(callback.asBinder(), cb);
517 }
518 if (op != AppOpsManager.OP_NONE) {
519 ArrayList<Callback> cbs = mOpModeWatchers.get(op);
520 if (cbs == null) {
521 cbs = new ArrayList<Callback>();
522 mOpModeWatchers.put(op, cbs);
523 }
524 cbs.add(cb);
525 }
526 if (packageName != null) {
527 ArrayList<Callback> cbs = mPackageModeWatchers.get(packageName);
528 if (cbs == null) {
529 cbs = new ArrayList<Callback>();
530 mPackageModeWatchers.put(packageName, cbs);
531 }
532 cbs.add(cb);
533 }
534 }
535 }
536
537 @Override
538 public void stopWatchingMode(IAppOpsCallback callback) {
539 synchronized (this) {
540 Callback cb = mModeWatchers.remove(callback.asBinder());
541 if (cb != null) {
542 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700543 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800544 ArrayList<Callback> cbs = mOpModeWatchers.valueAt(i);
545 cbs.remove(cb);
546 if (cbs.size() <= 0) {
547 mOpModeWatchers.removeAt(i);
548 }
549 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700550 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
551 ArrayList<Callback> cbs = mPackageModeWatchers.valueAt(i);
552 cbs.remove(cb);
553 if (cbs.size() <= 0) {
554 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800555 }
556 }
557 }
558 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800559 }
560
561 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700562 public IBinder getToken(IBinder clientToken) {
563 synchronized (this) {
564 ClientState cs = mClients.get(clientToken);
565 if (cs == null) {
566 cs = new ClientState(clientToken);
567 mClients.put(clientToken, cs);
568 }
569 return cs;
570 }
571 }
572
573 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800574 public int checkOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800575 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800576 verifyIncomingOp(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800577 synchronized (this) {
Jason Monk1c7c3192014-06-26 12:52:18 -0400578 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -0400579 return AppOpsManager.MODE_IGNORED;
580 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800581 Op op = getOpLocked(AppOpsManager.opToSwitch(code), uid, packageName, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800582 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -0700583 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800584 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800585 return op.mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800586 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800587 }
588
589 @Override
John Spurlock7b414672014-07-18 13:02:39 -0400590 public int checkAudioOperation(int code, int usage, int uid, String packageName) {
John Spurlock1af30c72014-03-10 08:33:35 -0400591 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -0400592 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -0400593 if (mode != AppOpsManager.MODE_ALLOWED) {
594 return mode;
595 }
596 }
597 return checkOperation(code, uid, packageName);
598 }
599
John Spurlock7b414672014-07-18 13:02:39 -0400600 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
601 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
602 if (usageRestrictions != null) {
603 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -0400604 if (r != null && !r.exceptionPackages.contains(packageName)) {
605 return r.mode;
606 }
607 }
608 return AppOpsManager.MODE_ALLOWED;
609 }
610
611 @Override
John Spurlock7b414672014-07-18 13:02:39 -0400612 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -0400613 String[] exceptionPackages) {
614 verifyIncomingUid(uid);
615 verifyIncomingOp(code);
616 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -0400617 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
618 if (usageRestrictions == null) {
619 usageRestrictions = new SparseArray<Restriction>();
620 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -0400621 }
John Spurlock7b414672014-07-18 13:02:39 -0400622 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -0400623 if (mode != AppOpsManager.MODE_ALLOWED) {
624 final Restriction r = new Restriction();
625 r.mode = mode;
626 if (exceptionPackages != null) {
627 final int N = exceptionPackages.length;
628 r.exceptionPackages = new ArraySet<String>(N);
629 for (int i = 0; i < N; i++) {
630 final String pkg = exceptionPackages[i];
631 if (pkg != null) {
632 r.exceptionPackages.add(pkg.trim());
633 }
634 }
635 }
John Spurlock7b414672014-07-18 13:02:39 -0400636 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -0400637 }
638 }
639 }
640
641 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700642 public int checkPackage(int uid, String packageName) {
643 synchronized (this) {
Dianne Hackborn0fcef842014-09-12 15:38:33 -0700644 if (getOpsRawLocked(uid, packageName, true) != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700645 return AppOpsManager.MODE_ALLOWED;
646 } else {
647 return AppOpsManager.MODE_ERRORED;
648 }
649 }
650 }
651
652 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800653 public int noteOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800654 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800655 verifyIncomingOp(code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800656 synchronized (this) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800657 Ops ops = getOpsLocked(uid, packageName, true);
658 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800659 if (DEBUG) Log.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
660 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700661 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800662 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800663 Op op = getOpLocked(ops, code, true);
Jason Monk1c7c3192014-06-26 12:52:18 -0400664 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -0400665 return AppOpsManager.MODE_IGNORED;
666 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800667 if (op.duration == -1) {
668 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
669 + " code " + code + " time=" + op.time + " duration=" + op.duration);
670 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800671 op.duration = 0;
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800672 final int switchCode = AppOpsManager.opToSwitch(code);
673 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
674 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
675 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
676 + switchCode + " (" + code + ") uid " + uid + " package " + packageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800677 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800678 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800679 }
680 if (DEBUG) Log.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
681 + " package " + packageName);
682 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800683 op.rejectTime = 0;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800684 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800685 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800686 }
687
688 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700689 public int startOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800690 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800691 verifyIncomingOp(code);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700692 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800693 synchronized (this) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800694 Ops ops = getOpsLocked(uid, packageName, true);
695 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800696 if (DEBUG) Log.d(TAG, "startOperation: no op for code " + code + " uid " + uid
697 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700698 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800699 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800700 Op op = getOpLocked(ops, code, true);
Jason Monk1c7c3192014-06-26 12:52:18 -0400701 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -0400702 return AppOpsManager.MODE_IGNORED;
703 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800704 final int switchCode = AppOpsManager.opToSwitch(code);
705 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
706 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
707 if (DEBUG) Log.d(TAG, "startOperation: reject #" + op.mode + " for code "
708 + switchCode + " (" + code + ") uid " + uid + " package " + packageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800709 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800710 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800711 }
712 if (DEBUG) Log.d(TAG, "startOperation: allowing code " + code + " uid " + uid
713 + " package " + packageName);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800714 if (op.nesting == 0) {
715 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800716 op.rejectTime = 0;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800717 op.duration = -1;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800718 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800719 op.nesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700720 if (client.mStartedOps != null) {
721 client.mStartedOps.add(op);
722 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800723 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800724 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800725 }
726
727 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700728 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800729 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800730 verifyIncomingOp(code);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700731 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800732 synchronized (this) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800733 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800734 if (op == null) {
735 return;
736 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700737 if (client.mStartedOps != null) {
738 if (!client.mStartedOps.remove(op)) {
739 throw new IllegalStateException("Operation not started: uid" + op.uid
740 + " pkg=" + op.packageName + " op=" + op.op);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800741 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800742 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700743 finishOperationLocked(op);
744 }
745 }
746
747 void finishOperationLocked(Op op) {
748 if (op.nesting <= 1) {
749 if (op.nesting == 1) {
750 op.duration = (int)(System.currentTimeMillis() - op.time);
751 op.time += op.duration;
752 } else {
753 Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
754 + op.packageName + " code " + op.op + " time=" + op.time
755 + " duration=" + op.duration + " nesting=" + op.nesting);
756 }
757 op.nesting = 0;
758 } else {
759 op.nesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800760 }
761 }
762
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800763 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800764 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800765 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800766 }
767 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800768 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800769 }
770 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
771 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800772 }
773
Dianne Hackborn961321f2013-02-05 17:22:41 -0800774 private void verifyIncomingOp(int op) {
775 if (op >= 0 && op < AppOpsManager._NUM_OP) {
776 return;
777 }
778 throw new IllegalArgumentException("Bad operation #" + op);
779 }
780
Dianne Hackborn72e39832013-01-18 18:36:09 -0800781 private Ops getOpsLocked(int uid, String packageName, boolean edit) {
Dianne Hackborn0fcef842014-09-12 15:38:33 -0700782 if (uid == 0) {
783 packageName = "root";
784 } else if (uid == Process.SHELL_UID) {
785 packageName = "com.android.shell";
786 }
787 return getOpsRawLocked(uid, packageName, edit);
788 }
789
790 private Ops getOpsRawLocked(int uid, String packageName, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800791 HashMap<String, Ops> pkgOps = mUidOps.get(uid);
792 if (pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800793 if (!edit) {
794 return null;
795 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800796 pkgOps = new HashMap<String, Ops>();
797 mUidOps.put(uid, pkgOps);
798 }
799 Ops ops = pkgOps.get(packageName);
800 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800801 if (!edit) {
802 return null;
803 }
Jason Monk1c7c3192014-06-26 12:52:18 -0400804 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800805 // This is the first time we have seen this package name under this uid,
806 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -0800807 if (uid != 0) {
808 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800809 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800810 int pkgUid = -1;
811 try {
Jason Monk1c7c3192014-06-26 12:52:18 -0400812 ApplicationInfo appInfo = ActivityThread.getPackageManager()
813 .getApplicationInfo(packageName, 0, UserHandle.getUserId(uid));
814 if (appInfo != null) {
815 pkgUid = appInfo.uid;
816 isPrivileged = (appInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
817 } else {
818 if ("media".equals(packageName)) {
819 pkgUid = Process.MEDIA_UID;
820 isPrivileged = false;
821 }
Dianne Hackborn713df152013-05-17 11:27:57 -0700822 }
Jason Monk1c7c3192014-06-26 12:52:18 -0400823 } catch (RemoteException e) {
824 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800825 }
826 if (pkgUid != uid) {
827 // Oops! The package name is not valid for the uid they are calling
828 // under. Abort.
829 Slog.w(TAG, "Bad call: specified package " + packageName
830 + " under uid " + uid + " but it is really " + pkgUid);
831 return null;
832 }
833 } finally {
834 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800835 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800836 }
Jason Monk1c7c3192014-06-26 12:52:18 -0400837 ops = new Ops(packageName, uid, isPrivileged);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800838 pkgOps.put(packageName, ops);
839 }
Dianne Hackborn72e39832013-01-18 18:36:09 -0800840 return ops;
841 }
842
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800843 private void scheduleWriteLocked() {
844 if (!mWriteScheduled) {
845 mWriteScheduled = true;
846 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
847 }
848 }
849
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800850 private void scheduleFastWriteLocked() {
851 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800852 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800853 mFastWriteScheduled = true;
854 mHandler.removeCallbacks(mWriteRunner);
855 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800856 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800857 }
858
Dianne Hackborn72e39832013-01-18 18:36:09 -0800859 private Op getOpLocked(int code, int uid, String packageName, boolean edit) {
860 Ops ops = getOpsLocked(uid, packageName, edit);
861 if (ops == null) {
862 return null;
863 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800864 return getOpLocked(ops, code, edit);
865 }
866
867 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800868 Op op = ops.get(code);
869 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800870 if (!edit) {
871 return null;
872 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700873 op = new Op(ops.uid, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800874 ops.put(code, op);
875 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800876 if (edit) {
877 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -0800878 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800879 return op;
880 }
881
Jason Monk1c7c3192014-06-26 12:52:18 -0400882 private boolean isOpRestricted(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -0400883 int userHandle = UserHandle.getUserId(uid);
884 boolean[] opRestrictions = mOpRestrictions.get(userHandle);
885 if ((opRestrictions != null) && opRestrictions[code]) {
Jason Monk1c7c3192014-06-26 12:52:18 -0400886 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
887 synchronized (this) {
888 Ops ops = getOpsLocked(uid, packageName, true);
889 if ((ops != null) && ops.isPrivileged) {
890 return false;
891 }
892 }
893 }
Julia Reynolds401de172014-07-24 18:21:29 -0400894 return true;
Jason Monk62062992014-05-06 09:55:28 -0400895 }
896 return false;
897 }
898
Dianne Hackborn35654b62013-01-14 17:38:02 -0800899 void readState() {
900 synchronized (mFile) {
901 synchronized (this) {
902 FileInputStream stream;
903 try {
904 stream = mFile.openRead();
905 } catch (FileNotFoundException e) {
906 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
907 return;
908 }
909 boolean success = false;
910 try {
911 XmlPullParser parser = Xml.newPullParser();
912 parser.setInput(stream, null);
913 int type;
914 while ((type = parser.next()) != XmlPullParser.START_TAG
915 && type != XmlPullParser.END_DOCUMENT) {
916 ;
917 }
918
919 if (type != XmlPullParser.START_TAG) {
920 throw new IllegalStateException("no start tag found");
921 }
922
923 int outerDepth = parser.getDepth();
924 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
925 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
926 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
927 continue;
928 }
929
930 String tagName = parser.getName();
931 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +0000932 readPackage(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800933 } else {
934 Slog.w(TAG, "Unknown element under <app-ops>: "
935 + parser.getName());
936 XmlUtils.skipCurrentTag(parser);
937 }
938 }
939 success = true;
940 } catch (IllegalStateException e) {
941 Slog.w(TAG, "Failed parsing " + e);
942 } catch (NullPointerException e) {
943 Slog.w(TAG, "Failed parsing " + e);
944 } catch (NumberFormatException e) {
945 Slog.w(TAG, "Failed parsing " + e);
946 } catch (XmlPullParserException e) {
947 Slog.w(TAG, "Failed parsing " + e);
948 } catch (IOException e) {
949 Slog.w(TAG, "Failed parsing " + e);
950 } catch (IndexOutOfBoundsException e) {
951 Slog.w(TAG, "Failed parsing " + e);
952 } finally {
953 if (!success) {
954 mUidOps.clear();
955 }
956 try {
957 stream.close();
958 } catch (IOException e) {
959 }
960 }
961 }
962 }
963 }
964
Dave Burke0997c5bd2013-08-02 20:25:02 +0000965 void readPackage(XmlPullParser parser) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -0800966 XmlPullParserException, IOException {
967 String pkgName = parser.getAttributeValue(null, "n");
968 int outerDepth = parser.getDepth();
969 int type;
970 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
971 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
972 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
973 continue;
974 }
975
976 String tagName = parser.getName();
977 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +0000978 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800979 } else {
980 Slog.w(TAG, "Unknown element under <pkg>: "
981 + parser.getName());
982 XmlUtils.skipCurrentTag(parser);
983 }
984 }
985 }
986
Dave Burke0997c5bd2013-08-02 20:25:02 +0000987 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -0800988 XmlPullParserException, IOException {
989 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Jason Monk1c7c3192014-06-26 12:52:18 -0400990 String isPrivilegedString = parser.getAttributeValue(null, "p");
991 boolean isPrivileged = false;
992 if (isPrivilegedString == null) {
993 try {
994 IPackageManager packageManager = ActivityThread.getPackageManager();
995 if (packageManager != null) {
996 ApplicationInfo appInfo = ActivityThread.getPackageManager()
997 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
998 if (appInfo != null) {
999 isPrivileged = (appInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
1000 }
1001 } else {
1002 // Could not load data, don't add to cache so it will be loaded later.
1003 return;
1004 }
1005 } catch (RemoteException e) {
1006 Slog.w(TAG, "Could not contact PackageManager", e);
1007 }
1008 } else {
1009 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
1010 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001011 int outerDepth = parser.getDepth();
1012 int type;
1013 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1014 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1015 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1016 continue;
1017 }
1018
1019 String tagName = parser.getName();
1020 if (tagName.equals("op")) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001021 Op op = new Op(uid, pkgName, Integer.parseInt(parser.getAttributeValue(null, "n")));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001022 String mode = parser.getAttributeValue(null, "m");
1023 if (mode != null) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001024 op.mode = Integer.parseInt(mode);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001025 }
1026 String time = parser.getAttributeValue(null, "t");
1027 if (time != null) {
1028 op.time = Long.parseLong(time);
1029 }
1030 time = parser.getAttributeValue(null, "r");
1031 if (time != null) {
1032 op.rejectTime = Long.parseLong(time);
1033 }
1034 String dur = parser.getAttributeValue(null, "d");
1035 if (dur != null) {
1036 op.duration = Integer.parseInt(dur);
1037 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001038 HashMap<String, Ops> pkgOps = mUidOps.get(uid);
1039 if (pkgOps == null) {
1040 pkgOps = new HashMap<String, Ops>();
1041 mUidOps.put(uid, pkgOps);
1042 }
1043 Ops ops = pkgOps.get(pkgName);
1044 if (ops == null) {
Jason Monk1c7c3192014-06-26 12:52:18 -04001045 ops = new Ops(pkgName, uid, isPrivileged);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001046 pkgOps.put(pkgName, ops);
1047 }
1048 ops.put(op.op, op);
1049 } else {
1050 Slog.w(TAG, "Unknown element under <pkg>: "
1051 + parser.getName());
1052 XmlUtils.skipCurrentTag(parser);
1053 }
1054 }
1055 }
1056
1057 void writeState() {
1058 synchronized (mFile) {
1059 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
1060
1061 FileOutputStream stream;
1062 try {
1063 stream = mFile.startWrite();
1064 } catch (IOException e) {
1065 Slog.w(TAG, "Failed to write state: " + e);
1066 return;
1067 }
1068
1069 try {
1070 XmlSerializer out = new FastXmlSerializer();
1071 out.setOutput(stream, "utf-8");
1072 out.startDocument(null, true);
1073 out.startTag(null, "app-ops");
1074
1075 if (allOps != null) {
1076 String lastPkg = null;
1077 for (int i=0; i<allOps.size(); i++) {
1078 AppOpsManager.PackageOps pkg = allOps.get(i);
1079 if (!pkg.getPackageName().equals(lastPkg)) {
1080 if (lastPkg != null) {
1081 out.endTag(null, "pkg");
1082 }
1083 lastPkg = pkg.getPackageName();
1084 out.startTag(null, "pkg");
1085 out.attribute(null, "n", lastPkg);
1086 }
1087 out.startTag(null, "uid");
1088 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04001089 synchronized (this) {
1090 Ops ops = getOpsLocked(pkg.getUid(), pkg.getPackageName(), false);
1091 // Should always be present as the list of PackageOps is generated
1092 // from Ops.
1093 if (ops != null) {
1094 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
1095 } else {
1096 out.attribute(null, "p", Boolean.toString(false));
1097 }
1098 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001099 List<AppOpsManager.OpEntry> ops = pkg.getOps();
1100 for (int j=0; j<ops.size(); j++) {
1101 AppOpsManager.OpEntry op = ops.get(j);
1102 out.startTag(null, "op");
1103 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07001104 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001105 out.attribute(null, "m", Integer.toString(op.getMode()));
1106 }
1107 long time = op.getTime();
1108 if (time != 0) {
1109 out.attribute(null, "t", Long.toString(time));
1110 }
1111 time = op.getRejectTime();
1112 if (time != 0) {
1113 out.attribute(null, "r", Long.toString(time));
1114 }
1115 int dur = op.getDuration();
1116 if (dur != 0) {
1117 out.attribute(null, "d", Integer.toString(dur));
1118 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001119 out.endTag(null, "op");
1120 }
1121 out.endTag(null, "uid");
1122 }
1123 if (lastPkg != null) {
1124 out.endTag(null, "pkg");
1125 }
1126 }
1127
1128 out.endTag(null, "app-ops");
1129 out.endDocument();
1130 mFile.finishWrite(stream);
1131 } catch (IOException e) {
1132 Slog.w(TAG, "Failed to write state, restoring backup.", e);
1133 mFile.failWrite(stream);
1134 }
1135 }
1136 }
1137
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001138 @Override
1139 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1140 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1141 != PackageManager.PERMISSION_GRANTED) {
1142 pw.println("Permission Denial: can't dump ApOps service from from pid="
1143 + Binder.getCallingPid()
1144 + ", uid=" + Binder.getCallingUid());
1145 return;
1146 }
1147
1148 synchronized (this) {
1149 pw.println("Current AppOps Service state:");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001150 final long now = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001151 boolean needSep = false;
1152 if (mOpModeWatchers.size() > 0) {
1153 needSep = true;
1154 pw.println(" Op mode watchers:");
1155 for (int i=0; i<mOpModeWatchers.size(); i++) {
1156 pw.print(" Op "); pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
1157 pw.println(":");
1158 ArrayList<Callback> callbacks = mOpModeWatchers.valueAt(i);
1159 for (int j=0; j<callbacks.size(); j++) {
1160 pw.print(" #"); pw.print(j); pw.print(": ");
1161 pw.println(callbacks.get(j));
1162 }
1163 }
1164 }
1165 if (mPackageModeWatchers.size() > 0) {
1166 needSep = true;
1167 pw.println(" Package mode watchers:");
1168 for (int i=0; i<mPackageModeWatchers.size(); i++) {
1169 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
1170 pw.println(":");
1171 ArrayList<Callback> callbacks = mPackageModeWatchers.valueAt(i);
1172 for (int j=0; j<callbacks.size(); j++) {
1173 pw.print(" #"); pw.print(j); pw.print(": ");
1174 pw.println(callbacks.get(j));
1175 }
1176 }
1177 }
1178 if (mModeWatchers.size() > 0) {
1179 needSep = true;
1180 pw.println(" All mode watchers:");
1181 for (int i=0; i<mModeWatchers.size(); i++) {
1182 pw.print(" "); pw.print(mModeWatchers.keyAt(i));
1183 pw.print(" -> "); pw.println(mModeWatchers.valueAt(i));
1184 }
1185 }
1186 if (mClients.size() > 0) {
1187 needSep = true;
1188 pw.println(" Clients:");
1189 for (int i=0; i<mClients.size(); i++) {
1190 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
1191 ClientState cs = mClients.valueAt(i);
1192 pw.print(" "); pw.println(cs);
1193 if (cs.mStartedOps != null && cs.mStartedOps.size() > 0) {
1194 pw.println(" Started ops:");
1195 for (int j=0; j<cs.mStartedOps.size(); j++) {
1196 Op op = cs.mStartedOps.get(j);
1197 pw.print(" "); pw.print("uid="); pw.print(op.uid);
1198 pw.print(" pkg="); pw.print(op.packageName);
1199 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
1200 }
1201 }
1202 }
1203 }
John Spurlock1af30c72014-03-10 08:33:35 -04001204 if (mAudioRestrictions.size() > 0) {
1205 boolean printedHeader = false;
1206 for (int o=0; o<mAudioRestrictions.size(); o++) {
1207 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
1208 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
1209 for (int i=0; i<restrictions.size(); i++) {
1210 if (!printedHeader){
1211 pw.println(" Audio Restrictions:");
1212 printedHeader = true;
1213 needSep = true;
1214 }
John Spurlock7b414672014-07-18 13:02:39 -04001215 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04001216 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04001217 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04001218 Restriction r = restrictions.valueAt(i);
1219 pw.print(": mode="); pw.println(r.mode);
1220 if (!r.exceptionPackages.isEmpty()) {
1221 pw.println(" Exceptions:");
1222 for (int j=0; j<r.exceptionPackages.size(); j++) {
1223 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
1224 }
1225 }
1226 }
1227 }
1228 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001229 if (needSep) {
1230 pw.println();
1231 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001232 for (int i=0; i<mUidOps.size(); i++) {
1233 pw.print(" Uid "); UserHandle.formatUid(pw, mUidOps.keyAt(i)); pw.println(":");
1234 HashMap<String, Ops> pkgOps = mUidOps.valueAt(i);
1235 for (Ops ops : pkgOps.values()) {
1236 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
1237 for (int j=0; j<ops.size(); j++) {
1238 Op op = ops.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001239 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
1240 pw.print(": mode="); pw.print(op.mode);
1241 if (op.time != 0) {
1242 pw.print("; time="); TimeUtils.formatDuration(now-op.time, pw);
1243 pw.print(" ago");
1244 }
1245 if (op.rejectTime != 0) {
1246 pw.print("; rejectTime="); TimeUtils.formatDuration(now-op.rejectTime, pw);
1247 pw.print(" ago");
1248 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001249 if (op.duration == -1) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001250 pw.print(" (running)");
1251 } else if (op.duration != 0) {
1252 pw.print("; duration="); TimeUtils.formatDuration(op.duration, pw);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001253 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001254 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001255 }
1256 }
1257 }
1258 }
1259 }
John Spurlock1af30c72014-03-10 08:33:35 -04001260
1261 private static final class Restriction {
1262 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
1263 int mode;
1264 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
1265 }
Jason Monk62062992014-05-06 09:55:28 -04001266
1267 @Override
Jason Monk62062992014-05-06 09:55:28 -04001268 public void setUserRestrictions(Bundle restrictions, int userHandle) throws RemoteException {
1269 checkSystemUid("setUserRestrictions");
1270 boolean[] opRestrictions = mOpRestrictions.get(userHandle);
1271 if (opRestrictions == null) {
1272 opRestrictions = new boolean[AppOpsManager._NUM_OP];
1273 mOpRestrictions.put(userHandle, opRestrictions);
1274 }
1275 for (int i = 0; i < opRestrictions.length; ++i) {
1276 String restriction = AppOpsManager.opToRestriction(i);
1277 if (restriction != null) {
1278 opRestrictions[i] = restrictions.getBoolean(restriction, false);
1279 } else {
1280 opRestrictions[i] = false;
1281 }
1282 }
1283 }
1284
1285 @Override
1286 public void removeUser(int userHandle) throws RemoteException {
1287 checkSystemUid("removeUser");
1288 mOpRestrictions.remove(userHandle);
Jason Monk62062992014-05-06 09:55:28 -04001289 }
1290
1291 private void checkSystemUid(String function) {
1292 int uid = Binder.getCallingUid();
1293 if (uid != Process.SYSTEM_UID) {
1294 throw new SecurityException(function + " must by called by the system");
1295 }
1296 }
1297
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001298}