blob: 7d427d6cb7b38d57793ce041379a151bd1af86ec [file] [log] [blame]
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import java.io.File;
20import java.io.FileDescriptor;
Dianne Hackborn35654b62013-01-14 17:38:02 -080021import java.io.FileInputStream;
22import java.io.FileNotFoundException;
23import java.io.FileOutputStream;
24import java.io.IOException;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080025import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010026import java.nio.charset.StandardCharsets;
Dianne Hackborn35654b62013-01-14 17:38:02 -080027import java.util.ArrayList;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080028import java.util.HashMap;
Dianne Hackbornc2293022013-02-06 23:14:49 -080029import java.util.Iterator;
Dianne Hackborn35654b62013-01-14 17:38:02 -080030import java.util.List;
Dianne Hackborn607b4142013-08-02 18:10:10 -070031import java.util.Map;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080032
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -080033import android.app.ActivityManager;
Jason Monk1c7c3192014-06-26 12:52:18 -040034import android.app.ActivityThread;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080035import android.app.AppOpsManager;
36import android.content.Context;
Jason Monk1c7c3192014-06-26 12:52:18 -040037import android.content.pm.ApplicationInfo;
38import android.content.pm.IPackageManager;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080039import android.content.pm.PackageManager;
40import android.content.pm.PackageManager.NameNotFoundException;
John Spurlock7b414672014-07-18 13:02:39 -040041import android.media.AudioAttributes;
Dianne Hackborn35654b62013-01-14 17:38:02 -080042import android.os.AsyncTask;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080043import android.os.Binder;
Jason Monk62062992014-05-06 09:55:28 -040044import android.os.Bundle;
Dianne Hackborn35654b62013-01-14 17:38:02 -080045import android.os.Handler;
Dianne Hackbornc2293022013-02-06 23:14:49 -080046import android.os.IBinder;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080047import android.os.Process;
Dianne Hackbornc2293022013-02-06 23:14:49 -080048import android.os.RemoteException;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080049import android.os.ServiceManager;
50import android.os.UserHandle;
Dianne Hackborne98f5db2013-07-17 17:23:25 -070051import android.util.ArrayMap;
John Spurlock1af30c72014-03-10 08:33:35 -040052import android.util.ArraySet;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080053import android.util.AtomicFile;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -080054import android.util.Log;
Dianne Hackborn607b4142013-08-02 18:10:10 -070055import android.util.Pair;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080056import android.util.Slog;
57import android.util.SparseArray;
58import android.util.TimeUtils;
Dianne Hackborn35654b62013-01-14 17:38:02 -080059import android.util.Xml;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080060
61import com.android.internal.app.IAppOpsService;
Dianne Hackbornc2293022013-02-06 23:14:49 -080062import com.android.internal.app.IAppOpsCallback;
Dianne Hackborn35654b62013-01-14 17:38:02 -080063import com.android.internal.util.FastXmlSerializer;
64import com.android.internal.util.XmlUtils;
65
66import org.xmlpull.v1.XmlPullParser;
67import org.xmlpull.v1.XmlPullParserException;
68import org.xmlpull.v1.XmlSerializer;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080069
70public class AppOpsService extends IAppOpsService.Stub {
71 static final String TAG = "AppOps";
Dianne Hackborn35654b62013-01-14 17:38:02 -080072 static final boolean DEBUG = false;
73
74 // Write at most every 30 minutes.
75 static final long WRITE_DELAY = DEBUG ? 1000 : 30*60*1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080076
77 Context mContext;
78 final AtomicFile mFile;
Dianne Hackborn35654b62013-01-14 17:38:02 -080079 final Handler mHandler;
80
81 boolean mWriteScheduled;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -080082 boolean mFastWriteScheduled;
Dianne Hackborn35654b62013-01-14 17:38:02 -080083 final Runnable mWriteRunner = new Runnable() {
84 public void run() {
85 synchronized (AppOpsService.this) {
86 mWriteScheduled = false;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -080087 mFastWriteScheduled = false;
Dianne Hackborn35654b62013-01-14 17:38:02 -080088 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
89 @Override protected Void doInBackground(Void... params) {
90 writeState();
91 return null;
92 }
93 };
94 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
95 }
96 }
97 };
Dianne Hackborna06de0f2012-12-11 16:34:47 -080098
99 final SparseArray<HashMap<String, Ops>> mUidOps
100 = new SparseArray<HashMap<String, Ops>>();
101
Jason Monk62062992014-05-06 09:55:28 -0400102 private final SparseArray<boolean[]> mOpRestrictions = new SparseArray<boolean[]>();
103
Dianne Hackbornc2293022013-02-06 23:14:49 -0800104 public final static class Ops extends SparseArray<Op> {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800105 public final String packageName;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800106 public final int uid;
Jason Monk1c7c3192014-06-26 12:52:18 -0400107 public final boolean isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800108
Jason Monk1c7c3192014-06-26 12:52:18 -0400109 public Ops(String _packageName, int _uid, boolean _isPrivileged) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800110 packageName = _packageName;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800111 uid = _uid;
Jason Monk1c7c3192014-06-26 12:52:18 -0400112 isPrivileged = _isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800113 }
114 }
115
Dianne Hackbornc2293022013-02-06 23:14:49 -0800116 public final static class Op {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700117 public final int uid;
118 public final String packageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800119 public final int op;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800120 public int mode;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800121 public int duration;
122 public long time;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800123 public long rejectTime;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800124 public int nesting;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800125
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700126 public Op(int _uid, String _packageName, int _op) {
127 uid = _uid;
128 packageName = _packageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800129 op = _op;
David Braunf5d83192013-09-16 13:43:51 -0700130 mode = AppOpsManager.opToDefaultMode(op);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800131 }
132 }
133
Dianne Hackbornc2293022013-02-06 23:14:49 -0800134 final SparseArray<ArrayList<Callback>> mOpModeWatchers
135 = new SparseArray<ArrayList<Callback>>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700136 final ArrayMap<String, ArrayList<Callback>> mPackageModeWatchers
137 = new ArrayMap<String, ArrayList<Callback>>();
138 final ArrayMap<IBinder, Callback> mModeWatchers
139 = new ArrayMap<IBinder, Callback>();
John Spurlock1af30c72014-03-10 08:33:35 -0400140 final SparseArray<SparseArray<Restriction>> mAudioRestrictions
141 = new SparseArray<SparseArray<Restriction>>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800142
143 public final class Callback implements DeathRecipient {
144 final IAppOpsCallback mCallback;
145
146 public Callback(IAppOpsCallback callback) {
147 mCallback = callback;
148 try {
149 mCallback.asBinder().linkToDeath(this, 0);
150 } catch (RemoteException e) {
151 }
152 }
153
154 public void unlinkToDeath() {
155 mCallback.asBinder().unlinkToDeath(this, 0);
156 }
157
158 @Override
159 public void binderDied() {
160 stopWatchingMode(mCallback);
161 }
162 }
163
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700164 final ArrayMap<IBinder, ClientState> mClients = new ArrayMap<IBinder, ClientState>();
165
166 public final class ClientState extends Binder implements DeathRecipient {
167 final IBinder mAppToken;
168 final int mPid;
169 final ArrayList<Op> mStartedOps;
170
171 public ClientState(IBinder appToken) {
172 mAppToken = appToken;
173 mPid = Binder.getCallingPid();
174 if (appToken instanceof Binder) {
175 // For local clients, there is no reason to track them.
176 mStartedOps = null;
177 } else {
178 mStartedOps = new ArrayList<Op>();
179 try {
180 mAppToken.linkToDeath(this, 0);
181 } catch (RemoteException e) {
182 }
183 }
184 }
185
186 @Override
187 public String toString() {
188 return "ClientState{" +
189 "mAppToken=" + mAppToken +
190 ", " + (mStartedOps != null ? ("pid=" + mPid) : "local") +
191 '}';
192 }
193
194 @Override
195 public void binderDied() {
196 synchronized (AppOpsService.this) {
197 for (int i=mStartedOps.size()-1; i>=0; i--) {
198 finishOperationLocked(mStartedOps.get(i));
199 }
200 mClients.remove(mAppToken);
201 }
202 }
203 }
204
Jeff Brown6f357d32014-01-15 20:40:55 -0800205 public AppOpsService(File storagePath, Handler handler) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800206 mFile = new AtomicFile(storagePath);
Jeff Brown6f357d32014-01-15 20:40:55 -0800207 mHandler = handler;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800208 readState();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800209 }
David Braunf5d83192013-09-16 13:43:51 -0700210
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800211 public void publish(Context context) {
212 mContext = context;
213 ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
214 }
215
Dianne Hackborn514074f2013-02-11 10:52:46 -0800216 public void systemReady() {
217 synchronized (this) {
218 boolean changed = false;
219 for (int i=0; i<mUidOps.size(); i++) {
220 HashMap<String, Ops> pkgs = mUidOps.valueAt(i);
221 Iterator<Ops> it = pkgs.values().iterator();
222 while (it.hasNext()) {
223 Ops ops = it.next();
224 int curUid;
225 try {
226 curUid = mContext.getPackageManager().getPackageUid(ops.packageName,
227 UserHandle.getUserId(ops.uid));
228 } catch (NameNotFoundException e) {
229 curUid = -1;
230 }
231 if (curUid != ops.uid) {
232 Slog.i(TAG, "Pruning old package " + ops.packageName
233 + "/" + ops.uid + ": new uid=" + curUid);
234 it.remove();
235 changed = true;
236 }
237 }
238 if (pkgs.size() <= 0) {
239 mUidOps.removeAt(i);
240 }
241 }
242 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800243 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800244 }
245 }
246 }
247
248 public void packageRemoved(int uid, String packageName) {
249 synchronized (this) {
250 HashMap<String, Ops> pkgs = mUidOps.get(uid);
251 if (pkgs != null) {
252 if (pkgs.remove(packageName) != null) {
253 if (pkgs.size() <= 0) {
254 mUidOps.remove(uid);
255 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800256 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800257 }
258 }
259 }
260 }
261
262 public void uidRemoved(int uid) {
263 synchronized (this) {
264 if (mUidOps.indexOfKey(uid) >= 0) {
265 mUidOps.remove(uid);
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800266 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800267 }
268 }
269 }
270
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800271 public void shutdown() {
272 Slog.w(TAG, "Writing app ops before shutdown...");
Dianne Hackborn35654b62013-01-14 17:38:02 -0800273 boolean doWrite = false;
274 synchronized (this) {
275 if (mWriteScheduled) {
276 mWriteScheduled = false;
277 doWrite = true;
278 }
279 }
280 if (doWrite) {
281 writeState();
282 }
283 }
284
Dianne Hackborn72e39832013-01-18 18:36:09 -0800285 private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
286 ArrayList<AppOpsManager.OpEntry> resOps = null;
287 if (ops == null) {
288 resOps = new ArrayList<AppOpsManager.OpEntry>();
289 for (int j=0; j<pkgOps.size(); j++) {
290 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800291 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
292 curOp.rejectTime, curOp.duration));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800293 }
294 } else {
295 for (int j=0; j<ops.length; j++) {
296 Op curOp = pkgOps.get(ops[j]);
297 if (curOp != null) {
298 if (resOps == null) {
299 resOps = new ArrayList<AppOpsManager.OpEntry>();
300 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800301 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
302 curOp.rejectTime, curOp.duration));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800303 }
304 }
305 }
306 return resOps;
307 }
308
Dianne Hackborn35654b62013-01-14 17:38:02 -0800309 @Override
310 public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
311 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
312 Binder.getCallingPid(), Binder.getCallingUid(), null);
313 ArrayList<AppOpsManager.PackageOps> res = null;
314 synchronized (this) {
315 for (int i=0; i<mUidOps.size(); i++) {
316 HashMap<String, Ops> packages = mUidOps.valueAt(i);
317 for (Ops pkgOps : packages.values()) {
Dianne Hackborn72e39832013-01-18 18:36:09 -0800318 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800319 if (resOps != null) {
320 if (res == null) {
321 res = new ArrayList<AppOpsManager.PackageOps>();
322 }
323 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
324 pkgOps.packageName, pkgOps.uid, resOps);
325 res.add(resPackage);
326 }
327 }
328 }
329 }
330 return res;
331 }
332
333 @Override
Dianne Hackborn72e39832013-01-18 18:36:09 -0800334 public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
335 int[] ops) {
336 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
337 Binder.getCallingPid(), Binder.getCallingUid(), null);
338 synchronized (this) {
339 Ops pkgOps = getOpsLocked(uid, packageName, false);
340 if (pkgOps == null) {
341 return null;
342 }
343 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
344 if (resOps == null) {
345 return null;
346 }
347 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
348 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
349 pkgOps.packageName, pkgOps.uid, resOps);
350 res.add(resPackage);
351 return res;
352 }
353 }
354
Dianne Hackborn607b4142013-08-02 18:10:10 -0700355 private void pruneOp(Op op, int uid, String packageName) {
356 if (op.time == 0 && op.rejectTime == 0) {
357 Ops ops = getOpsLocked(uid, packageName, false);
358 if (ops != null) {
359 ops.remove(op.op);
360 if (ops.size() <= 0) {
361 HashMap<String, Ops> pkgOps = mUidOps.get(uid);
362 if (pkgOps != null) {
363 pkgOps.remove(ops.packageName);
364 if (pkgOps.size() <= 0) {
365 mUidOps.remove(uid);
366 }
367 }
368 }
369 }
370 }
371 }
372
Dianne Hackborn72e39832013-01-18 18:36:09 -0800373 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800374 public void setMode(int code, int uid, String packageName, int mode) {
Dianne Hackbornb64afe12014-07-22 16:29:04 -0700375 if (Binder.getCallingPid() != Process.myPid()) {
376 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
377 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborn133b9df2014-07-01 13:06:10 -0700378 }
Dianne Hackborn961321f2013-02-05 17:22:41 -0800379 verifyIncomingOp(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800380 ArrayList<Callback> repCbs = null;
381 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800382 synchronized (this) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800383 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800384 if (op != null) {
385 if (op.mode != mode) {
386 op.mode = mode;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800387 ArrayList<Callback> cbs = mOpModeWatchers.get(code);
388 if (cbs != null) {
389 if (repCbs == null) {
390 repCbs = new ArrayList<Callback>();
391 }
392 repCbs.addAll(cbs);
393 }
394 cbs = mPackageModeWatchers.get(packageName);
395 if (cbs != null) {
396 if (repCbs == null) {
397 repCbs = new ArrayList<Callback>();
398 }
399 repCbs.addAll(cbs);
400 }
David Braunf5d83192013-09-16 13:43:51 -0700401 if (mode == AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800402 // If going into the default mode, prune this op
403 // if there is nothing else interesting in it.
Dianne Hackborn607b4142013-08-02 18:10:10 -0700404 pruneOp(op, uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800405 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800406 scheduleFastWriteLocked();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800407 }
408 }
409 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800410 if (repCbs != null) {
411 for (int i=0; i<repCbs.size(); i++) {
412 try {
413 repCbs.get(i).mCallback.opChanged(code, packageName);
414 } catch (RemoteException e) {
415 }
416 }
417 }
418 }
419
Dianne Hackborn607b4142013-08-02 18:10:10 -0700420 private static HashMap<Callback, ArrayList<Pair<String, Integer>>> addCallbacks(
421 HashMap<Callback, ArrayList<Pair<String, Integer>>> callbacks,
422 String packageName, int op, ArrayList<Callback> cbs) {
423 if (cbs == null) {
424 return callbacks;
425 }
426 if (callbacks == null) {
427 callbacks = new HashMap<Callback, ArrayList<Pair<String, Integer>>>();
428 }
429 for (int i=0; i<cbs.size(); i++) {
430 Callback cb = cbs.get(i);
431 ArrayList<Pair<String, Integer>> reports = callbacks.get(cb);
432 if (reports == null) {
433 reports = new ArrayList<Pair<String, Integer>>();
434 callbacks.put(cb, reports);
435 }
436 reports.add(new Pair<String, Integer>(packageName, op));
437 }
438 return callbacks;
439 }
440
441 @Override
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800442 public void resetAllModes(int reqUserId, String reqPackageName) {
443 final int callingPid = Binder.getCallingPid();
444 final int callingUid = Binder.getCallingUid();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700445 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800446 callingPid, callingUid, null);
447 reqUserId = ActivityManager.handleIncomingUser(callingPid, callingUid, reqUserId,
448 true, true, "resetAllModes", null);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700449 HashMap<Callback, ArrayList<Pair<String, Integer>>> callbacks = null;
450 synchronized (this) {
451 boolean changed = false;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700452 for (int i=mUidOps.size()-1; i>=0; i--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700453 HashMap<String, Ops> packages = mUidOps.valueAt(i);
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800454 if (reqUserId != UserHandle.USER_ALL
455 && reqUserId != UserHandle.getUserId(mUidOps.keyAt(i))) {
Alexandra Gherghinad6a98972014-08-04 17:05:34 +0100456 // Skip any ops for a different user
457 continue;
458 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700459 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
460 while (it.hasNext()) {
461 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700462 String packageName = ent.getKey();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800463 if (reqPackageName != null && !reqPackageName.equals(packageName)) {
464 // Skip any ops for a different package
465 continue;
466 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700467 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700468 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700469 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -0700470 if (AppOpsManager.opAllowsReset(curOp.op)
471 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -0700472 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700473 changed = true;
474 callbacks = addCallbacks(callbacks, packageName, curOp.op,
475 mOpModeWatchers.get(curOp.op));
476 callbacks = addCallbacks(callbacks, packageName, curOp.op,
477 mPackageModeWatchers.get(packageName));
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700478 if (curOp.time == 0 && curOp.rejectTime == 0) {
479 pkgOps.removeAt(j);
480 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700481 }
482 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700483 if (pkgOps.size() == 0) {
484 it.remove();
485 }
486 }
487 if (packages.size() == 0) {
488 mUidOps.removeAt(i);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700489 }
490 }
491 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800492 scheduleFastWriteLocked();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700493 }
494 }
495 if (callbacks != null) {
496 for (Map.Entry<Callback, ArrayList<Pair<String, Integer>>> ent : callbacks.entrySet()) {
497 Callback cb = ent.getKey();
498 ArrayList<Pair<String, Integer>> reports = ent.getValue();
499 for (int i=0; i<reports.size(); i++) {
500 Pair<String, Integer> rep = reports.get(i);
501 try {
502 cb.mCallback.opChanged(rep.second, rep.first);
503 } catch (RemoteException e) {
504 }
505 }
506 }
507 }
508 }
509
Dianne Hackbornc2293022013-02-06 23:14:49 -0800510 @Override
511 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
512 synchronized (this) {
513 op = AppOpsManager.opToSwitch(op);
514 Callback cb = mModeWatchers.get(callback.asBinder());
515 if (cb == null) {
516 cb = new Callback(callback);
517 mModeWatchers.put(callback.asBinder(), cb);
518 }
519 if (op != AppOpsManager.OP_NONE) {
520 ArrayList<Callback> cbs = mOpModeWatchers.get(op);
521 if (cbs == null) {
522 cbs = new ArrayList<Callback>();
523 mOpModeWatchers.put(op, cbs);
524 }
525 cbs.add(cb);
526 }
527 if (packageName != null) {
528 ArrayList<Callback> cbs = mPackageModeWatchers.get(packageName);
529 if (cbs == null) {
530 cbs = new ArrayList<Callback>();
531 mPackageModeWatchers.put(packageName, cbs);
532 }
533 cbs.add(cb);
534 }
535 }
536 }
537
538 @Override
539 public void stopWatchingMode(IAppOpsCallback callback) {
540 synchronized (this) {
541 Callback cb = mModeWatchers.remove(callback.asBinder());
542 if (cb != null) {
543 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700544 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800545 ArrayList<Callback> cbs = mOpModeWatchers.valueAt(i);
546 cbs.remove(cb);
547 if (cbs.size() <= 0) {
548 mOpModeWatchers.removeAt(i);
549 }
550 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700551 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
552 ArrayList<Callback> cbs = mPackageModeWatchers.valueAt(i);
553 cbs.remove(cb);
554 if (cbs.size() <= 0) {
555 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800556 }
557 }
558 }
559 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800560 }
561
562 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700563 public IBinder getToken(IBinder clientToken) {
564 synchronized (this) {
565 ClientState cs = mClients.get(clientToken);
566 if (cs == null) {
567 cs = new ClientState(clientToken);
568 mClients.put(clientToken, cs);
569 }
570 return cs;
571 }
572 }
573
574 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800575 public int checkOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800576 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800577 verifyIncomingOp(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800578 synchronized (this) {
Jason Monk1c7c3192014-06-26 12:52:18 -0400579 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -0400580 return AppOpsManager.MODE_IGNORED;
581 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800582 Op op = getOpLocked(AppOpsManager.opToSwitch(code), uid, packageName, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800583 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -0700584 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800585 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800586 return op.mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800587 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800588 }
589
590 @Override
John Spurlock7b414672014-07-18 13:02:39 -0400591 public int checkAudioOperation(int code, int usage, int uid, String packageName) {
John Spurlock1af30c72014-03-10 08:33:35 -0400592 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -0400593 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -0400594 if (mode != AppOpsManager.MODE_ALLOWED) {
595 return mode;
596 }
597 }
598 return checkOperation(code, uid, packageName);
599 }
600
John Spurlock7b414672014-07-18 13:02:39 -0400601 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
602 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
603 if (usageRestrictions != null) {
604 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -0400605 if (r != null && !r.exceptionPackages.contains(packageName)) {
606 return r.mode;
607 }
608 }
609 return AppOpsManager.MODE_ALLOWED;
610 }
611
612 @Override
John Spurlock7b414672014-07-18 13:02:39 -0400613 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -0400614 String[] exceptionPackages) {
615 verifyIncomingUid(uid);
616 verifyIncomingOp(code);
617 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -0400618 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
619 if (usageRestrictions == null) {
620 usageRestrictions = new SparseArray<Restriction>();
621 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -0400622 }
John Spurlock7b414672014-07-18 13:02:39 -0400623 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -0400624 if (mode != AppOpsManager.MODE_ALLOWED) {
625 final Restriction r = new Restriction();
626 r.mode = mode;
627 if (exceptionPackages != null) {
628 final int N = exceptionPackages.length;
629 r.exceptionPackages = new ArraySet<String>(N);
630 for (int i = 0; i < N; i++) {
631 final String pkg = exceptionPackages[i];
632 if (pkg != null) {
633 r.exceptionPackages.add(pkg.trim());
634 }
635 }
636 }
John Spurlock7b414672014-07-18 13:02:39 -0400637 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -0400638 }
639 }
640 }
641
642 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700643 public int checkPackage(int uid, String packageName) {
644 synchronized (this) {
Dianne Hackborn0fcef842014-09-12 15:38:33 -0700645 if (getOpsRawLocked(uid, packageName, true) != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700646 return AppOpsManager.MODE_ALLOWED;
647 } else {
648 return AppOpsManager.MODE_ERRORED;
649 }
650 }
651 }
652
653 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800654 public int noteOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800655 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800656 verifyIncomingOp(code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800657 synchronized (this) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800658 Ops ops = getOpsLocked(uid, packageName, true);
659 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800660 if (DEBUG) Log.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
661 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700662 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800663 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800664 Op op = getOpLocked(ops, code, true);
Jason Monk1c7c3192014-06-26 12:52:18 -0400665 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -0400666 return AppOpsManager.MODE_IGNORED;
667 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800668 if (op.duration == -1) {
669 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
670 + " code " + code + " time=" + op.time + " duration=" + op.duration);
671 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800672 op.duration = 0;
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800673 final int switchCode = AppOpsManager.opToSwitch(code);
674 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
675 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
676 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
677 + switchCode + " (" + code + ") uid " + uid + " package " + packageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800678 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800679 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800680 }
681 if (DEBUG) Log.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
682 + " package " + packageName);
683 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800684 op.rejectTime = 0;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800685 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800686 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800687 }
688
689 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700690 public int startOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800691 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800692 verifyIncomingOp(code);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700693 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800694 synchronized (this) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800695 Ops ops = getOpsLocked(uid, packageName, true);
696 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800697 if (DEBUG) Log.d(TAG, "startOperation: no op for code " + code + " uid " + uid
698 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700699 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800700 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800701 Op op = getOpLocked(ops, code, true);
Jason Monk1c7c3192014-06-26 12:52:18 -0400702 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -0400703 return AppOpsManager.MODE_IGNORED;
704 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800705 final int switchCode = AppOpsManager.opToSwitch(code);
706 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
707 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
708 if (DEBUG) Log.d(TAG, "startOperation: reject #" + op.mode + " for code "
709 + switchCode + " (" + code + ") uid " + uid + " package " + packageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800710 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800711 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800712 }
713 if (DEBUG) Log.d(TAG, "startOperation: allowing code " + code + " uid " + uid
714 + " package " + packageName);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800715 if (op.nesting == 0) {
716 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800717 op.rejectTime = 0;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800718 op.duration = -1;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800719 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800720 op.nesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700721 if (client.mStartedOps != null) {
722 client.mStartedOps.add(op);
723 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800724 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800725 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800726 }
727
728 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700729 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800730 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800731 verifyIncomingOp(code);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700732 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800733 synchronized (this) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800734 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800735 if (op == null) {
736 return;
737 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700738 if (client.mStartedOps != null) {
739 if (!client.mStartedOps.remove(op)) {
740 throw new IllegalStateException("Operation not started: uid" + op.uid
741 + " pkg=" + op.packageName + " op=" + op.op);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800742 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800743 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700744 finishOperationLocked(op);
745 }
746 }
747
Svet Ganovb9d71a62015-04-30 10:38:13 -0700748 @Override
749 public int permissionToOpCode(String permission) {
750 return AppOpsManager.permissionToOpCode(permission);
751 }
752
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700753 void finishOperationLocked(Op op) {
754 if (op.nesting <= 1) {
755 if (op.nesting == 1) {
756 op.duration = (int)(System.currentTimeMillis() - op.time);
757 op.time += op.duration;
758 } else {
759 Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
760 + op.packageName + " code " + op.op + " time=" + op.time
761 + " duration=" + op.duration + " nesting=" + op.nesting);
762 }
763 op.nesting = 0;
764 } else {
765 op.nesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800766 }
767 }
768
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800769 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800770 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800771 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800772 }
773 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800774 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800775 }
776 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
777 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800778 }
779
Dianne Hackborn961321f2013-02-05 17:22:41 -0800780 private void verifyIncomingOp(int op) {
781 if (op >= 0 && op < AppOpsManager._NUM_OP) {
782 return;
783 }
784 throw new IllegalArgumentException("Bad operation #" + op);
785 }
786
Dianne Hackborn72e39832013-01-18 18:36:09 -0800787 private Ops getOpsLocked(int uid, String packageName, boolean edit) {
Dianne Hackborn0fcef842014-09-12 15:38:33 -0700788 if (uid == 0) {
789 packageName = "root";
790 } else if (uid == Process.SHELL_UID) {
791 packageName = "com.android.shell";
792 }
793 return getOpsRawLocked(uid, packageName, edit);
794 }
795
796 private Ops getOpsRawLocked(int uid, String packageName, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800797 HashMap<String, Ops> pkgOps = mUidOps.get(uid);
798 if (pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800799 if (!edit) {
800 return null;
801 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800802 pkgOps = new HashMap<String, Ops>();
803 mUidOps.put(uid, pkgOps);
804 }
805 Ops ops = pkgOps.get(packageName);
806 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800807 if (!edit) {
808 return null;
809 }
Jason Monk1c7c3192014-06-26 12:52:18 -0400810 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800811 // This is the first time we have seen this package name under this uid,
812 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -0800813 if (uid != 0) {
814 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800815 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800816 int pkgUid = -1;
817 try {
Jason Monk1c7c3192014-06-26 12:52:18 -0400818 ApplicationInfo appInfo = ActivityThread.getPackageManager()
819 .getApplicationInfo(packageName, 0, UserHandle.getUserId(uid));
820 if (appInfo != null) {
821 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800822 isPrivileged = (appInfo.privateFlags
823 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -0400824 } else {
825 if ("media".equals(packageName)) {
826 pkgUid = Process.MEDIA_UID;
827 isPrivileged = false;
828 }
Dianne Hackborn713df152013-05-17 11:27:57 -0700829 }
Jason Monk1c7c3192014-06-26 12:52:18 -0400830 } catch (RemoteException e) {
831 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800832 }
833 if (pkgUid != uid) {
834 // Oops! The package name is not valid for the uid they are calling
835 // under. Abort.
836 Slog.w(TAG, "Bad call: specified package " + packageName
837 + " under uid " + uid + " but it is really " + pkgUid);
838 return null;
839 }
840 } finally {
841 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800842 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800843 }
Jason Monk1c7c3192014-06-26 12:52:18 -0400844 ops = new Ops(packageName, uid, isPrivileged);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800845 pkgOps.put(packageName, ops);
846 }
Dianne Hackborn72e39832013-01-18 18:36:09 -0800847 return ops;
848 }
849
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800850 private void scheduleWriteLocked() {
851 if (!mWriteScheduled) {
852 mWriteScheduled = true;
853 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
854 }
855 }
856
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800857 private void scheduleFastWriteLocked() {
858 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800859 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800860 mFastWriteScheduled = true;
861 mHandler.removeCallbacks(mWriteRunner);
862 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800863 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800864 }
865
Dianne Hackborn72e39832013-01-18 18:36:09 -0800866 private Op getOpLocked(int code, int uid, String packageName, boolean edit) {
867 Ops ops = getOpsLocked(uid, packageName, edit);
868 if (ops == null) {
869 return null;
870 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800871 return getOpLocked(ops, code, edit);
872 }
873
874 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800875 Op op = ops.get(code);
876 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800877 if (!edit) {
878 return null;
879 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700880 op = new Op(ops.uid, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800881 ops.put(code, op);
882 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800883 if (edit) {
884 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -0800885 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800886 return op;
887 }
888
Jason Monk1c7c3192014-06-26 12:52:18 -0400889 private boolean isOpRestricted(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -0400890 int userHandle = UserHandle.getUserId(uid);
891 boolean[] opRestrictions = mOpRestrictions.get(userHandle);
892 if ((opRestrictions != null) && opRestrictions[code]) {
Jason Monk1c7c3192014-06-26 12:52:18 -0400893 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
894 synchronized (this) {
895 Ops ops = getOpsLocked(uid, packageName, true);
896 if ((ops != null) && ops.isPrivileged) {
897 return false;
898 }
899 }
900 }
Julia Reynolds401de172014-07-24 18:21:29 -0400901 return true;
Jason Monk62062992014-05-06 09:55:28 -0400902 }
903 return false;
904 }
905
Dianne Hackborn35654b62013-01-14 17:38:02 -0800906 void readState() {
907 synchronized (mFile) {
908 synchronized (this) {
909 FileInputStream stream;
910 try {
911 stream = mFile.openRead();
912 } catch (FileNotFoundException e) {
913 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
914 return;
915 }
916 boolean success = false;
917 try {
918 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100919 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -0800920 int type;
921 while ((type = parser.next()) != XmlPullParser.START_TAG
922 && type != XmlPullParser.END_DOCUMENT) {
923 ;
924 }
925
926 if (type != XmlPullParser.START_TAG) {
927 throw new IllegalStateException("no start tag found");
928 }
929
930 int outerDepth = parser.getDepth();
931 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
932 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
933 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
934 continue;
935 }
936
937 String tagName = parser.getName();
938 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +0000939 readPackage(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800940 } else {
941 Slog.w(TAG, "Unknown element under <app-ops>: "
942 + parser.getName());
943 XmlUtils.skipCurrentTag(parser);
944 }
945 }
946 success = true;
947 } catch (IllegalStateException e) {
948 Slog.w(TAG, "Failed parsing " + e);
949 } catch (NullPointerException e) {
950 Slog.w(TAG, "Failed parsing " + e);
951 } catch (NumberFormatException e) {
952 Slog.w(TAG, "Failed parsing " + e);
953 } catch (XmlPullParserException e) {
954 Slog.w(TAG, "Failed parsing " + e);
955 } catch (IOException e) {
956 Slog.w(TAG, "Failed parsing " + e);
957 } catch (IndexOutOfBoundsException e) {
958 Slog.w(TAG, "Failed parsing " + e);
959 } finally {
960 if (!success) {
961 mUidOps.clear();
962 }
963 try {
964 stream.close();
965 } catch (IOException e) {
966 }
967 }
968 }
969 }
970 }
971
Dave Burke0997c5bd2013-08-02 20:25:02 +0000972 void readPackage(XmlPullParser parser) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -0800973 XmlPullParserException, IOException {
974 String pkgName = parser.getAttributeValue(null, "n");
975 int outerDepth = parser.getDepth();
976 int type;
977 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
978 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
979 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
980 continue;
981 }
982
983 String tagName = parser.getName();
984 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +0000985 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800986 } else {
987 Slog.w(TAG, "Unknown element under <pkg>: "
988 + parser.getName());
989 XmlUtils.skipCurrentTag(parser);
990 }
991 }
992 }
993
Dave Burke0997c5bd2013-08-02 20:25:02 +0000994 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -0800995 XmlPullParserException, IOException {
996 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Jason Monk1c7c3192014-06-26 12:52:18 -0400997 String isPrivilegedString = parser.getAttributeValue(null, "p");
998 boolean isPrivileged = false;
999 if (isPrivilegedString == null) {
1000 try {
1001 IPackageManager packageManager = ActivityThread.getPackageManager();
1002 if (packageManager != null) {
1003 ApplicationInfo appInfo = ActivityThread.getPackageManager()
1004 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
1005 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001006 isPrivileged = (appInfo.privateFlags
1007 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001008 }
1009 } else {
1010 // Could not load data, don't add to cache so it will be loaded later.
1011 return;
1012 }
1013 } catch (RemoteException e) {
1014 Slog.w(TAG, "Could not contact PackageManager", e);
1015 }
1016 } else {
1017 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
1018 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001019 int outerDepth = parser.getDepth();
1020 int type;
1021 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1022 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1023 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1024 continue;
1025 }
1026
1027 String tagName = parser.getName();
1028 if (tagName.equals("op")) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001029 Op op = new Op(uid, pkgName, Integer.parseInt(parser.getAttributeValue(null, "n")));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001030 String mode = parser.getAttributeValue(null, "m");
1031 if (mode != null) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001032 op.mode = Integer.parseInt(mode);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001033 }
1034 String time = parser.getAttributeValue(null, "t");
1035 if (time != null) {
1036 op.time = Long.parseLong(time);
1037 }
1038 time = parser.getAttributeValue(null, "r");
1039 if (time != null) {
1040 op.rejectTime = Long.parseLong(time);
1041 }
1042 String dur = parser.getAttributeValue(null, "d");
1043 if (dur != null) {
1044 op.duration = Integer.parseInt(dur);
1045 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001046 HashMap<String, Ops> pkgOps = mUidOps.get(uid);
1047 if (pkgOps == null) {
1048 pkgOps = new HashMap<String, Ops>();
1049 mUidOps.put(uid, pkgOps);
1050 }
1051 Ops ops = pkgOps.get(pkgName);
1052 if (ops == null) {
Jason Monk1c7c3192014-06-26 12:52:18 -04001053 ops = new Ops(pkgName, uid, isPrivileged);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001054 pkgOps.put(pkgName, ops);
1055 }
1056 ops.put(op.op, op);
1057 } else {
1058 Slog.w(TAG, "Unknown element under <pkg>: "
1059 + parser.getName());
1060 XmlUtils.skipCurrentTag(parser);
1061 }
1062 }
1063 }
1064
1065 void writeState() {
1066 synchronized (mFile) {
1067 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
1068
1069 FileOutputStream stream;
1070 try {
1071 stream = mFile.startWrite();
1072 } catch (IOException e) {
1073 Slog.w(TAG, "Failed to write state: " + e);
1074 return;
1075 }
1076
1077 try {
1078 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001079 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001080 out.startDocument(null, true);
1081 out.startTag(null, "app-ops");
1082
1083 if (allOps != null) {
1084 String lastPkg = null;
1085 for (int i=0; i<allOps.size(); i++) {
1086 AppOpsManager.PackageOps pkg = allOps.get(i);
1087 if (!pkg.getPackageName().equals(lastPkg)) {
1088 if (lastPkg != null) {
1089 out.endTag(null, "pkg");
1090 }
1091 lastPkg = pkg.getPackageName();
1092 out.startTag(null, "pkg");
1093 out.attribute(null, "n", lastPkg);
1094 }
1095 out.startTag(null, "uid");
1096 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04001097 synchronized (this) {
1098 Ops ops = getOpsLocked(pkg.getUid(), pkg.getPackageName(), false);
1099 // Should always be present as the list of PackageOps is generated
1100 // from Ops.
1101 if (ops != null) {
1102 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
1103 } else {
1104 out.attribute(null, "p", Boolean.toString(false));
1105 }
1106 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001107 List<AppOpsManager.OpEntry> ops = pkg.getOps();
1108 for (int j=0; j<ops.size(); j++) {
1109 AppOpsManager.OpEntry op = ops.get(j);
1110 out.startTag(null, "op");
1111 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07001112 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001113 out.attribute(null, "m", Integer.toString(op.getMode()));
1114 }
1115 long time = op.getTime();
1116 if (time != 0) {
1117 out.attribute(null, "t", Long.toString(time));
1118 }
1119 time = op.getRejectTime();
1120 if (time != 0) {
1121 out.attribute(null, "r", Long.toString(time));
1122 }
1123 int dur = op.getDuration();
1124 if (dur != 0) {
1125 out.attribute(null, "d", Integer.toString(dur));
1126 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001127 out.endTag(null, "op");
1128 }
1129 out.endTag(null, "uid");
1130 }
1131 if (lastPkg != null) {
1132 out.endTag(null, "pkg");
1133 }
1134 }
1135
1136 out.endTag(null, "app-ops");
1137 out.endDocument();
1138 mFile.finishWrite(stream);
1139 } catch (IOException e) {
1140 Slog.w(TAG, "Failed to write state, restoring backup.", e);
1141 mFile.failWrite(stream);
1142 }
1143 }
1144 }
1145
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001146 @Override
1147 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1148 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1149 != PackageManager.PERMISSION_GRANTED) {
1150 pw.println("Permission Denial: can't dump ApOps service from from pid="
1151 + Binder.getCallingPid()
1152 + ", uid=" + Binder.getCallingUid());
1153 return;
1154 }
1155
1156 synchronized (this) {
1157 pw.println("Current AppOps Service state:");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001158 final long now = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001159 boolean needSep = false;
1160 if (mOpModeWatchers.size() > 0) {
1161 needSep = true;
1162 pw.println(" Op mode watchers:");
1163 for (int i=0; i<mOpModeWatchers.size(); i++) {
1164 pw.print(" Op "); pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
1165 pw.println(":");
1166 ArrayList<Callback> callbacks = mOpModeWatchers.valueAt(i);
1167 for (int j=0; j<callbacks.size(); j++) {
1168 pw.print(" #"); pw.print(j); pw.print(": ");
1169 pw.println(callbacks.get(j));
1170 }
1171 }
1172 }
1173 if (mPackageModeWatchers.size() > 0) {
1174 needSep = true;
1175 pw.println(" Package mode watchers:");
1176 for (int i=0; i<mPackageModeWatchers.size(); i++) {
1177 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
1178 pw.println(":");
1179 ArrayList<Callback> callbacks = mPackageModeWatchers.valueAt(i);
1180 for (int j=0; j<callbacks.size(); j++) {
1181 pw.print(" #"); pw.print(j); pw.print(": ");
1182 pw.println(callbacks.get(j));
1183 }
1184 }
1185 }
1186 if (mModeWatchers.size() > 0) {
1187 needSep = true;
1188 pw.println(" All mode watchers:");
1189 for (int i=0; i<mModeWatchers.size(); i++) {
1190 pw.print(" "); pw.print(mModeWatchers.keyAt(i));
1191 pw.print(" -> "); pw.println(mModeWatchers.valueAt(i));
1192 }
1193 }
1194 if (mClients.size() > 0) {
1195 needSep = true;
1196 pw.println(" Clients:");
1197 for (int i=0; i<mClients.size(); i++) {
1198 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
1199 ClientState cs = mClients.valueAt(i);
1200 pw.print(" "); pw.println(cs);
1201 if (cs.mStartedOps != null && cs.mStartedOps.size() > 0) {
1202 pw.println(" Started ops:");
1203 for (int j=0; j<cs.mStartedOps.size(); j++) {
1204 Op op = cs.mStartedOps.get(j);
1205 pw.print(" "); pw.print("uid="); pw.print(op.uid);
1206 pw.print(" pkg="); pw.print(op.packageName);
1207 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
1208 }
1209 }
1210 }
1211 }
John Spurlock1af30c72014-03-10 08:33:35 -04001212 if (mAudioRestrictions.size() > 0) {
1213 boolean printedHeader = false;
1214 for (int o=0; o<mAudioRestrictions.size(); o++) {
1215 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
1216 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
1217 for (int i=0; i<restrictions.size(); i++) {
1218 if (!printedHeader){
1219 pw.println(" Audio Restrictions:");
1220 printedHeader = true;
1221 needSep = true;
1222 }
John Spurlock7b414672014-07-18 13:02:39 -04001223 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04001224 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04001225 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04001226 Restriction r = restrictions.valueAt(i);
1227 pw.print(": mode="); pw.println(r.mode);
1228 if (!r.exceptionPackages.isEmpty()) {
1229 pw.println(" Exceptions:");
1230 for (int j=0; j<r.exceptionPackages.size(); j++) {
1231 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
1232 }
1233 }
1234 }
1235 }
1236 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001237 if (needSep) {
1238 pw.println();
1239 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001240 for (int i=0; i<mUidOps.size(); i++) {
1241 pw.print(" Uid "); UserHandle.formatUid(pw, mUidOps.keyAt(i)); pw.println(":");
1242 HashMap<String, Ops> pkgOps = mUidOps.valueAt(i);
1243 for (Ops ops : pkgOps.values()) {
1244 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
1245 for (int j=0; j<ops.size(); j++) {
1246 Op op = ops.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001247 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
1248 pw.print(": mode="); pw.print(op.mode);
1249 if (op.time != 0) {
1250 pw.print("; time="); TimeUtils.formatDuration(now-op.time, pw);
1251 pw.print(" ago");
1252 }
1253 if (op.rejectTime != 0) {
1254 pw.print("; rejectTime="); TimeUtils.formatDuration(now-op.rejectTime, pw);
1255 pw.print(" ago");
1256 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001257 if (op.duration == -1) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001258 pw.print(" (running)");
1259 } else if (op.duration != 0) {
1260 pw.print("; duration="); TimeUtils.formatDuration(op.duration, pw);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001261 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001262 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001263 }
1264 }
1265 }
1266 }
1267 }
John Spurlock1af30c72014-03-10 08:33:35 -04001268
1269 private static final class Restriction {
1270 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
1271 int mode;
1272 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
1273 }
Jason Monk62062992014-05-06 09:55:28 -04001274
1275 @Override
Jason Monk62062992014-05-06 09:55:28 -04001276 public void setUserRestrictions(Bundle restrictions, int userHandle) throws RemoteException {
1277 checkSystemUid("setUserRestrictions");
1278 boolean[] opRestrictions = mOpRestrictions.get(userHandle);
1279 if (opRestrictions == null) {
1280 opRestrictions = new boolean[AppOpsManager._NUM_OP];
1281 mOpRestrictions.put(userHandle, opRestrictions);
1282 }
1283 for (int i = 0; i < opRestrictions.length; ++i) {
1284 String restriction = AppOpsManager.opToRestriction(i);
1285 if (restriction != null) {
1286 opRestrictions[i] = restrictions.getBoolean(restriction, false);
1287 } else {
1288 opRestrictions[i] = false;
1289 }
1290 }
1291 }
1292
1293 @Override
1294 public void removeUser(int userHandle) throws RemoteException {
1295 checkSystemUid("removeUser");
1296 mOpRestrictions.remove(userHandle);
Jason Monk62062992014-05-06 09:55:28 -04001297 }
1298
1299 private void checkSystemUid(String function) {
1300 int uid = Binder.getCallingUid();
1301 if (uid != Process.SYSTEM_UID) {
1302 throw new SecurityException(function + " must by called by the system");
1303 }
1304 }
1305
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001306}