blob: 1366149a1c62e7629f3cfe5d29c11b6b03f7c95b [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
Svet Ganovb9d71a62015-04-30 10:38:13 -0700747 @Override
748 public int permissionToOpCode(String permission) {
749 return AppOpsManager.permissionToOpCode(permission);
750 }
751
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700752 void finishOperationLocked(Op op) {
753 if (op.nesting <= 1) {
754 if (op.nesting == 1) {
755 op.duration = (int)(System.currentTimeMillis() - op.time);
756 op.time += op.duration;
757 } else {
758 Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
759 + op.packageName + " code " + op.op + " time=" + op.time
760 + " duration=" + op.duration + " nesting=" + op.nesting);
761 }
762 op.nesting = 0;
763 } else {
764 op.nesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800765 }
766 }
767
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800768 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800769 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800770 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800771 }
772 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800773 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800774 }
775 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
776 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800777 }
778
Dianne Hackborn961321f2013-02-05 17:22:41 -0800779 private void verifyIncomingOp(int op) {
780 if (op >= 0 && op < AppOpsManager._NUM_OP) {
781 return;
782 }
783 throw new IllegalArgumentException("Bad operation #" + op);
784 }
785
Dianne Hackborn72e39832013-01-18 18:36:09 -0800786 private Ops getOpsLocked(int uid, String packageName, boolean edit) {
Dianne Hackborn0fcef842014-09-12 15:38:33 -0700787 if (uid == 0) {
788 packageName = "root";
789 } else if (uid == Process.SHELL_UID) {
790 packageName = "com.android.shell";
791 }
792 return getOpsRawLocked(uid, packageName, edit);
793 }
794
795 private Ops getOpsRawLocked(int uid, String packageName, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800796 HashMap<String, Ops> pkgOps = mUidOps.get(uid);
797 if (pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800798 if (!edit) {
799 return null;
800 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800801 pkgOps = new HashMap<String, Ops>();
802 mUidOps.put(uid, pkgOps);
803 }
804 Ops ops = pkgOps.get(packageName);
805 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800806 if (!edit) {
807 return null;
808 }
Jason Monk1c7c3192014-06-26 12:52:18 -0400809 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800810 // This is the first time we have seen this package name under this uid,
811 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -0800812 if (uid != 0) {
813 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800814 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800815 int pkgUid = -1;
816 try {
Jason Monk1c7c3192014-06-26 12:52:18 -0400817 ApplicationInfo appInfo = ActivityThread.getPackageManager()
818 .getApplicationInfo(packageName, 0, UserHandle.getUserId(uid));
819 if (appInfo != null) {
820 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800821 isPrivileged = (appInfo.privateFlags
822 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -0400823 } else {
824 if ("media".equals(packageName)) {
825 pkgUid = Process.MEDIA_UID;
826 isPrivileged = false;
827 }
Dianne Hackborn713df152013-05-17 11:27:57 -0700828 }
Jason Monk1c7c3192014-06-26 12:52:18 -0400829 } catch (RemoteException e) {
830 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800831 }
832 if (pkgUid != uid) {
833 // Oops! The package name is not valid for the uid they are calling
834 // under. Abort.
835 Slog.w(TAG, "Bad call: specified package " + packageName
836 + " under uid " + uid + " but it is really " + pkgUid);
837 return null;
838 }
839 } finally {
840 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800841 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800842 }
Jason Monk1c7c3192014-06-26 12:52:18 -0400843 ops = new Ops(packageName, uid, isPrivileged);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800844 pkgOps.put(packageName, ops);
845 }
Dianne Hackborn72e39832013-01-18 18:36:09 -0800846 return ops;
847 }
848
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800849 private void scheduleWriteLocked() {
850 if (!mWriteScheduled) {
851 mWriteScheduled = true;
852 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
853 }
854 }
855
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800856 private void scheduleFastWriteLocked() {
857 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800858 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800859 mFastWriteScheduled = true;
860 mHandler.removeCallbacks(mWriteRunner);
861 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800862 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800863 }
864
Dianne Hackborn72e39832013-01-18 18:36:09 -0800865 private Op getOpLocked(int code, int uid, String packageName, boolean edit) {
866 Ops ops = getOpsLocked(uid, packageName, edit);
867 if (ops == null) {
868 return null;
869 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800870 return getOpLocked(ops, code, edit);
871 }
872
873 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800874 Op op = ops.get(code);
875 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800876 if (!edit) {
877 return null;
878 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700879 op = new Op(ops.uid, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800880 ops.put(code, op);
881 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800882 if (edit) {
883 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -0800884 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800885 return op;
886 }
887
Jason Monk1c7c3192014-06-26 12:52:18 -0400888 private boolean isOpRestricted(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -0400889 int userHandle = UserHandle.getUserId(uid);
890 boolean[] opRestrictions = mOpRestrictions.get(userHandle);
891 if ((opRestrictions != null) && opRestrictions[code]) {
Jason Monk1c7c3192014-06-26 12:52:18 -0400892 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
893 synchronized (this) {
894 Ops ops = getOpsLocked(uid, packageName, true);
895 if ((ops != null) && ops.isPrivileged) {
896 return false;
897 }
898 }
899 }
Julia Reynolds401de172014-07-24 18:21:29 -0400900 return true;
Jason Monk62062992014-05-06 09:55:28 -0400901 }
902 return false;
903 }
904
Dianne Hackborn35654b62013-01-14 17:38:02 -0800905 void readState() {
906 synchronized (mFile) {
907 synchronized (this) {
908 FileInputStream stream;
909 try {
910 stream = mFile.openRead();
911 } catch (FileNotFoundException e) {
912 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
913 return;
914 }
915 boolean success = false;
916 try {
917 XmlPullParser parser = Xml.newPullParser();
918 parser.setInput(stream, null);
919 int type;
920 while ((type = parser.next()) != XmlPullParser.START_TAG
921 && type != XmlPullParser.END_DOCUMENT) {
922 ;
923 }
924
925 if (type != XmlPullParser.START_TAG) {
926 throw new IllegalStateException("no start tag found");
927 }
928
929 int outerDepth = parser.getDepth();
930 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
931 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
932 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
933 continue;
934 }
935
936 String tagName = parser.getName();
937 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +0000938 readPackage(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800939 } else {
940 Slog.w(TAG, "Unknown element under <app-ops>: "
941 + parser.getName());
942 XmlUtils.skipCurrentTag(parser);
943 }
944 }
945 success = true;
946 } catch (IllegalStateException e) {
947 Slog.w(TAG, "Failed parsing " + e);
948 } catch (NullPointerException e) {
949 Slog.w(TAG, "Failed parsing " + e);
950 } catch (NumberFormatException e) {
951 Slog.w(TAG, "Failed parsing " + e);
952 } catch (XmlPullParserException e) {
953 Slog.w(TAG, "Failed parsing " + e);
954 } catch (IOException e) {
955 Slog.w(TAG, "Failed parsing " + e);
956 } catch (IndexOutOfBoundsException e) {
957 Slog.w(TAG, "Failed parsing " + e);
958 } finally {
959 if (!success) {
960 mUidOps.clear();
961 }
962 try {
963 stream.close();
964 } catch (IOException e) {
965 }
966 }
967 }
968 }
969 }
970
Dave Burke0997c5bd2013-08-02 20:25:02 +0000971 void readPackage(XmlPullParser parser) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -0800972 XmlPullParserException, IOException {
973 String pkgName = parser.getAttributeValue(null, "n");
974 int outerDepth = parser.getDepth();
975 int type;
976 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
977 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
978 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
979 continue;
980 }
981
982 String tagName = parser.getName();
983 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +0000984 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800985 } else {
986 Slog.w(TAG, "Unknown element under <pkg>: "
987 + parser.getName());
988 XmlUtils.skipCurrentTag(parser);
989 }
990 }
991 }
992
Dave Burke0997c5bd2013-08-02 20:25:02 +0000993 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -0800994 XmlPullParserException, IOException {
995 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Jason Monk1c7c3192014-06-26 12:52:18 -0400996 String isPrivilegedString = parser.getAttributeValue(null, "p");
997 boolean isPrivileged = false;
998 if (isPrivilegedString == null) {
999 try {
1000 IPackageManager packageManager = ActivityThread.getPackageManager();
1001 if (packageManager != null) {
1002 ApplicationInfo appInfo = ActivityThread.getPackageManager()
1003 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
1004 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001005 isPrivileged = (appInfo.privateFlags
1006 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001007 }
1008 } else {
1009 // Could not load data, don't add to cache so it will be loaded later.
1010 return;
1011 }
1012 } catch (RemoteException e) {
1013 Slog.w(TAG, "Could not contact PackageManager", e);
1014 }
1015 } else {
1016 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
1017 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001018 int outerDepth = parser.getDepth();
1019 int type;
1020 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1021 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1022 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1023 continue;
1024 }
1025
1026 String tagName = parser.getName();
1027 if (tagName.equals("op")) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001028 Op op = new Op(uid, pkgName, Integer.parseInt(parser.getAttributeValue(null, "n")));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001029 String mode = parser.getAttributeValue(null, "m");
1030 if (mode != null) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001031 op.mode = Integer.parseInt(mode);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001032 }
1033 String time = parser.getAttributeValue(null, "t");
1034 if (time != null) {
1035 op.time = Long.parseLong(time);
1036 }
1037 time = parser.getAttributeValue(null, "r");
1038 if (time != null) {
1039 op.rejectTime = Long.parseLong(time);
1040 }
1041 String dur = parser.getAttributeValue(null, "d");
1042 if (dur != null) {
1043 op.duration = Integer.parseInt(dur);
1044 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001045 HashMap<String, Ops> pkgOps = mUidOps.get(uid);
1046 if (pkgOps == null) {
1047 pkgOps = new HashMap<String, Ops>();
1048 mUidOps.put(uid, pkgOps);
1049 }
1050 Ops ops = pkgOps.get(pkgName);
1051 if (ops == null) {
Jason Monk1c7c3192014-06-26 12:52:18 -04001052 ops = new Ops(pkgName, uid, isPrivileged);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001053 pkgOps.put(pkgName, ops);
1054 }
1055 ops.put(op.op, op);
1056 } else {
1057 Slog.w(TAG, "Unknown element under <pkg>: "
1058 + parser.getName());
1059 XmlUtils.skipCurrentTag(parser);
1060 }
1061 }
1062 }
1063
1064 void writeState() {
1065 synchronized (mFile) {
1066 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
1067
1068 FileOutputStream stream;
1069 try {
1070 stream = mFile.startWrite();
1071 } catch (IOException e) {
1072 Slog.w(TAG, "Failed to write state: " + e);
1073 return;
1074 }
1075
1076 try {
1077 XmlSerializer out = new FastXmlSerializer();
1078 out.setOutput(stream, "utf-8");
1079 out.startDocument(null, true);
1080 out.startTag(null, "app-ops");
1081
1082 if (allOps != null) {
1083 String lastPkg = null;
1084 for (int i=0; i<allOps.size(); i++) {
1085 AppOpsManager.PackageOps pkg = allOps.get(i);
1086 if (!pkg.getPackageName().equals(lastPkg)) {
1087 if (lastPkg != null) {
1088 out.endTag(null, "pkg");
1089 }
1090 lastPkg = pkg.getPackageName();
1091 out.startTag(null, "pkg");
1092 out.attribute(null, "n", lastPkg);
1093 }
1094 out.startTag(null, "uid");
1095 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04001096 synchronized (this) {
1097 Ops ops = getOpsLocked(pkg.getUid(), pkg.getPackageName(), false);
1098 // Should always be present as the list of PackageOps is generated
1099 // from Ops.
1100 if (ops != null) {
1101 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
1102 } else {
1103 out.attribute(null, "p", Boolean.toString(false));
1104 }
1105 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001106 List<AppOpsManager.OpEntry> ops = pkg.getOps();
1107 for (int j=0; j<ops.size(); j++) {
1108 AppOpsManager.OpEntry op = ops.get(j);
1109 out.startTag(null, "op");
1110 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07001111 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001112 out.attribute(null, "m", Integer.toString(op.getMode()));
1113 }
1114 long time = op.getTime();
1115 if (time != 0) {
1116 out.attribute(null, "t", Long.toString(time));
1117 }
1118 time = op.getRejectTime();
1119 if (time != 0) {
1120 out.attribute(null, "r", Long.toString(time));
1121 }
1122 int dur = op.getDuration();
1123 if (dur != 0) {
1124 out.attribute(null, "d", Integer.toString(dur));
1125 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001126 out.endTag(null, "op");
1127 }
1128 out.endTag(null, "uid");
1129 }
1130 if (lastPkg != null) {
1131 out.endTag(null, "pkg");
1132 }
1133 }
1134
1135 out.endTag(null, "app-ops");
1136 out.endDocument();
1137 mFile.finishWrite(stream);
1138 } catch (IOException e) {
1139 Slog.w(TAG, "Failed to write state, restoring backup.", e);
1140 mFile.failWrite(stream);
1141 }
1142 }
1143 }
1144
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001145 @Override
1146 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1147 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1148 != PackageManager.PERMISSION_GRANTED) {
1149 pw.println("Permission Denial: can't dump ApOps service from from pid="
1150 + Binder.getCallingPid()
1151 + ", uid=" + Binder.getCallingUid());
1152 return;
1153 }
1154
1155 synchronized (this) {
1156 pw.println("Current AppOps Service state:");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001157 final long now = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001158 boolean needSep = false;
1159 if (mOpModeWatchers.size() > 0) {
1160 needSep = true;
1161 pw.println(" Op mode watchers:");
1162 for (int i=0; i<mOpModeWatchers.size(); i++) {
1163 pw.print(" Op "); pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
1164 pw.println(":");
1165 ArrayList<Callback> callbacks = mOpModeWatchers.valueAt(i);
1166 for (int j=0; j<callbacks.size(); j++) {
1167 pw.print(" #"); pw.print(j); pw.print(": ");
1168 pw.println(callbacks.get(j));
1169 }
1170 }
1171 }
1172 if (mPackageModeWatchers.size() > 0) {
1173 needSep = true;
1174 pw.println(" Package mode watchers:");
1175 for (int i=0; i<mPackageModeWatchers.size(); i++) {
1176 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
1177 pw.println(":");
1178 ArrayList<Callback> callbacks = mPackageModeWatchers.valueAt(i);
1179 for (int j=0; j<callbacks.size(); j++) {
1180 pw.print(" #"); pw.print(j); pw.print(": ");
1181 pw.println(callbacks.get(j));
1182 }
1183 }
1184 }
1185 if (mModeWatchers.size() > 0) {
1186 needSep = true;
1187 pw.println(" All mode watchers:");
1188 for (int i=0; i<mModeWatchers.size(); i++) {
1189 pw.print(" "); pw.print(mModeWatchers.keyAt(i));
1190 pw.print(" -> "); pw.println(mModeWatchers.valueAt(i));
1191 }
1192 }
1193 if (mClients.size() > 0) {
1194 needSep = true;
1195 pw.println(" Clients:");
1196 for (int i=0; i<mClients.size(); i++) {
1197 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
1198 ClientState cs = mClients.valueAt(i);
1199 pw.print(" "); pw.println(cs);
1200 if (cs.mStartedOps != null && cs.mStartedOps.size() > 0) {
1201 pw.println(" Started ops:");
1202 for (int j=0; j<cs.mStartedOps.size(); j++) {
1203 Op op = cs.mStartedOps.get(j);
1204 pw.print(" "); pw.print("uid="); pw.print(op.uid);
1205 pw.print(" pkg="); pw.print(op.packageName);
1206 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
1207 }
1208 }
1209 }
1210 }
John Spurlock1af30c72014-03-10 08:33:35 -04001211 if (mAudioRestrictions.size() > 0) {
1212 boolean printedHeader = false;
1213 for (int o=0; o<mAudioRestrictions.size(); o++) {
1214 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
1215 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
1216 for (int i=0; i<restrictions.size(); i++) {
1217 if (!printedHeader){
1218 pw.println(" Audio Restrictions:");
1219 printedHeader = true;
1220 needSep = true;
1221 }
John Spurlock7b414672014-07-18 13:02:39 -04001222 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04001223 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04001224 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04001225 Restriction r = restrictions.valueAt(i);
1226 pw.print(": mode="); pw.println(r.mode);
1227 if (!r.exceptionPackages.isEmpty()) {
1228 pw.println(" Exceptions:");
1229 for (int j=0; j<r.exceptionPackages.size(); j++) {
1230 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
1231 }
1232 }
1233 }
1234 }
1235 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001236 if (needSep) {
1237 pw.println();
1238 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001239 for (int i=0; i<mUidOps.size(); i++) {
1240 pw.print(" Uid "); UserHandle.formatUid(pw, mUidOps.keyAt(i)); pw.println(":");
1241 HashMap<String, Ops> pkgOps = mUidOps.valueAt(i);
1242 for (Ops ops : pkgOps.values()) {
1243 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
1244 for (int j=0; j<ops.size(); j++) {
1245 Op op = ops.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001246 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
1247 pw.print(": mode="); pw.print(op.mode);
1248 if (op.time != 0) {
1249 pw.print("; time="); TimeUtils.formatDuration(now-op.time, pw);
1250 pw.print(" ago");
1251 }
1252 if (op.rejectTime != 0) {
1253 pw.print("; rejectTime="); TimeUtils.formatDuration(now-op.rejectTime, pw);
1254 pw.print(" ago");
1255 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001256 if (op.duration == -1) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001257 pw.print(" (running)");
1258 } else if (op.duration != 0) {
1259 pw.print("; duration="); TimeUtils.formatDuration(op.duration, pw);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001260 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001261 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001262 }
1263 }
1264 }
1265 }
1266 }
John Spurlock1af30c72014-03-10 08:33:35 -04001267
1268 private static final class Restriction {
1269 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
1270 int mode;
1271 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
1272 }
Jason Monk62062992014-05-06 09:55:28 -04001273
1274 @Override
Jason Monk62062992014-05-06 09:55:28 -04001275 public void setUserRestrictions(Bundle restrictions, int userHandle) throws RemoteException {
1276 checkSystemUid("setUserRestrictions");
1277 boolean[] opRestrictions = mOpRestrictions.get(userHandle);
1278 if (opRestrictions == null) {
1279 opRestrictions = new boolean[AppOpsManager._NUM_OP];
1280 mOpRestrictions.put(userHandle, opRestrictions);
1281 }
1282 for (int i = 0; i < opRestrictions.length; ++i) {
1283 String restriction = AppOpsManager.opToRestriction(i);
1284 if (restriction != null) {
1285 opRestrictions[i] = restrictions.getBoolean(restriction, false);
1286 } else {
1287 opRestrictions[i] = false;
1288 }
1289 }
1290 }
1291
1292 @Override
1293 public void removeUser(int userHandle) throws RemoteException {
1294 checkSystemUid("removeUser");
1295 mOpRestrictions.remove(userHandle);
Jason Monk62062992014-05-06 09:55:28 -04001296 }
1297
1298 private void checkSystemUid(String function) {
1299 int uid = Binder.getCallingUid();
1300 if (uid != Process.SYSTEM_UID) {
1301 throw new SecurityException(function + " must by called by the system");
1302 }
1303 }
1304
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001305}