blob: 79c66b9346efc370085d219a195a3c62c4924b2e [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) {
Svet Ganov38536112015-05-19 12:45:52 -0700411 // There are components watching for mode changes such as window manager
412 // and location manager which are in our process. The callbacks in these
413 // components may require permissions our remote caller does not have.
414 final long identity = Binder.clearCallingIdentity();
415 try {
416 for (int i = 0; i < repCbs.size(); i++) {
417 try {
418 repCbs.get(i).mCallback.opChanged(code, packageName);
419 } catch (RemoteException e) {
420 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800421 }
Svet Ganov38536112015-05-19 12:45:52 -0700422 } finally {
423 Binder.restoreCallingIdentity(identity);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800424 }
425 }
426 }
427
Dianne Hackborn607b4142013-08-02 18:10:10 -0700428 private static HashMap<Callback, ArrayList<Pair<String, Integer>>> addCallbacks(
429 HashMap<Callback, ArrayList<Pair<String, Integer>>> callbacks,
430 String packageName, int op, ArrayList<Callback> cbs) {
431 if (cbs == null) {
432 return callbacks;
433 }
434 if (callbacks == null) {
435 callbacks = new HashMap<Callback, ArrayList<Pair<String, Integer>>>();
436 }
437 for (int i=0; i<cbs.size(); i++) {
438 Callback cb = cbs.get(i);
439 ArrayList<Pair<String, Integer>> reports = callbacks.get(cb);
440 if (reports == null) {
441 reports = new ArrayList<Pair<String, Integer>>();
442 callbacks.put(cb, reports);
443 }
444 reports.add(new Pair<String, Integer>(packageName, op));
445 }
446 return callbacks;
447 }
448
449 @Override
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800450 public void resetAllModes(int reqUserId, String reqPackageName) {
451 final int callingPid = Binder.getCallingPid();
452 final int callingUid = Binder.getCallingUid();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700453 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800454 callingPid, callingUid, null);
455 reqUserId = ActivityManager.handleIncomingUser(callingPid, callingUid, reqUserId,
456 true, true, "resetAllModes", null);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700457 HashMap<Callback, ArrayList<Pair<String, Integer>>> callbacks = null;
458 synchronized (this) {
459 boolean changed = false;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700460 for (int i=mUidOps.size()-1; i>=0; i--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700461 HashMap<String, Ops> packages = mUidOps.valueAt(i);
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800462 if (reqUserId != UserHandle.USER_ALL
463 && reqUserId != UserHandle.getUserId(mUidOps.keyAt(i))) {
Alexandra Gherghinad6a98972014-08-04 17:05:34 +0100464 // Skip any ops for a different user
465 continue;
466 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700467 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
468 while (it.hasNext()) {
469 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700470 String packageName = ent.getKey();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800471 if (reqPackageName != null && !reqPackageName.equals(packageName)) {
472 // Skip any ops for a different package
473 continue;
474 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700475 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700476 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700477 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -0700478 if (AppOpsManager.opAllowsReset(curOp.op)
479 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -0700480 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700481 changed = true;
482 callbacks = addCallbacks(callbacks, packageName, curOp.op,
483 mOpModeWatchers.get(curOp.op));
484 callbacks = addCallbacks(callbacks, packageName, curOp.op,
485 mPackageModeWatchers.get(packageName));
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700486 if (curOp.time == 0 && curOp.rejectTime == 0) {
487 pkgOps.removeAt(j);
488 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700489 }
490 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700491 if (pkgOps.size() == 0) {
492 it.remove();
493 }
494 }
495 if (packages.size() == 0) {
496 mUidOps.removeAt(i);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700497 }
498 }
499 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800500 scheduleFastWriteLocked();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700501 }
502 }
503 if (callbacks != null) {
504 for (Map.Entry<Callback, ArrayList<Pair<String, Integer>>> ent : callbacks.entrySet()) {
505 Callback cb = ent.getKey();
506 ArrayList<Pair<String, Integer>> reports = ent.getValue();
507 for (int i=0; i<reports.size(); i++) {
508 Pair<String, Integer> rep = reports.get(i);
509 try {
510 cb.mCallback.opChanged(rep.second, rep.first);
511 } catch (RemoteException e) {
512 }
513 }
514 }
515 }
516 }
517
Dianne Hackbornc2293022013-02-06 23:14:49 -0800518 @Override
519 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
520 synchronized (this) {
521 op = AppOpsManager.opToSwitch(op);
522 Callback cb = mModeWatchers.get(callback.asBinder());
523 if (cb == null) {
524 cb = new Callback(callback);
525 mModeWatchers.put(callback.asBinder(), cb);
526 }
527 if (op != AppOpsManager.OP_NONE) {
528 ArrayList<Callback> cbs = mOpModeWatchers.get(op);
529 if (cbs == null) {
530 cbs = new ArrayList<Callback>();
531 mOpModeWatchers.put(op, cbs);
532 }
533 cbs.add(cb);
534 }
535 if (packageName != null) {
536 ArrayList<Callback> cbs = mPackageModeWatchers.get(packageName);
537 if (cbs == null) {
538 cbs = new ArrayList<Callback>();
539 mPackageModeWatchers.put(packageName, cbs);
540 }
541 cbs.add(cb);
542 }
543 }
544 }
545
546 @Override
547 public void stopWatchingMode(IAppOpsCallback callback) {
548 synchronized (this) {
549 Callback cb = mModeWatchers.remove(callback.asBinder());
550 if (cb != null) {
551 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700552 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800553 ArrayList<Callback> cbs = mOpModeWatchers.valueAt(i);
554 cbs.remove(cb);
555 if (cbs.size() <= 0) {
556 mOpModeWatchers.removeAt(i);
557 }
558 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700559 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
560 ArrayList<Callback> cbs = mPackageModeWatchers.valueAt(i);
561 cbs.remove(cb);
562 if (cbs.size() <= 0) {
563 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800564 }
565 }
566 }
567 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800568 }
569
570 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700571 public IBinder getToken(IBinder clientToken) {
572 synchronized (this) {
573 ClientState cs = mClients.get(clientToken);
574 if (cs == null) {
575 cs = new ClientState(clientToken);
576 mClients.put(clientToken, cs);
577 }
578 return cs;
579 }
580 }
581
582 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800583 public int checkOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800584 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800585 verifyIncomingOp(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800586 synchronized (this) {
Jason Monk1c7c3192014-06-26 12:52:18 -0400587 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -0400588 return AppOpsManager.MODE_IGNORED;
589 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800590 Op op = getOpLocked(AppOpsManager.opToSwitch(code), uid, packageName, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800591 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -0700592 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800593 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800594 return op.mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800595 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800596 }
597
598 @Override
John Spurlock7b414672014-07-18 13:02:39 -0400599 public int checkAudioOperation(int code, int usage, int uid, String packageName) {
John Spurlock1af30c72014-03-10 08:33:35 -0400600 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -0400601 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -0400602 if (mode != AppOpsManager.MODE_ALLOWED) {
603 return mode;
604 }
605 }
606 return checkOperation(code, uid, packageName);
607 }
608
John Spurlock7b414672014-07-18 13:02:39 -0400609 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
610 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
611 if (usageRestrictions != null) {
612 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -0400613 if (r != null && !r.exceptionPackages.contains(packageName)) {
614 return r.mode;
615 }
616 }
617 return AppOpsManager.MODE_ALLOWED;
618 }
619
620 @Override
John Spurlock7b414672014-07-18 13:02:39 -0400621 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -0400622 String[] exceptionPackages) {
623 verifyIncomingUid(uid);
624 verifyIncomingOp(code);
625 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -0400626 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
627 if (usageRestrictions == null) {
628 usageRestrictions = new SparseArray<Restriction>();
629 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -0400630 }
John Spurlock7b414672014-07-18 13:02:39 -0400631 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -0400632 if (mode != AppOpsManager.MODE_ALLOWED) {
633 final Restriction r = new Restriction();
634 r.mode = mode;
635 if (exceptionPackages != null) {
636 final int N = exceptionPackages.length;
637 r.exceptionPackages = new ArraySet<String>(N);
638 for (int i = 0; i < N; i++) {
639 final String pkg = exceptionPackages[i];
640 if (pkg != null) {
641 r.exceptionPackages.add(pkg.trim());
642 }
643 }
644 }
John Spurlock7b414672014-07-18 13:02:39 -0400645 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -0400646 }
647 }
648 }
649
650 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700651 public int checkPackage(int uid, String packageName) {
652 synchronized (this) {
Dianne Hackborn0fcef842014-09-12 15:38:33 -0700653 if (getOpsRawLocked(uid, packageName, true) != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700654 return AppOpsManager.MODE_ALLOWED;
655 } else {
656 return AppOpsManager.MODE_ERRORED;
657 }
658 }
659 }
660
661 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800662 public int noteOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800663 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800664 verifyIncomingOp(code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800665 synchronized (this) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800666 Ops ops = getOpsLocked(uid, packageName, true);
667 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800668 if (DEBUG) Log.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
669 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700670 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800671 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800672 Op op = getOpLocked(ops, code, true);
Jason Monk1c7c3192014-06-26 12:52:18 -0400673 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -0400674 return AppOpsManager.MODE_IGNORED;
675 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800676 if (op.duration == -1) {
677 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
678 + " code " + code + " time=" + op.time + " duration=" + op.duration);
679 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800680 op.duration = 0;
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800681 final int switchCode = AppOpsManager.opToSwitch(code);
682 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
683 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
684 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
685 + switchCode + " (" + code + ") uid " + uid + " package " + packageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800686 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800687 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800688 }
689 if (DEBUG) Log.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
690 + " package " + packageName);
691 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800692 op.rejectTime = 0;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800693 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800694 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800695 }
696
697 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700698 public int startOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800699 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800700 verifyIncomingOp(code);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700701 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800702 synchronized (this) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800703 Ops ops = getOpsLocked(uid, packageName, true);
704 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800705 if (DEBUG) Log.d(TAG, "startOperation: no op for code " + code + " uid " + uid
706 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700707 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800708 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800709 Op op = getOpLocked(ops, code, true);
Jason Monk1c7c3192014-06-26 12:52:18 -0400710 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -0400711 return AppOpsManager.MODE_IGNORED;
712 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800713 final int switchCode = AppOpsManager.opToSwitch(code);
714 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
715 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
716 if (DEBUG) Log.d(TAG, "startOperation: reject #" + op.mode + " for code "
717 + switchCode + " (" + code + ") uid " + uid + " package " + packageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800718 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800719 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800720 }
721 if (DEBUG) Log.d(TAG, "startOperation: allowing code " + code + " uid " + uid
722 + " package " + packageName);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800723 if (op.nesting == 0) {
724 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800725 op.rejectTime = 0;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800726 op.duration = -1;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800727 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800728 op.nesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700729 if (client.mStartedOps != null) {
730 client.mStartedOps.add(op);
731 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800732 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800733 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800734 }
735
736 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700737 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800738 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800739 verifyIncomingOp(code);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700740 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800741 synchronized (this) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800742 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800743 if (op == null) {
744 return;
745 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700746 if (client.mStartedOps != null) {
747 if (!client.mStartedOps.remove(op)) {
748 throw new IllegalStateException("Operation not started: uid" + op.uid
749 + " pkg=" + op.packageName + " op=" + op.op);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800750 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800751 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700752 finishOperationLocked(op);
753 }
754 }
755
Svet Ganovb9d71a62015-04-30 10:38:13 -0700756 @Override
757 public int permissionToOpCode(String permission) {
758 return AppOpsManager.permissionToOpCode(permission);
759 }
760
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700761 void finishOperationLocked(Op op) {
762 if (op.nesting <= 1) {
763 if (op.nesting == 1) {
764 op.duration = (int)(System.currentTimeMillis() - op.time);
765 op.time += op.duration;
766 } else {
767 Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
768 + op.packageName + " code " + op.op + " time=" + op.time
769 + " duration=" + op.duration + " nesting=" + op.nesting);
770 }
771 op.nesting = 0;
772 } else {
773 op.nesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800774 }
775 }
776
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800777 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800778 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800779 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800780 }
781 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800782 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800783 }
784 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
785 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800786 }
787
Dianne Hackborn961321f2013-02-05 17:22:41 -0800788 private void verifyIncomingOp(int op) {
789 if (op >= 0 && op < AppOpsManager._NUM_OP) {
790 return;
791 }
792 throw new IllegalArgumentException("Bad operation #" + op);
793 }
794
Dianne Hackborn72e39832013-01-18 18:36:09 -0800795 private Ops getOpsLocked(int uid, String packageName, boolean edit) {
Dianne Hackborn0fcef842014-09-12 15:38:33 -0700796 if (uid == 0) {
797 packageName = "root";
798 } else if (uid == Process.SHELL_UID) {
799 packageName = "com.android.shell";
800 }
801 return getOpsRawLocked(uid, packageName, edit);
802 }
803
804 private Ops getOpsRawLocked(int uid, String packageName, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800805 HashMap<String, Ops> pkgOps = mUidOps.get(uid);
806 if (pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800807 if (!edit) {
808 return null;
809 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800810 pkgOps = new HashMap<String, Ops>();
811 mUidOps.put(uid, pkgOps);
812 }
813 Ops ops = pkgOps.get(packageName);
814 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800815 if (!edit) {
816 return null;
817 }
Jason Monk1c7c3192014-06-26 12:52:18 -0400818 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800819 // This is the first time we have seen this package name under this uid,
820 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -0800821 if (uid != 0) {
822 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800823 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800824 int pkgUid = -1;
825 try {
Jason Monk1c7c3192014-06-26 12:52:18 -0400826 ApplicationInfo appInfo = ActivityThread.getPackageManager()
827 .getApplicationInfo(packageName, 0, UserHandle.getUserId(uid));
828 if (appInfo != null) {
829 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -0800830 isPrivileged = (appInfo.privateFlags
831 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -0400832 } else {
833 if ("media".equals(packageName)) {
834 pkgUid = Process.MEDIA_UID;
835 isPrivileged = false;
836 }
Dianne Hackborn713df152013-05-17 11:27:57 -0700837 }
Jason Monk1c7c3192014-06-26 12:52:18 -0400838 } catch (RemoteException e) {
839 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800840 }
841 if (pkgUid != uid) {
842 // Oops! The package name is not valid for the uid they are calling
843 // under. Abort.
844 Slog.w(TAG, "Bad call: specified package " + packageName
845 + " under uid " + uid + " but it is really " + pkgUid);
846 return null;
847 }
848 } finally {
849 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800850 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800851 }
Jason Monk1c7c3192014-06-26 12:52:18 -0400852 ops = new Ops(packageName, uid, isPrivileged);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800853 pkgOps.put(packageName, ops);
854 }
Dianne Hackborn72e39832013-01-18 18:36:09 -0800855 return ops;
856 }
857
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800858 private void scheduleWriteLocked() {
859 if (!mWriteScheduled) {
860 mWriteScheduled = true;
861 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
862 }
863 }
864
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800865 private void scheduleFastWriteLocked() {
866 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800867 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800868 mFastWriteScheduled = true;
869 mHandler.removeCallbacks(mWriteRunner);
870 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800871 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800872 }
873
Dianne Hackborn72e39832013-01-18 18:36:09 -0800874 private Op getOpLocked(int code, int uid, String packageName, boolean edit) {
875 Ops ops = getOpsLocked(uid, packageName, edit);
876 if (ops == null) {
877 return null;
878 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800879 return getOpLocked(ops, code, edit);
880 }
881
882 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800883 Op op = ops.get(code);
884 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800885 if (!edit) {
886 return null;
887 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700888 op = new Op(ops.uid, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800889 ops.put(code, op);
890 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800891 if (edit) {
892 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -0800893 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800894 return op;
895 }
896
Jason Monk1c7c3192014-06-26 12:52:18 -0400897 private boolean isOpRestricted(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -0400898 int userHandle = UserHandle.getUserId(uid);
899 boolean[] opRestrictions = mOpRestrictions.get(userHandle);
900 if ((opRestrictions != null) && opRestrictions[code]) {
Jason Monk1c7c3192014-06-26 12:52:18 -0400901 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
902 synchronized (this) {
903 Ops ops = getOpsLocked(uid, packageName, true);
904 if ((ops != null) && ops.isPrivileged) {
905 return false;
906 }
907 }
908 }
Julia Reynolds401de172014-07-24 18:21:29 -0400909 return true;
Jason Monk62062992014-05-06 09:55:28 -0400910 }
911 return false;
912 }
913
Dianne Hackborn35654b62013-01-14 17:38:02 -0800914 void readState() {
915 synchronized (mFile) {
916 synchronized (this) {
917 FileInputStream stream;
918 try {
919 stream = mFile.openRead();
920 } catch (FileNotFoundException e) {
921 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
922 return;
923 }
924 boolean success = false;
925 try {
926 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100927 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -0800928 int type;
929 while ((type = parser.next()) != XmlPullParser.START_TAG
930 && type != XmlPullParser.END_DOCUMENT) {
931 ;
932 }
933
934 if (type != XmlPullParser.START_TAG) {
935 throw new IllegalStateException("no start tag found");
936 }
937
938 int outerDepth = parser.getDepth();
939 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
940 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
941 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
942 continue;
943 }
944
945 String tagName = parser.getName();
946 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +0000947 readPackage(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800948 } else {
949 Slog.w(TAG, "Unknown element under <app-ops>: "
950 + parser.getName());
951 XmlUtils.skipCurrentTag(parser);
952 }
953 }
954 success = true;
955 } catch (IllegalStateException e) {
956 Slog.w(TAG, "Failed parsing " + e);
957 } catch (NullPointerException e) {
958 Slog.w(TAG, "Failed parsing " + e);
959 } catch (NumberFormatException e) {
960 Slog.w(TAG, "Failed parsing " + e);
961 } catch (XmlPullParserException e) {
962 Slog.w(TAG, "Failed parsing " + e);
963 } catch (IOException e) {
964 Slog.w(TAG, "Failed parsing " + e);
965 } catch (IndexOutOfBoundsException e) {
966 Slog.w(TAG, "Failed parsing " + e);
967 } finally {
968 if (!success) {
969 mUidOps.clear();
970 }
971 try {
972 stream.close();
973 } catch (IOException e) {
974 }
975 }
976 }
977 }
978 }
979
Dave Burke0997c5bd2013-08-02 20:25:02 +0000980 void readPackage(XmlPullParser parser) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -0800981 XmlPullParserException, IOException {
982 String pkgName = parser.getAttributeValue(null, "n");
983 int outerDepth = parser.getDepth();
984 int type;
985 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
986 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
987 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
988 continue;
989 }
990
991 String tagName = parser.getName();
992 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +0000993 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800994 } else {
995 Slog.w(TAG, "Unknown element under <pkg>: "
996 + parser.getName());
997 XmlUtils.skipCurrentTag(parser);
998 }
999 }
1000 }
1001
Dave Burke0997c5bd2013-08-02 20:25:02 +00001002 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08001003 XmlPullParserException, IOException {
1004 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Jason Monk1c7c3192014-06-26 12:52:18 -04001005 String isPrivilegedString = parser.getAttributeValue(null, "p");
1006 boolean isPrivileged = false;
1007 if (isPrivilegedString == null) {
1008 try {
1009 IPackageManager packageManager = ActivityThread.getPackageManager();
1010 if (packageManager != null) {
1011 ApplicationInfo appInfo = ActivityThread.getPackageManager()
1012 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
1013 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001014 isPrivileged = (appInfo.privateFlags
1015 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001016 }
1017 } else {
1018 // Could not load data, don't add to cache so it will be loaded later.
1019 return;
1020 }
1021 } catch (RemoteException e) {
1022 Slog.w(TAG, "Could not contact PackageManager", e);
1023 }
1024 } else {
1025 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
1026 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001027 int outerDepth = parser.getDepth();
1028 int type;
1029 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1030 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1031 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1032 continue;
1033 }
1034
1035 String tagName = parser.getName();
1036 if (tagName.equals("op")) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001037 Op op = new Op(uid, pkgName, Integer.parseInt(parser.getAttributeValue(null, "n")));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001038 String mode = parser.getAttributeValue(null, "m");
1039 if (mode != null) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001040 op.mode = Integer.parseInt(mode);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001041 }
1042 String time = parser.getAttributeValue(null, "t");
1043 if (time != null) {
1044 op.time = Long.parseLong(time);
1045 }
1046 time = parser.getAttributeValue(null, "r");
1047 if (time != null) {
1048 op.rejectTime = Long.parseLong(time);
1049 }
1050 String dur = parser.getAttributeValue(null, "d");
1051 if (dur != null) {
1052 op.duration = Integer.parseInt(dur);
1053 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001054 HashMap<String, Ops> pkgOps = mUidOps.get(uid);
1055 if (pkgOps == null) {
1056 pkgOps = new HashMap<String, Ops>();
1057 mUidOps.put(uid, pkgOps);
1058 }
1059 Ops ops = pkgOps.get(pkgName);
1060 if (ops == null) {
Jason Monk1c7c3192014-06-26 12:52:18 -04001061 ops = new Ops(pkgName, uid, isPrivileged);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001062 pkgOps.put(pkgName, ops);
1063 }
1064 ops.put(op.op, op);
1065 } else {
1066 Slog.w(TAG, "Unknown element under <pkg>: "
1067 + parser.getName());
1068 XmlUtils.skipCurrentTag(parser);
1069 }
1070 }
1071 }
1072
1073 void writeState() {
1074 synchronized (mFile) {
1075 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
1076
1077 FileOutputStream stream;
1078 try {
1079 stream = mFile.startWrite();
1080 } catch (IOException e) {
1081 Slog.w(TAG, "Failed to write state: " + e);
1082 return;
1083 }
1084
1085 try {
1086 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001087 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001088 out.startDocument(null, true);
1089 out.startTag(null, "app-ops");
1090
1091 if (allOps != null) {
1092 String lastPkg = null;
1093 for (int i=0; i<allOps.size(); i++) {
1094 AppOpsManager.PackageOps pkg = allOps.get(i);
1095 if (!pkg.getPackageName().equals(lastPkg)) {
1096 if (lastPkg != null) {
1097 out.endTag(null, "pkg");
1098 }
1099 lastPkg = pkg.getPackageName();
1100 out.startTag(null, "pkg");
1101 out.attribute(null, "n", lastPkg);
1102 }
1103 out.startTag(null, "uid");
1104 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04001105 synchronized (this) {
1106 Ops ops = getOpsLocked(pkg.getUid(), pkg.getPackageName(), false);
1107 // Should always be present as the list of PackageOps is generated
1108 // from Ops.
1109 if (ops != null) {
1110 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
1111 } else {
1112 out.attribute(null, "p", Boolean.toString(false));
1113 }
1114 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001115 List<AppOpsManager.OpEntry> ops = pkg.getOps();
1116 for (int j=0; j<ops.size(); j++) {
1117 AppOpsManager.OpEntry op = ops.get(j);
1118 out.startTag(null, "op");
1119 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07001120 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001121 out.attribute(null, "m", Integer.toString(op.getMode()));
1122 }
1123 long time = op.getTime();
1124 if (time != 0) {
1125 out.attribute(null, "t", Long.toString(time));
1126 }
1127 time = op.getRejectTime();
1128 if (time != 0) {
1129 out.attribute(null, "r", Long.toString(time));
1130 }
1131 int dur = op.getDuration();
1132 if (dur != 0) {
1133 out.attribute(null, "d", Integer.toString(dur));
1134 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001135 out.endTag(null, "op");
1136 }
1137 out.endTag(null, "uid");
1138 }
1139 if (lastPkg != null) {
1140 out.endTag(null, "pkg");
1141 }
1142 }
1143
1144 out.endTag(null, "app-ops");
1145 out.endDocument();
1146 mFile.finishWrite(stream);
1147 } catch (IOException e) {
1148 Slog.w(TAG, "Failed to write state, restoring backup.", e);
1149 mFile.failWrite(stream);
1150 }
1151 }
1152 }
1153
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001154 @Override
1155 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1156 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1157 != PackageManager.PERMISSION_GRANTED) {
1158 pw.println("Permission Denial: can't dump ApOps service from from pid="
1159 + Binder.getCallingPid()
1160 + ", uid=" + Binder.getCallingUid());
1161 return;
1162 }
1163
1164 synchronized (this) {
1165 pw.println("Current AppOps Service state:");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001166 final long now = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001167 boolean needSep = false;
1168 if (mOpModeWatchers.size() > 0) {
1169 needSep = true;
1170 pw.println(" Op mode watchers:");
1171 for (int i=0; i<mOpModeWatchers.size(); i++) {
1172 pw.print(" Op "); pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
1173 pw.println(":");
1174 ArrayList<Callback> callbacks = mOpModeWatchers.valueAt(i);
1175 for (int j=0; j<callbacks.size(); j++) {
1176 pw.print(" #"); pw.print(j); pw.print(": ");
1177 pw.println(callbacks.get(j));
1178 }
1179 }
1180 }
1181 if (mPackageModeWatchers.size() > 0) {
1182 needSep = true;
1183 pw.println(" Package mode watchers:");
1184 for (int i=0; i<mPackageModeWatchers.size(); i++) {
1185 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
1186 pw.println(":");
1187 ArrayList<Callback> callbacks = mPackageModeWatchers.valueAt(i);
1188 for (int j=0; j<callbacks.size(); j++) {
1189 pw.print(" #"); pw.print(j); pw.print(": ");
1190 pw.println(callbacks.get(j));
1191 }
1192 }
1193 }
1194 if (mModeWatchers.size() > 0) {
1195 needSep = true;
1196 pw.println(" All mode watchers:");
1197 for (int i=0; i<mModeWatchers.size(); i++) {
1198 pw.print(" "); pw.print(mModeWatchers.keyAt(i));
1199 pw.print(" -> "); pw.println(mModeWatchers.valueAt(i));
1200 }
1201 }
1202 if (mClients.size() > 0) {
1203 needSep = true;
1204 pw.println(" Clients:");
1205 for (int i=0; i<mClients.size(); i++) {
1206 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
1207 ClientState cs = mClients.valueAt(i);
1208 pw.print(" "); pw.println(cs);
1209 if (cs.mStartedOps != null && cs.mStartedOps.size() > 0) {
1210 pw.println(" Started ops:");
1211 for (int j=0; j<cs.mStartedOps.size(); j++) {
1212 Op op = cs.mStartedOps.get(j);
1213 pw.print(" "); pw.print("uid="); pw.print(op.uid);
1214 pw.print(" pkg="); pw.print(op.packageName);
1215 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
1216 }
1217 }
1218 }
1219 }
John Spurlock1af30c72014-03-10 08:33:35 -04001220 if (mAudioRestrictions.size() > 0) {
1221 boolean printedHeader = false;
1222 for (int o=0; o<mAudioRestrictions.size(); o++) {
1223 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
1224 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
1225 for (int i=0; i<restrictions.size(); i++) {
1226 if (!printedHeader){
1227 pw.println(" Audio Restrictions:");
1228 printedHeader = true;
1229 needSep = true;
1230 }
John Spurlock7b414672014-07-18 13:02:39 -04001231 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04001232 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04001233 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04001234 Restriction r = restrictions.valueAt(i);
1235 pw.print(": mode="); pw.println(r.mode);
1236 if (!r.exceptionPackages.isEmpty()) {
1237 pw.println(" Exceptions:");
1238 for (int j=0; j<r.exceptionPackages.size(); j++) {
1239 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
1240 }
1241 }
1242 }
1243 }
1244 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001245 if (needSep) {
1246 pw.println();
1247 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001248 for (int i=0; i<mUidOps.size(); i++) {
1249 pw.print(" Uid "); UserHandle.formatUid(pw, mUidOps.keyAt(i)); pw.println(":");
1250 HashMap<String, Ops> pkgOps = mUidOps.valueAt(i);
1251 for (Ops ops : pkgOps.values()) {
1252 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
1253 for (int j=0; j<ops.size(); j++) {
1254 Op op = ops.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001255 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
1256 pw.print(": mode="); pw.print(op.mode);
1257 if (op.time != 0) {
1258 pw.print("; time="); TimeUtils.formatDuration(now-op.time, pw);
1259 pw.print(" ago");
1260 }
1261 if (op.rejectTime != 0) {
1262 pw.print("; rejectTime="); TimeUtils.formatDuration(now-op.rejectTime, pw);
1263 pw.print(" ago");
1264 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001265 if (op.duration == -1) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001266 pw.print(" (running)");
1267 } else if (op.duration != 0) {
1268 pw.print("; duration="); TimeUtils.formatDuration(op.duration, pw);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001269 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001270 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001271 }
1272 }
1273 }
1274 }
1275 }
John Spurlock1af30c72014-03-10 08:33:35 -04001276
1277 private static final class Restriction {
1278 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
1279 int mode;
1280 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
1281 }
Jason Monk62062992014-05-06 09:55:28 -04001282
1283 @Override
Jason Monk62062992014-05-06 09:55:28 -04001284 public void setUserRestrictions(Bundle restrictions, int userHandle) throws RemoteException {
1285 checkSystemUid("setUserRestrictions");
1286 boolean[] opRestrictions = mOpRestrictions.get(userHandle);
1287 if (opRestrictions == null) {
1288 opRestrictions = new boolean[AppOpsManager._NUM_OP];
1289 mOpRestrictions.put(userHandle, opRestrictions);
1290 }
1291 for (int i = 0; i < opRestrictions.length; ++i) {
1292 String restriction = AppOpsManager.opToRestriction(i);
1293 if (restriction != null) {
1294 opRestrictions[i] = restrictions.getBoolean(restriction, false);
1295 } else {
1296 opRestrictions[i] = false;
1297 }
1298 }
1299 }
1300
1301 @Override
1302 public void removeUser(int userHandle) throws RemoteException {
1303 checkSystemUid("removeUser");
1304 mOpRestrictions.remove(userHandle);
Jason Monk62062992014-05-06 09:55:28 -04001305 }
1306
1307 private void checkSystemUid(String function) {
1308 int uid = Binder.getCallingUid();
1309 if (uid != Process.SYSTEM_UID) {
1310 throw new SecurityException(function + " must by called by the system");
1311 }
1312 }
1313
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001314}