blob: 14a462e7442dbb85da3e8999817808deb5288762 [file] [log] [blame]
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import java.io.File;
20import java.io.FileDescriptor;
Dianne Hackborn35654b62013-01-14 17:38:02 -080021import java.io.FileInputStream;
22import java.io.FileNotFoundException;
23import java.io.FileOutputStream;
24import java.io.IOException;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080025import java.io.PrintWriter;
Dianne Hackborn35654b62013-01-14 17:38:02 -080026import java.util.ArrayList;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080027import java.util.HashMap;
Dianne Hackbornc2293022013-02-06 23:14:49 -080028import java.util.Iterator;
Dianne Hackborn35654b62013-01-14 17:38:02 -080029import java.util.List;
Dianne Hackborn607b4142013-08-02 18:10:10 -070030import java.util.Map;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080031
Jason Monk1c7c3192014-06-26 12:52:18 -040032import android.app.ActivityThread;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080033import android.app.AppOpsManager;
34import android.content.Context;
Jason Monk1c7c3192014-06-26 12:52:18 -040035import android.content.pm.ApplicationInfo;
36import android.content.pm.IPackageManager;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080037import android.content.pm.PackageManager;
38import android.content.pm.PackageManager.NameNotFoundException;
John Spurlock1af30c72014-03-10 08:33:35 -040039import android.media.AudioService;
Dianne Hackborn35654b62013-01-14 17:38:02 -080040import android.os.AsyncTask;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080041import android.os.Binder;
Jason Monk62062992014-05-06 09:55:28 -040042import android.os.Bundle;
Dianne Hackborn35654b62013-01-14 17:38:02 -080043import android.os.Handler;
Dianne Hackbornc2293022013-02-06 23:14:49 -080044import android.os.IBinder;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080045import android.os.Process;
Dianne Hackbornc2293022013-02-06 23:14:49 -080046import android.os.RemoteException;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080047import android.os.ServiceManager;
48import android.os.UserHandle;
Jason Monk62062992014-05-06 09:55:28 -040049import android.os.UserManager;
Dianne Hackborne98f5db2013-07-17 17:23:25 -070050import android.util.ArrayMap;
John Spurlock1af30c72014-03-10 08:33:35 -040051import android.util.ArraySet;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080052import android.util.AtomicFile;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -080053import android.util.Log;
Dianne Hackborn607b4142013-08-02 18:10:10 -070054import android.util.Pair;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080055import android.util.Slog;
56import android.util.SparseArray;
Jason Monk62062992014-05-06 09:55:28 -040057import android.util.SparseIntArray;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080058import 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;
Jason Monk62062992014-05-06 09:55:28 -040065import com.google.android.util.AbstractMessageParser.MusicTrack;
Dianne Hackborn35654b62013-01-14 17:38:02 -080066
67import org.xmlpull.v1.XmlPullParser;
68import org.xmlpull.v1.XmlPullParserException;
69import org.xmlpull.v1.XmlSerializer;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080070
71public class AppOpsService extends IAppOpsService.Stub {
72 static final String TAG = "AppOps";
Dianne Hackborn35654b62013-01-14 17:38:02 -080073 static final boolean DEBUG = false;
74
75 // Write at most every 30 minutes.
76 static final long WRITE_DELAY = DEBUG ? 1000 : 30*60*1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080077
78 Context mContext;
79 final AtomicFile mFile;
Dianne Hackborn35654b62013-01-14 17:38:02 -080080 final Handler mHandler;
81
82 boolean mWriteScheduled;
83 final Runnable mWriteRunner = new Runnable() {
84 public void run() {
85 synchronized (AppOpsService.this) {
86 mWriteScheduled = false;
87 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
88 @Override protected Void doInBackground(Void... params) {
89 writeState();
90 return null;
91 }
92 };
93 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
94 }
95 }
96 };
Dianne Hackborna06de0f2012-12-11 16:34:47 -080097
98 final SparseArray<HashMap<String, Ops>> mUidOps
99 = new SparseArray<HashMap<String, Ops>>();
100
Jason Monk62062992014-05-06 09:55:28 -0400101 private int mDeviceOwnerUid;
102 private final SparseIntArray mProfileOwnerUids = new SparseIntArray();
103 private final SparseArray<boolean[]> mOpRestrictions = new SparseArray<boolean[]>();
104
Dianne Hackbornc2293022013-02-06 23:14:49 -0800105 public final static class Ops extends SparseArray<Op> {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800106 public final String packageName;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800107 public final int uid;
Jason Monk1c7c3192014-06-26 12:52:18 -0400108 public final boolean isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800109
Jason Monk1c7c3192014-06-26 12:52:18 -0400110 public Ops(String _packageName, int _uid, boolean _isPrivileged) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800111 packageName = _packageName;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800112 uid = _uid;
Jason Monk1c7c3192014-06-26 12:52:18 -0400113 isPrivileged = _isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800114 }
115 }
116
Dianne Hackbornc2293022013-02-06 23:14:49 -0800117 public final static class Op {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700118 public final int uid;
119 public final String packageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800120 public final int op;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800121 public int mode;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800122 public int duration;
123 public long time;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800124 public long rejectTime;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800125 public int nesting;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800126
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700127 public Op(int _uid, String _packageName, int _op) {
128 uid = _uid;
129 packageName = _packageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800130 op = _op;
David Braunf5d83192013-09-16 13:43:51 -0700131 mode = AppOpsManager.opToDefaultMode(op);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800132 }
133 }
134
Dianne Hackbornc2293022013-02-06 23:14:49 -0800135 final SparseArray<ArrayList<Callback>> mOpModeWatchers
136 = new SparseArray<ArrayList<Callback>>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700137 final ArrayMap<String, ArrayList<Callback>> mPackageModeWatchers
138 = new ArrayMap<String, ArrayList<Callback>>();
139 final ArrayMap<IBinder, Callback> mModeWatchers
140 = new ArrayMap<IBinder, Callback>();
John Spurlock1af30c72014-03-10 08:33:35 -0400141 final SparseArray<SparseArray<Restriction>> mAudioRestrictions
142 = new SparseArray<SparseArray<Restriction>>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800143
144 public final class Callback implements DeathRecipient {
145 final IAppOpsCallback mCallback;
146
147 public Callback(IAppOpsCallback callback) {
148 mCallback = callback;
149 try {
150 mCallback.asBinder().linkToDeath(this, 0);
151 } catch (RemoteException e) {
152 }
153 }
154
155 public void unlinkToDeath() {
156 mCallback.asBinder().unlinkToDeath(this, 0);
157 }
158
159 @Override
160 public void binderDied() {
161 stopWatchingMode(mCallback);
162 }
163 }
164
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700165 final ArrayMap<IBinder, ClientState> mClients = new ArrayMap<IBinder, ClientState>();
166
167 public final class ClientState extends Binder implements DeathRecipient {
168 final IBinder mAppToken;
169 final int mPid;
170 final ArrayList<Op> mStartedOps;
171
172 public ClientState(IBinder appToken) {
173 mAppToken = appToken;
174 mPid = Binder.getCallingPid();
175 if (appToken instanceof Binder) {
176 // For local clients, there is no reason to track them.
177 mStartedOps = null;
178 } else {
179 mStartedOps = new ArrayList<Op>();
180 try {
181 mAppToken.linkToDeath(this, 0);
182 } catch (RemoteException e) {
183 }
184 }
185 }
186
187 @Override
188 public String toString() {
189 return "ClientState{" +
190 "mAppToken=" + mAppToken +
191 ", " + (mStartedOps != null ? ("pid=" + mPid) : "local") +
192 '}';
193 }
194
195 @Override
196 public void binderDied() {
197 synchronized (AppOpsService.this) {
198 for (int i=mStartedOps.size()-1; i>=0; i--) {
199 finishOperationLocked(mStartedOps.get(i));
200 }
201 mClients.remove(mAppToken);
202 }
203 }
204 }
205
Jeff Brown6f357d32014-01-15 20:40:55 -0800206 public AppOpsService(File storagePath, Handler handler) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800207 mFile = new AtomicFile(storagePath);
Jeff Brown6f357d32014-01-15 20:40:55 -0800208 mHandler = handler;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800209 readState();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800210 }
David Braunf5d83192013-09-16 13:43:51 -0700211
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800212 public void publish(Context context) {
213 mContext = context;
214 ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
215 }
216
Dianne Hackborn514074f2013-02-11 10:52:46 -0800217 public void systemReady() {
218 synchronized (this) {
219 boolean changed = false;
220 for (int i=0; i<mUidOps.size(); i++) {
221 HashMap<String, Ops> pkgs = mUidOps.valueAt(i);
222 Iterator<Ops> it = pkgs.values().iterator();
223 while (it.hasNext()) {
224 Ops ops = it.next();
225 int curUid;
226 try {
227 curUid = mContext.getPackageManager().getPackageUid(ops.packageName,
228 UserHandle.getUserId(ops.uid));
229 } catch (NameNotFoundException e) {
230 curUid = -1;
231 }
232 if (curUid != ops.uid) {
233 Slog.i(TAG, "Pruning old package " + ops.packageName
234 + "/" + ops.uid + ": new uid=" + curUid);
235 it.remove();
236 changed = true;
237 }
238 }
239 if (pkgs.size() <= 0) {
240 mUidOps.removeAt(i);
241 }
242 }
243 if (changed) {
244 scheduleWriteLocked();
245 }
246 }
247 }
248
249 public void packageRemoved(int uid, String packageName) {
250 synchronized (this) {
251 HashMap<String, Ops> pkgs = mUidOps.get(uid);
252 if (pkgs != null) {
253 if (pkgs.remove(packageName) != null) {
254 if (pkgs.size() <= 0) {
255 mUidOps.remove(uid);
256 }
257 scheduleWriteLocked();
258 }
259 }
260 }
261 }
262
263 public void uidRemoved(int uid) {
264 synchronized (this) {
265 if (mUidOps.indexOfKey(uid) >= 0) {
266 mUidOps.remove(uid);
267 scheduleWriteLocked();
268 }
269 }
270 }
271
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800272 public void shutdown() {
273 Slog.w(TAG, "Writing app ops before shutdown...");
Dianne Hackborn35654b62013-01-14 17:38:02 -0800274 boolean doWrite = false;
275 synchronized (this) {
276 if (mWriteScheduled) {
277 mWriteScheduled = false;
278 doWrite = true;
279 }
280 }
281 if (doWrite) {
282 writeState();
283 }
284 }
285
Dianne Hackborn72e39832013-01-18 18:36:09 -0800286 private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
287 ArrayList<AppOpsManager.OpEntry> resOps = null;
288 if (ops == null) {
289 resOps = new ArrayList<AppOpsManager.OpEntry>();
290 for (int j=0; j<pkgOps.size(); j++) {
291 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800292 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
293 curOp.rejectTime, curOp.duration));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800294 }
295 } else {
296 for (int j=0; j<ops.length; j++) {
297 Op curOp = pkgOps.get(ops[j]);
298 if (curOp != null) {
299 if (resOps == null) {
300 resOps = new ArrayList<AppOpsManager.OpEntry>();
301 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800302 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
303 curOp.rejectTime, curOp.duration));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800304 }
305 }
306 }
307 return resOps;
308 }
309
Dianne Hackborn35654b62013-01-14 17:38:02 -0800310 @Override
311 public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
312 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
313 Binder.getCallingPid(), Binder.getCallingUid(), null);
314 ArrayList<AppOpsManager.PackageOps> res = null;
315 synchronized (this) {
316 for (int i=0; i<mUidOps.size(); i++) {
317 HashMap<String, Ops> packages = mUidOps.valueAt(i);
318 for (Ops pkgOps : packages.values()) {
Dianne Hackborn72e39832013-01-18 18:36:09 -0800319 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800320 if (resOps != null) {
321 if (res == null) {
322 res = new ArrayList<AppOpsManager.PackageOps>();
323 }
324 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
325 pkgOps.packageName, pkgOps.uid, resOps);
326 res.add(resPackage);
327 }
328 }
329 }
330 }
331 return res;
332 }
333
334 @Override
Dianne Hackborn72e39832013-01-18 18:36:09 -0800335 public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
336 int[] ops) {
337 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
338 Binder.getCallingPid(), Binder.getCallingUid(), null);
339 synchronized (this) {
340 Ops pkgOps = getOpsLocked(uid, packageName, false);
341 if (pkgOps == null) {
342 return null;
343 }
344 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
345 if (resOps == null) {
346 return null;
347 }
348 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
349 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
350 pkgOps.packageName, pkgOps.uid, resOps);
351 res.add(resPackage);
352 return res;
353 }
354 }
355
Dianne Hackborn607b4142013-08-02 18:10:10 -0700356 private void pruneOp(Op op, int uid, String packageName) {
357 if (op.time == 0 && op.rejectTime == 0) {
358 Ops ops = getOpsLocked(uid, packageName, false);
359 if (ops != null) {
360 ops.remove(op.op);
361 if (ops.size() <= 0) {
362 HashMap<String, Ops> pkgOps = mUidOps.get(uid);
363 if (pkgOps != null) {
364 pkgOps.remove(ops.packageName);
365 if (pkgOps.size() <= 0) {
366 mUidOps.remove(uid);
367 }
368 }
369 }
370 }
371 }
372 }
373
Dianne Hackborn72e39832013-01-18 18:36:09 -0800374 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800375 public void setMode(int code, int uid, String packageName, int mode) {
Dianne Hackborn133b9df2014-07-01 13:06:10 -0700376 if (Binder.getCallingPid() == Process.myPid()) {
377 return;
378 }
379 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
380 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800381 verifyIncomingOp(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800382 ArrayList<Callback> repCbs = null;
383 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800384 synchronized (this) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800385 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800386 if (op != null) {
387 if (op.mode != mode) {
388 op.mode = mode;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800389 ArrayList<Callback> cbs = mOpModeWatchers.get(code);
390 if (cbs != null) {
391 if (repCbs == null) {
392 repCbs = new ArrayList<Callback>();
393 }
394 repCbs.addAll(cbs);
395 }
396 cbs = mPackageModeWatchers.get(packageName);
397 if (cbs != null) {
398 if (repCbs == null) {
399 repCbs = new ArrayList<Callback>();
400 }
401 repCbs.addAll(cbs);
402 }
David Braunf5d83192013-09-16 13:43:51 -0700403 if (mode == AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800404 // If going into the default mode, prune this op
405 // if there is nothing else interesting in it.
Dianne Hackborn607b4142013-08-02 18:10:10 -0700406 pruneOp(op, uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800407 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800408 scheduleWriteNowLocked();
409 }
410 }
411 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800412 if (repCbs != null) {
413 for (int i=0; i<repCbs.size(); i++) {
414 try {
415 repCbs.get(i).mCallback.opChanged(code, packageName);
416 } catch (RemoteException e) {
417 }
418 }
419 }
420 }
421
Dianne Hackborn607b4142013-08-02 18:10:10 -0700422 private static HashMap<Callback, ArrayList<Pair<String, Integer>>> addCallbacks(
423 HashMap<Callback, ArrayList<Pair<String, Integer>>> callbacks,
424 String packageName, int op, ArrayList<Callback> cbs) {
425 if (cbs == null) {
426 return callbacks;
427 }
428 if (callbacks == null) {
429 callbacks = new HashMap<Callback, ArrayList<Pair<String, Integer>>>();
430 }
431 for (int i=0; i<cbs.size(); i++) {
432 Callback cb = cbs.get(i);
433 ArrayList<Pair<String, Integer>> reports = callbacks.get(cb);
434 if (reports == null) {
435 reports = new ArrayList<Pair<String, Integer>>();
436 callbacks.put(cb, reports);
437 }
438 reports.add(new Pair<String, Integer>(packageName, op));
439 }
440 return callbacks;
441 }
442
443 @Override
444 public void resetAllModes() {
445 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
446 Binder.getCallingPid(), Binder.getCallingUid(), null);
447 HashMap<Callback, ArrayList<Pair<String, Integer>>> callbacks = null;
448 synchronized (this) {
449 boolean changed = false;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700450 for (int i=mUidOps.size()-1; i>=0; i--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700451 HashMap<String, Ops> packages = mUidOps.valueAt(i);
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700452 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
453 while (it.hasNext()) {
454 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -0700455 String packageName = ent.getKey();
456 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700457 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -0700458 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -0700459 if (AppOpsManager.opAllowsReset(curOp.op)
460 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -0700461 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700462 changed = true;
463 callbacks = addCallbacks(callbacks, packageName, curOp.op,
464 mOpModeWatchers.get(curOp.op));
465 callbacks = addCallbacks(callbacks, packageName, curOp.op,
466 mPackageModeWatchers.get(packageName));
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700467 if (curOp.time == 0 && curOp.rejectTime == 0) {
468 pkgOps.removeAt(j);
469 }
Dianne Hackborn607b4142013-08-02 18:10:10 -0700470 }
471 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -0700472 if (pkgOps.size() == 0) {
473 it.remove();
474 }
475 }
476 if (packages.size() == 0) {
477 mUidOps.removeAt(i);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700478 }
479 }
480 if (changed) {
481 scheduleWriteNowLocked();
482 }
483 }
484 if (callbacks != null) {
485 for (Map.Entry<Callback, ArrayList<Pair<String, Integer>>> ent : callbacks.entrySet()) {
486 Callback cb = ent.getKey();
487 ArrayList<Pair<String, Integer>> reports = ent.getValue();
488 for (int i=0; i<reports.size(); i++) {
489 Pair<String, Integer> rep = reports.get(i);
490 try {
491 cb.mCallback.opChanged(rep.second, rep.first);
492 } catch (RemoteException e) {
493 }
494 }
495 }
496 }
497 }
498
Dianne Hackbornc2293022013-02-06 23:14:49 -0800499 @Override
500 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
501 synchronized (this) {
502 op = AppOpsManager.opToSwitch(op);
503 Callback cb = mModeWatchers.get(callback.asBinder());
504 if (cb == null) {
505 cb = new Callback(callback);
506 mModeWatchers.put(callback.asBinder(), cb);
507 }
508 if (op != AppOpsManager.OP_NONE) {
509 ArrayList<Callback> cbs = mOpModeWatchers.get(op);
510 if (cbs == null) {
511 cbs = new ArrayList<Callback>();
512 mOpModeWatchers.put(op, cbs);
513 }
514 cbs.add(cb);
515 }
516 if (packageName != null) {
517 ArrayList<Callback> cbs = mPackageModeWatchers.get(packageName);
518 if (cbs == null) {
519 cbs = new ArrayList<Callback>();
520 mPackageModeWatchers.put(packageName, cbs);
521 }
522 cbs.add(cb);
523 }
524 }
525 }
526
527 @Override
528 public void stopWatchingMode(IAppOpsCallback callback) {
529 synchronized (this) {
530 Callback cb = mModeWatchers.remove(callback.asBinder());
531 if (cb != null) {
532 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700533 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800534 ArrayList<Callback> cbs = mOpModeWatchers.valueAt(i);
535 cbs.remove(cb);
536 if (cbs.size() <= 0) {
537 mOpModeWatchers.removeAt(i);
538 }
539 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700540 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
541 ArrayList<Callback> cbs = mPackageModeWatchers.valueAt(i);
542 cbs.remove(cb);
543 if (cbs.size() <= 0) {
544 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800545 }
546 }
547 }
548 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800549 }
550
551 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700552 public IBinder getToken(IBinder clientToken) {
553 synchronized (this) {
554 ClientState cs = mClients.get(clientToken);
555 if (cs == null) {
556 cs = new ClientState(clientToken);
557 mClients.put(clientToken, cs);
558 }
559 return cs;
560 }
561 }
562
563 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800564 public int checkOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800565 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800566 verifyIncomingOp(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800567 synchronized (this) {
Jason Monk1c7c3192014-06-26 12:52:18 -0400568 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -0400569 return AppOpsManager.MODE_IGNORED;
570 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800571 Op op = getOpLocked(AppOpsManager.opToSwitch(code), uid, packageName, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800572 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -0700573 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800574 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800575 return op.mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800576 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800577 }
578
579 @Override
John Spurlock1af30c72014-03-10 08:33:35 -0400580 public int checkAudioOperation(int code, int stream, int uid, String packageName) {
581 synchronized (this) {
582 final int mode = checkRestrictionLocked(code, stream, uid, packageName);
583 if (mode != AppOpsManager.MODE_ALLOWED) {
584 return mode;
585 }
586 }
587 return checkOperation(code, uid, packageName);
588 }
589
590 private int checkRestrictionLocked(int code, int stream, int uid, String packageName) {
591 final SparseArray<Restriction> streamRestrictions = mAudioRestrictions.get(code);
592 if (streamRestrictions != null) {
593 final Restriction r = streamRestrictions.get(stream);
594 if (r != null && !r.exceptionPackages.contains(packageName)) {
595 return r.mode;
596 }
597 }
598 return AppOpsManager.MODE_ALLOWED;
599 }
600
601 @Override
602 public void setAudioRestriction(int code, int stream, int uid, int mode,
603 String[] exceptionPackages) {
604 verifyIncomingUid(uid);
605 verifyIncomingOp(code);
606 synchronized (this) {
607 SparseArray<Restriction> streamRestrictions = mAudioRestrictions.get(code);
608 if (streamRestrictions == null) {
609 streamRestrictions = new SparseArray<Restriction>();
610 mAudioRestrictions.put(code, streamRestrictions);
611 }
612 streamRestrictions.remove(stream);
613 if (mode != AppOpsManager.MODE_ALLOWED) {
614 final Restriction r = new Restriction();
615 r.mode = mode;
616 if (exceptionPackages != null) {
617 final int N = exceptionPackages.length;
618 r.exceptionPackages = new ArraySet<String>(N);
619 for (int i = 0; i < N; i++) {
620 final String pkg = exceptionPackages[i];
621 if (pkg != null) {
622 r.exceptionPackages.add(pkg.trim());
623 }
624 }
625 }
626 streamRestrictions.put(stream, r);
627 }
628 }
629 }
630
631 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700632 public int checkPackage(int uid, String packageName) {
633 synchronized (this) {
634 if (getOpsLocked(uid, packageName, true) != null) {
635 return AppOpsManager.MODE_ALLOWED;
636 } else {
637 return AppOpsManager.MODE_ERRORED;
638 }
639 }
640 }
641
642 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800643 public int noteOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800644 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800645 verifyIncomingOp(code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800646 synchronized (this) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800647 Ops ops = getOpsLocked(uid, packageName, true);
648 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800649 if (DEBUG) Log.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
650 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700651 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800652 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800653 Op op = getOpLocked(ops, code, true);
Jason Monk1c7c3192014-06-26 12:52:18 -0400654 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -0400655 return AppOpsManager.MODE_IGNORED;
656 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800657 if (op.duration == -1) {
658 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
659 + " code " + code + " time=" + op.time + " duration=" + op.duration);
660 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800661 op.duration = 0;
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800662 final int switchCode = AppOpsManager.opToSwitch(code);
663 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
664 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
665 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
666 + switchCode + " (" + code + ") uid " + uid + " package " + packageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800667 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800668 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800669 }
670 if (DEBUG) Log.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
671 + " package " + packageName);
672 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800673 op.rejectTime = 0;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800674 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800675 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800676 }
677
678 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700679 public int startOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800680 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800681 verifyIncomingOp(code);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700682 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800683 synchronized (this) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800684 Ops ops = getOpsLocked(uid, packageName, true);
685 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800686 if (DEBUG) Log.d(TAG, "startOperation: no op for code " + code + " uid " + uid
687 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700688 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800689 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800690 Op op = getOpLocked(ops, code, true);
Jason Monk1c7c3192014-06-26 12:52:18 -0400691 if (isOpRestricted(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -0400692 return AppOpsManager.MODE_IGNORED;
693 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800694 final int switchCode = AppOpsManager.opToSwitch(code);
695 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
696 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
697 if (DEBUG) Log.d(TAG, "startOperation: reject #" + op.mode + " for code "
698 + switchCode + " (" + code + ") uid " + uid + " package " + packageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800699 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800700 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800701 }
702 if (DEBUG) Log.d(TAG, "startOperation: allowing code " + code + " uid " + uid
703 + " package " + packageName);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800704 if (op.nesting == 0) {
705 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800706 op.rejectTime = 0;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800707 op.duration = -1;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800708 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800709 op.nesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700710 if (client.mStartedOps != null) {
711 client.mStartedOps.add(op);
712 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800713 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800714 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800715 }
716
717 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700718 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800719 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800720 verifyIncomingOp(code);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700721 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800722 synchronized (this) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800723 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800724 if (op == null) {
725 return;
726 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700727 if (client.mStartedOps != null) {
728 if (!client.mStartedOps.remove(op)) {
729 throw new IllegalStateException("Operation not started: uid" + op.uid
730 + " pkg=" + op.packageName + " op=" + op.op);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800731 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800732 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700733 finishOperationLocked(op);
734 }
735 }
736
737 void finishOperationLocked(Op op) {
738 if (op.nesting <= 1) {
739 if (op.nesting == 1) {
740 op.duration = (int)(System.currentTimeMillis() - op.time);
741 op.time += op.duration;
742 } else {
743 Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
744 + op.packageName + " code " + op.op + " time=" + op.time
745 + " duration=" + op.duration + " nesting=" + op.nesting);
746 }
747 op.nesting = 0;
748 } else {
749 op.nesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800750 }
751 }
752
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800753 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800754 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800755 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800756 }
757 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800758 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800759 }
760 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
761 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800762 }
763
Dianne Hackborn961321f2013-02-05 17:22:41 -0800764 private void verifyIncomingOp(int op) {
765 if (op >= 0 && op < AppOpsManager._NUM_OP) {
766 return;
767 }
768 throw new IllegalArgumentException("Bad operation #" + op);
769 }
770
Dianne Hackborn72e39832013-01-18 18:36:09 -0800771 private Ops getOpsLocked(int uid, String packageName, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800772 HashMap<String, Ops> pkgOps = mUidOps.get(uid);
773 if (pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800774 if (!edit) {
775 return null;
776 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800777 pkgOps = new HashMap<String, Ops>();
778 mUidOps.put(uid, pkgOps);
779 }
Dianne Hackborn514074f2013-02-11 10:52:46 -0800780 if (uid == 0) {
781 packageName = "root";
782 } else if (uid == Process.SHELL_UID) {
783 packageName = "com.android.shell";
784 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800785 Ops ops = pkgOps.get(packageName);
786 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800787 if (!edit) {
788 return null;
789 }
Jason Monk1c7c3192014-06-26 12:52:18 -0400790 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800791 // This is the first time we have seen this package name under this uid,
792 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -0800793 if (uid != 0) {
794 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800795 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800796 int pkgUid = -1;
797 try {
Jason Monk1c7c3192014-06-26 12:52:18 -0400798 ApplicationInfo appInfo = ActivityThread.getPackageManager()
799 .getApplicationInfo(packageName, 0, UserHandle.getUserId(uid));
800 if (appInfo != null) {
801 pkgUid = appInfo.uid;
802 isPrivileged = (appInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
803 } else {
804 if ("media".equals(packageName)) {
805 pkgUid = Process.MEDIA_UID;
806 isPrivileged = false;
807 }
Dianne Hackborn713df152013-05-17 11:27:57 -0700808 }
Jason Monk1c7c3192014-06-26 12:52:18 -0400809 } catch (RemoteException e) {
810 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800811 }
812 if (pkgUid != uid) {
813 // Oops! The package name is not valid for the uid they are calling
814 // under. Abort.
815 Slog.w(TAG, "Bad call: specified package " + packageName
816 + " under uid " + uid + " but it is really " + pkgUid);
817 return null;
818 }
819 } finally {
820 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800821 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800822 }
Jason Monk1c7c3192014-06-26 12:52:18 -0400823 ops = new Ops(packageName, uid, isPrivileged);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800824 pkgOps.put(packageName, ops);
825 }
Dianne Hackborn72e39832013-01-18 18:36:09 -0800826 return ops;
827 }
828
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800829 private void scheduleWriteLocked() {
830 if (!mWriteScheduled) {
831 mWriteScheduled = true;
832 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
833 }
834 }
835
836 private void scheduleWriteNowLocked() {
837 if (!mWriteScheduled) {
838 mWriteScheduled = true;
839 }
840 mHandler.removeCallbacks(mWriteRunner);
841 mHandler.post(mWriteRunner);
842 }
843
Dianne Hackborn72e39832013-01-18 18:36:09 -0800844 private Op getOpLocked(int code, int uid, String packageName, boolean edit) {
845 Ops ops = getOpsLocked(uid, packageName, edit);
846 if (ops == null) {
847 return null;
848 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800849 return getOpLocked(ops, code, edit);
850 }
851
852 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800853 Op op = ops.get(code);
854 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800855 if (!edit) {
856 return null;
857 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700858 op = new Op(ops.uid, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800859 ops.put(code, op);
860 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800861 if (edit) {
862 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -0800863 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800864 return op;
865 }
866
Jason Monk1c7c3192014-06-26 12:52:18 -0400867 private boolean isOpRestricted(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -0400868 int userHandle = UserHandle.getUserId(uid);
869 boolean[] opRestrictions = mOpRestrictions.get(userHandle);
870 if ((opRestrictions != null) && opRestrictions[code]) {
Jason Monk1c7c3192014-06-26 12:52:18 -0400871 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
872 synchronized (this) {
873 Ops ops = getOpsLocked(uid, packageName, true);
874 if ((ops != null) && ops.isPrivileged) {
875 return false;
876 }
877 }
878 }
Jason Monk62062992014-05-06 09:55:28 -0400879 if (userHandle == UserHandle.USER_OWNER) {
880 if (uid != mDeviceOwnerUid) {
881 return true;
882 }
883 } else {
884 if (uid != mProfileOwnerUids.get(userHandle, -1)) {
885 return true;
886 }
887 }
888 }
889 return false;
890 }
891
Dianne Hackborn35654b62013-01-14 17:38:02 -0800892 void readState() {
893 synchronized (mFile) {
894 synchronized (this) {
895 FileInputStream stream;
896 try {
897 stream = mFile.openRead();
898 } catch (FileNotFoundException e) {
899 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
900 return;
901 }
902 boolean success = false;
903 try {
904 XmlPullParser parser = Xml.newPullParser();
905 parser.setInput(stream, null);
906 int type;
907 while ((type = parser.next()) != XmlPullParser.START_TAG
908 && type != XmlPullParser.END_DOCUMENT) {
909 ;
910 }
911
912 if (type != XmlPullParser.START_TAG) {
913 throw new IllegalStateException("no start tag found");
914 }
915
916 int outerDepth = parser.getDepth();
917 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
918 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
919 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
920 continue;
921 }
922
923 String tagName = parser.getName();
924 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +0000925 readPackage(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800926 } else {
927 Slog.w(TAG, "Unknown element under <app-ops>: "
928 + parser.getName());
929 XmlUtils.skipCurrentTag(parser);
930 }
931 }
932 success = true;
933 } catch (IllegalStateException e) {
934 Slog.w(TAG, "Failed parsing " + e);
935 } catch (NullPointerException e) {
936 Slog.w(TAG, "Failed parsing " + e);
937 } catch (NumberFormatException e) {
938 Slog.w(TAG, "Failed parsing " + e);
939 } catch (XmlPullParserException e) {
940 Slog.w(TAG, "Failed parsing " + e);
941 } catch (IOException e) {
942 Slog.w(TAG, "Failed parsing " + e);
943 } catch (IndexOutOfBoundsException e) {
944 Slog.w(TAG, "Failed parsing " + e);
945 } finally {
946 if (!success) {
947 mUidOps.clear();
948 }
949 try {
950 stream.close();
951 } catch (IOException e) {
952 }
953 }
954 }
955 }
956 }
957
Dave Burke0997c5bd2013-08-02 20:25:02 +0000958 void readPackage(XmlPullParser parser) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -0800959 XmlPullParserException, IOException {
960 String pkgName = parser.getAttributeValue(null, "n");
961 int outerDepth = parser.getDepth();
962 int type;
963 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
964 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
965 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
966 continue;
967 }
968
969 String tagName = parser.getName();
970 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +0000971 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800972 } else {
973 Slog.w(TAG, "Unknown element under <pkg>: "
974 + parser.getName());
975 XmlUtils.skipCurrentTag(parser);
976 }
977 }
978 }
979
Dave Burke0997c5bd2013-08-02 20:25:02 +0000980 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -0800981 XmlPullParserException, IOException {
982 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Jason Monk1c7c3192014-06-26 12:52:18 -0400983 String isPrivilegedString = parser.getAttributeValue(null, "p");
984 boolean isPrivileged = false;
985 if (isPrivilegedString == null) {
986 try {
987 IPackageManager packageManager = ActivityThread.getPackageManager();
988 if (packageManager != null) {
989 ApplicationInfo appInfo = ActivityThread.getPackageManager()
990 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
991 if (appInfo != null) {
992 isPrivileged = (appInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
993 }
994 } else {
995 // Could not load data, don't add to cache so it will be loaded later.
996 return;
997 }
998 } catch (RemoteException e) {
999 Slog.w(TAG, "Could not contact PackageManager", e);
1000 }
1001 } else {
1002 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
1003 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001004 int outerDepth = parser.getDepth();
1005 int type;
1006 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1007 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1008 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1009 continue;
1010 }
1011
1012 String tagName = parser.getName();
1013 if (tagName.equals("op")) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001014 Op op = new Op(uid, pkgName, Integer.parseInt(parser.getAttributeValue(null, "n")));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001015 String mode = parser.getAttributeValue(null, "m");
1016 if (mode != null) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00001017 op.mode = Integer.parseInt(mode);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001018 }
1019 String time = parser.getAttributeValue(null, "t");
1020 if (time != null) {
1021 op.time = Long.parseLong(time);
1022 }
1023 time = parser.getAttributeValue(null, "r");
1024 if (time != null) {
1025 op.rejectTime = Long.parseLong(time);
1026 }
1027 String dur = parser.getAttributeValue(null, "d");
1028 if (dur != null) {
1029 op.duration = Integer.parseInt(dur);
1030 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001031 HashMap<String, Ops> pkgOps = mUidOps.get(uid);
1032 if (pkgOps == null) {
1033 pkgOps = new HashMap<String, Ops>();
1034 mUidOps.put(uid, pkgOps);
1035 }
1036 Ops ops = pkgOps.get(pkgName);
1037 if (ops == null) {
Jason Monk1c7c3192014-06-26 12:52:18 -04001038 ops = new Ops(pkgName, uid, isPrivileged);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001039 pkgOps.put(pkgName, ops);
1040 }
1041 ops.put(op.op, op);
1042 } else {
1043 Slog.w(TAG, "Unknown element under <pkg>: "
1044 + parser.getName());
1045 XmlUtils.skipCurrentTag(parser);
1046 }
1047 }
1048 }
1049
1050 void writeState() {
1051 synchronized (mFile) {
1052 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
1053
1054 FileOutputStream stream;
1055 try {
1056 stream = mFile.startWrite();
1057 } catch (IOException e) {
1058 Slog.w(TAG, "Failed to write state: " + e);
1059 return;
1060 }
1061
1062 try {
1063 XmlSerializer out = new FastXmlSerializer();
1064 out.setOutput(stream, "utf-8");
1065 out.startDocument(null, true);
1066 out.startTag(null, "app-ops");
1067
1068 if (allOps != null) {
1069 String lastPkg = null;
1070 for (int i=0; i<allOps.size(); i++) {
1071 AppOpsManager.PackageOps pkg = allOps.get(i);
1072 if (!pkg.getPackageName().equals(lastPkg)) {
1073 if (lastPkg != null) {
1074 out.endTag(null, "pkg");
1075 }
1076 lastPkg = pkg.getPackageName();
1077 out.startTag(null, "pkg");
1078 out.attribute(null, "n", lastPkg);
1079 }
1080 out.startTag(null, "uid");
1081 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04001082 synchronized (this) {
1083 Ops ops = getOpsLocked(pkg.getUid(), pkg.getPackageName(), false);
1084 // Should always be present as the list of PackageOps is generated
1085 // from Ops.
1086 if (ops != null) {
1087 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
1088 } else {
1089 out.attribute(null, "p", Boolean.toString(false));
1090 }
1091 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001092 List<AppOpsManager.OpEntry> ops = pkg.getOps();
1093 for (int j=0; j<ops.size(); j++) {
1094 AppOpsManager.OpEntry op = ops.get(j);
1095 out.startTag(null, "op");
1096 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07001097 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001098 out.attribute(null, "m", Integer.toString(op.getMode()));
1099 }
1100 long time = op.getTime();
1101 if (time != 0) {
1102 out.attribute(null, "t", Long.toString(time));
1103 }
1104 time = op.getRejectTime();
1105 if (time != 0) {
1106 out.attribute(null, "r", Long.toString(time));
1107 }
1108 int dur = op.getDuration();
1109 if (dur != 0) {
1110 out.attribute(null, "d", Integer.toString(dur));
1111 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001112 out.endTag(null, "op");
1113 }
1114 out.endTag(null, "uid");
1115 }
1116 if (lastPkg != null) {
1117 out.endTag(null, "pkg");
1118 }
1119 }
1120
1121 out.endTag(null, "app-ops");
1122 out.endDocument();
1123 mFile.finishWrite(stream);
1124 } catch (IOException e) {
1125 Slog.w(TAG, "Failed to write state, restoring backup.", e);
1126 mFile.failWrite(stream);
1127 }
1128 }
1129 }
1130
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001131 @Override
1132 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1133 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1134 != PackageManager.PERMISSION_GRANTED) {
1135 pw.println("Permission Denial: can't dump ApOps service from from pid="
1136 + Binder.getCallingPid()
1137 + ", uid=" + Binder.getCallingUid());
1138 return;
1139 }
1140
1141 synchronized (this) {
1142 pw.println("Current AppOps Service state:");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001143 final long now = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001144 boolean needSep = false;
1145 if (mOpModeWatchers.size() > 0) {
1146 needSep = true;
1147 pw.println(" Op mode watchers:");
1148 for (int i=0; i<mOpModeWatchers.size(); i++) {
1149 pw.print(" Op "); pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
1150 pw.println(":");
1151 ArrayList<Callback> callbacks = mOpModeWatchers.valueAt(i);
1152 for (int j=0; j<callbacks.size(); j++) {
1153 pw.print(" #"); pw.print(j); pw.print(": ");
1154 pw.println(callbacks.get(j));
1155 }
1156 }
1157 }
1158 if (mPackageModeWatchers.size() > 0) {
1159 needSep = true;
1160 pw.println(" Package mode watchers:");
1161 for (int i=0; i<mPackageModeWatchers.size(); i++) {
1162 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
1163 pw.println(":");
1164 ArrayList<Callback> callbacks = mPackageModeWatchers.valueAt(i);
1165 for (int j=0; j<callbacks.size(); j++) {
1166 pw.print(" #"); pw.print(j); pw.print(": ");
1167 pw.println(callbacks.get(j));
1168 }
1169 }
1170 }
1171 if (mModeWatchers.size() > 0) {
1172 needSep = true;
1173 pw.println(" All mode watchers:");
1174 for (int i=0; i<mModeWatchers.size(); i++) {
1175 pw.print(" "); pw.print(mModeWatchers.keyAt(i));
1176 pw.print(" -> "); pw.println(mModeWatchers.valueAt(i));
1177 }
1178 }
1179 if (mClients.size() > 0) {
1180 needSep = true;
1181 pw.println(" Clients:");
1182 for (int i=0; i<mClients.size(); i++) {
1183 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
1184 ClientState cs = mClients.valueAt(i);
1185 pw.print(" "); pw.println(cs);
1186 if (cs.mStartedOps != null && cs.mStartedOps.size() > 0) {
1187 pw.println(" Started ops:");
1188 for (int j=0; j<cs.mStartedOps.size(); j++) {
1189 Op op = cs.mStartedOps.get(j);
1190 pw.print(" "); pw.print("uid="); pw.print(op.uid);
1191 pw.print(" pkg="); pw.print(op.packageName);
1192 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
1193 }
1194 }
1195 }
1196 }
John Spurlock1af30c72014-03-10 08:33:35 -04001197 if (mAudioRestrictions.size() > 0) {
1198 boolean printedHeader = false;
1199 for (int o=0; o<mAudioRestrictions.size(); o++) {
1200 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
1201 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
1202 for (int i=0; i<restrictions.size(); i++) {
1203 if (!printedHeader){
1204 pw.println(" Audio Restrictions:");
1205 printedHeader = true;
1206 needSep = true;
1207 }
1208 final int stream = restrictions.keyAt(i);
1209 pw.print(" "); pw.print(op);
1210 pw.print(" stream="); pw.print(AudioService.streamToString(stream));
1211 Restriction r = restrictions.valueAt(i);
1212 pw.print(": mode="); pw.println(r.mode);
1213 if (!r.exceptionPackages.isEmpty()) {
1214 pw.println(" Exceptions:");
1215 for (int j=0; j<r.exceptionPackages.size(); j++) {
1216 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
1217 }
1218 }
1219 }
1220 }
1221 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001222 if (needSep) {
1223 pw.println();
1224 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001225 for (int i=0; i<mUidOps.size(); i++) {
1226 pw.print(" Uid "); UserHandle.formatUid(pw, mUidOps.keyAt(i)); pw.println(":");
1227 HashMap<String, Ops> pkgOps = mUidOps.valueAt(i);
1228 for (Ops ops : pkgOps.values()) {
1229 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
1230 for (int j=0; j<ops.size(); j++) {
1231 Op op = ops.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001232 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
1233 pw.print(": mode="); pw.print(op.mode);
1234 if (op.time != 0) {
1235 pw.print("; time="); TimeUtils.formatDuration(now-op.time, pw);
1236 pw.print(" ago");
1237 }
1238 if (op.rejectTime != 0) {
1239 pw.print("; rejectTime="); TimeUtils.formatDuration(now-op.rejectTime, pw);
1240 pw.print(" ago");
1241 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001242 if (op.duration == -1) {
1243 pw.println(" (running)");
1244 } else {
1245 pw.print("; duration=");
1246 TimeUtils.formatDuration(op.duration, pw);
1247 pw.println();
1248 }
1249 }
1250 }
1251 }
1252 }
1253 }
John Spurlock1af30c72014-03-10 08:33:35 -04001254
1255 private static final class Restriction {
1256 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
1257 int mode;
1258 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
1259 }
Jason Monk62062992014-05-06 09:55:28 -04001260
1261 @Override
1262 public void setDeviceOwner(String packageName) throws RemoteException {
1263 checkSystemUid("setDeviceOwner");
1264 try {
1265 mDeviceOwnerUid = mContext.getPackageManager().getPackageUid(packageName,
1266 UserHandle.USER_OWNER);
1267 } catch (NameNotFoundException e) {
1268 Log.e(TAG, "Could not find Device Owner UID");
1269 mDeviceOwnerUid = -1;
1270 throw new IllegalArgumentException("Could not find device owner package "
1271 + packageName);
1272 }
1273 }
1274
1275 @Override
1276 public void setProfileOwner(String packageName, int userHandle) throws RemoteException {
1277 checkSystemUid("setProfileOwner");
1278 try {
1279 int uid = mContext.getPackageManager().getPackageUid(packageName,
1280 userHandle);
1281 mProfileOwnerUids.put(userHandle, uid);
1282 } catch (NameNotFoundException e) {
1283 Log.e(TAG, "Could not find Profile Owner UID");
1284 mProfileOwnerUids.put(userHandle, -1);
1285 throw new IllegalArgumentException("Could not find profile owner package "
1286 + packageName);
1287 }
1288 }
1289
1290 @Override
1291 public void setUserRestrictions(Bundle restrictions, int userHandle) throws RemoteException {
1292 checkSystemUid("setUserRestrictions");
1293 boolean[] opRestrictions = mOpRestrictions.get(userHandle);
1294 if (opRestrictions == null) {
1295 opRestrictions = new boolean[AppOpsManager._NUM_OP];
1296 mOpRestrictions.put(userHandle, opRestrictions);
1297 }
1298 for (int i = 0; i < opRestrictions.length; ++i) {
1299 String restriction = AppOpsManager.opToRestriction(i);
1300 if (restriction != null) {
1301 opRestrictions[i] = restrictions.getBoolean(restriction, false);
1302 } else {
1303 opRestrictions[i] = false;
1304 }
1305 }
1306 }
1307
1308 @Override
1309 public void removeUser(int userHandle) throws RemoteException {
1310 checkSystemUid("removeUser");
1311 mOpRestrictions.remove(userHandle);
Amith Yamasanif584f012014-05-19 17:57:25 -07001312 final int index = mProfileOwnerUids.indexOfKey(userHandle);
1313 if (index >= 0) {
1314 mProfileOwnerUids.removeAt(index);
1315 }
Jason Monk62062992014-05-06 09:55:28 -04001316 }
1317
1318 private void checkSystemUid(String function) {
1319 int uid = Binder.getCallingUid();
1320 if (uid != Process.SYSTEM_UID) {
1321 throw new SecurityException(function + " must by called by the system");
1322 }
1323 }
1324
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001325}