blob: 6b4d24843d5bc1aca56adaae9384fce1cb95948f [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 Hackborna06de0f2012-12-11 16:34:47 -080030
31import android.app.AppOpsManager;
32import android.content.Context;
33import android.content.pm.PackageManager;
34import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn35654b62013-01-14 17:38:02 -080035import android.os.AsyncTask;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080036import android.os.Binder;
Dianne Hackborn35654b62013-01-14 17:38:02 -080037import android.os.Handler;
Dianne Hackbornc2293022013-02-06 23:14:49 -080038import android.os.IBinder;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080039import android.os.Process;
Dianne Hackbornc2293022013-02-06 23:14:49 -080040import android.os.RemoteException;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080041import android.os.ServiceManager;
42import android.os.UserHandle;
Dianne Hackborne98f5db2013-07-17 17:23:25 -070043import android.util.ArrayMap;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080044import android.util.AtomicFile;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -080045import android.util.Log;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080046import android.util.Slog;
47import android.util.SparseArray;
48import android.util.TimeUtils;
Dianne Hackborn35654b62013-01-14 17:38:02 -080049import android.util.Xml;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080050
51import com.android.internal.app.IAppOpsService;
Dianne Hackbornc2293022013-02-06 23:14:49 -080052import com.android.internal.app.IAppOpsCallback;
Dianne Hackborn35654b62013-01-14 17:38:02 -080053import com.android.internal.util.FastXmlSerializer;
54import com.android.internal.util.XmlUtils;
55
56import org.xmlpull.v1.XmlPullParser;
57import org.xmlpull.v1.XmlPullParserException;
58import org.xmlpull.v1.XmlSerializer;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080059
60public class AppOpsService extends IAppOpsService.Stub {
61 static final String TAG = "AppOps";
Dianne Hackborn35654b62013-01-14 17:38:02 -080062 static final boolean DEBUG = false;
63
64 // Write at most every 30 minutes.
65 static final long WRITE_DELAY = DEBUG ? 1000 : 30*60*1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080066
67 Context mContext;
68 final AtomicFile mFile;
Dianne Hackborn35654b62013-01-14 17:38:02 -080069 final Handler mHandler;
70
71 boolean mWriteScheduled;
72 final Runnable mWriteRunner = new Runnable() {
73 public void run() {
74 synchronized (AppOpsService.this) {
75 mWriteScheduled = false;
76 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
77 @Override protected Void doInBackground(Void... params) {
78 writeState();
79 return null;
80 }
81 };
82 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
83 }
84 }
85 };
Dianne Hackborna06de0f2012-12-11 16:34:47 -080086
87 final SparseArray<HashMap<String, Ops>> mUidOps
88 = new SparseArray<HashMap<String, Ops>>();
89
Dianne Hackbornc2293022013-02-06 23:14:49 -080090 public final static class Ops extends SparseArray<Op> {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080091 public final String packageName;
Dianne Hackborn35654b62013-01-14 17:38:02 -080092 public final int uid;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080093
Dianne Hackborn35654b62013-01-14 17:38:02 -080094 public Ops(String _packageName, int _uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080095 packageName = _packageName;
Dianne Hackborn35654b62013-01-14 17:38:02 -080096 uid = _uid;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080097 }
98 }
99
Dianne Hackbornc2293022013-02-06 23:14:49 -0800100 public final static class Op {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700101 public final int uid;
102 public final String packageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800103 public final int op;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800104 public int mode;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800105 public int duration;
106 public long time;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800107 public long rejectTime;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800108 public int nesting;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800109
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700110 public Op(int _uid, String _packageName, int _op) {
111 uid = _uid;
112 packageName = _packageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800113 op = _op;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800114 mode = AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800115 }
116 }
117
Dianne Hackbornc2293022013-02-06 23:14:49 -0800118 final SparseArray<ArrayList<Callback>> mOpModeWatchers
119 = new SparseArray<ArrayList<Callback>>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700120 final ArrayMap<String, ArrayList<Callback>> mPackageModeWatchers
121 = new ArrayMap<String, ArrayList<Callback>>();
122 final ArrayMap<IBinder, Callback> mModeWatchers
123 = new ArrayMap<IBinder, Callback>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800124
125 public final class Callback implements DeathRecipient {
126 final IAppOpsCallback mCallback;
127
128 public Callback(IAppOpsCallback callback) {
129 mCallback = callback;
130 try {
131 mCallback.asBinder().linkToDeath(this, 0);
132 } catch (RemoteException e) {
133 }
134 }
135
136 public void unlinkToDeath() {
137 mCallback.asBinder().unlinkToDeath(this, 0);
138 }
139
140 @Override
141 public void binderDied() {
142 stopWatchingMode(mCallback);
143 }
144 }
145
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700146 final ArrayMap<IBinder, ClientState> mClients = new ArrayMap<IBinder, ClientState>();
147
148 public final class ClientState extends Binder implements DeathRecipient {
149 final IBinder mAppToken;
150 final int mPid;
151 final ArrayList<Op> mStartedOps;
152
153 public ClientState(IBinder appToken) {
154 mAppToken = appToken;
155 mPid = Binder.getCallingPid();
156 if (appToken instanceof Binder) {
157 // For local clients, there is no reason to track them.
158 mStartedOps = null;
159 } else {
160 mStartedOps = new ArrayList<Op>();
161 try {
162 mAppToken.linkToDeath(this, 0);
163 } catch (RemoteException e) {
164 }
165 }
166 }
167
168 @Override
169 public String toString() {
170 return "ClientState{" +
171 "mAppToken=" + mAppToken +
172 ", " + (mStartedOps != null ? ("pid=" + mPid) : "local") +
173 '}';
174 }
175
176 @Override
177 public void binderDied() {
178 synchronized (AppOpsService.this) {
179 for (int i=mStartedOps.size()-1; i>=0; i--) {
180 finishOperationLocked(mStartedOps.get(i));
181 }
182 mClients.remove(mAppToken);
183 }
184 }
185 }
186
Dianne Hackborn35654b62013-01-14 17:38:02 -0800187 public AppOpsService(File storagePath) {
188 mFile = new AtomicFile(storagePath);
189 mHandler = new Handler();
190 readState();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800191 }
192
193 public void publish(Context context) {
194 mContext = context;
195 ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
196 }
197
Dianne Hackborn514074f2013-02-11 10:52:46 -0800198 public void systemReady() {
199 synchronized (this) {
200 boolean changed = false;
201 for (int i=0; i<mUidOps.size(); i++) {
202 HashMap<String, Ops> pkgs = mUidOps.valueAt(i);
203 Iterator<Ops> it = pkgs.values().iterator();
204 while (it.hasNext()) {
205 Ops ops = it.next();
206 int curUid;
207 try {
208 curUid = mContext.getPackageManager().getPackageUid(ops.packageName,
209 UserHandle.getUserId(ops.uid));
210 } catch (NameNotFoundException e) {
211 curUid = -1;
212 }
213 if (curUid != ops.uid) {
214 Slog.i(TAG, "Pruning old package " + ops.packageName
215 + "/" + ops.uid + ": new uid=" + curUid);
216 it.remove();
217 changed = true;
218 }
219 }
220 if (pkgs.size() <= 0) {
221 mUidOps.removeAt(i);
222 }
223 }
224 if (changed) {
225 scheduleWriteLocked();
226 }
227 }
228 }
229
230 public void packageRemoved(int uid, String packageName) {
231 synchronized (this) {
232 HashMap<String, Ops> pkgs = mUidOps.get(uid);
233 if (pkgs != null) {
234 if (pkgs.remove(packageName) != null) {
235 if (pkgs.size() <= 0) {
236 mUidOps.remove(uid);
237 }
238 scheduleWriteLocked();
239 }
240 }
241 }
242 }
243
244 public void uidRemoved(int uid) {
245 synchronized (this) {
246 if (mUidOps.indexOfKey(uid) >= 0) {
247 mUidOps.remove(uid);
248 scheduleWriteLocked();
249 }
250 }
251 }
252
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800253 public void shutdown() {
254 Slog.w(TAG, "Writing app ops before shutdown...");
Dianne Hackborn35654b62013-01-14 17:38:02 -0800255 boolean doWrite = false;
256 synchronized (this) {
257 if (mWriteScheduled) {
258 mWriteScheduled = false;
259 doWrite = true;
260 }
261 }
262 if (doWrite) {
263 writeState();
264 }
265 }
266
Dianne Hackborn72e39832013-01-18 18:36:09 -0800267 private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
268 ArrayList<AppOpsManager.OpEntry> resOps = null;
269 if (ops == null) {
270 resOps = new ArrayList<AppOpsManager.OpEntry>();
271 for (int j=0; j<pkgOps.size(); j++) {
272 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800273 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
274 curOp.rejectTime, curOp.duration));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800275 }
276 } else {
277 for (int j=0; j<ops.length; j++) {
278 Op curOp = pkgOps.get(ops[j]);
279 if (curOp != null) {
280 if (resOps == null) {
281 resOps = new ArrayList<AppOpsManager.OpEntry>();
282 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800283 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
284 curOp.rejectTime, curOp.duration));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800285 }
286 }
287 }
288 return resOps;
289 }
290
Dianne Hackborn35654b62013-01-14 17:38:02 -0800291 @Override
292 public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
293 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
294 Binder.getCallingPid(), Binder.getCallingUid(), null);
295 ArrayList<AppOpsManager.PackageOps> res = null;
296 synchronized (this) {
297 for (int i=0; i<mUidOps.size(); i++) {
298 HashMap<String, Ops> packages = mUidOps.valueAt(i);
299 for (Ops pkgOps : packages.values()) {
Dianne Hackborn72e39832013-01-18 18:36:09 -0800300 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800301 if (resOps != null) {
302 if (res == null) {
303 res = new ArrayList<AppOpsManager.PackageOps>();
304 }
305 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
306 pkgOps.packageName, pkgOps.uid, resOps);
307 res.add(resPackage);
308 }
309 }
310 }
311 }
312 return res;
313 }
314
315 @Override
Dianne Hackborn72e39832013-01-18 18:36:09 -0800316 public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
317 int[] ops) {
318 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
319 Binder.getCallingPid(), Binder.getCallingUid(), null);
320 synchronized (this) {
321 Ops pkgOps = getOpsLocked(uid, packageName, false);
322 if (pkgOps == null) {
323 return null;
324 }
325 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
326 if (resOps == null) {
327 return null;
328 }
329 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
330 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
331 pkgOps.packageName, pkgOps.uid, resOps);
332 res.add(resPackage);
333 return res;
334 }
335 }
336
337 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800338 public void setMode(int code, int uid, String packageName, int mode) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800339 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800340 verifyIncomingOp(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800341 ArrayList<Callback> repCbs = null;
342 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800343 synchronized (this) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800344 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800345 if (op != null) {
346 if (op.mode != mode) {
347 op.mode = mode;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800348 ArrayList<Callback> cbs = mOpModeWatchers.get(code);
349 if (cbs != null) {
350 if (repCbs == null) {
351 repCbs = new ArrayList<Callback>();
352 }
353 repCbs.addAll(cbs);
354 }
355 cbs = mPackageModeWatchers.get(packageName);
356 if (cbs != null) {
357 if (repCbs == null) {
358 repCbs = new ArrayList<Callback>();
359 }
360 repCbs.addAll(cbs);
361 }
Dianne Hackborn514074f2013-02-11 10:52:46 -0800362 if (mode == AppOpsManager.MODE_ALLOWED) {
363 // If going into the default mode, prune this op
364 // if there is nothing else interesting in it.
365 if (op.time == 0 && op.rejectTime == 0) {
366 Ops ops = getOpsLocked(uid, packageName, false);
367 if (ops != null) {
368 ops.remove(op.op);
369 if (ops.size() <= 0) {
370 HashMap<String, Ops> pkgOps = mUidOps.get(uid);
371 if (pkgOps != null) {
372 pkgOps.remove(ops.packageName);
373 if (pkgOps.size() <= 0) {
374 mUidOps.remove(uid);
375 }
376 }
377 }
378 }
379 }
380 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800381 scheduleWriteNowLocked();
382 }
383 }
384 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800385 if (repCbs != null) {
386 for (int i=0; i<repCbs.size(); i++) {
387 try {
388 repCbs.get(i).mCallback.opChanged(code, packageName);
389 } catch (RemoteException e) {
390 }
391 }
392 }
393 }
394
395 @Override
396 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
397 synchronized (this) {
398 op = AppOpsManager.opToSwitch(op);
399 Callback cb = mModeWatchers.get(callback.asBinder());
400 if (cb == null) {
401 cb = new Callback(callback);
402 mModeWatchers.put(callback.asBinder(), cb);
403 }
404 if (op != AppOpsManager.OP_NONE) {
405 ArrayList<Callback> cbs = mOpModeWatchers.get(op);
406 if (cbs == null) {
407 cbs = new ArrayList<Callback>();
408 mOpModeWatchers.put(op, cbs);
409 }
410 cbs.add(cb);
411 }
412 if (packageName != null) {
413 ArrayList<Callback> cbs = mPackageModeWatchers.get(packageName);
414 if (cbs == null) {
415 cbs = new ArrayList<Callback>();
416 mPackageModeWatchers.put(packageName, cbs);
417 }
418 cbs.add(cb);
419 }
420 }
421 }
422
423 @Override
424 public void stopWatchingMode(IAppOpsCallback callback) {
425 synchronized (this) {
426 Callback cb = mModeWatchers.remove(callback.asBinder());
427 if (cb != null) {
428 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700429 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800430 ArrayList<Callback> cbs = mOpModeWatchers.valueAt(i);
431 cbs.remove(cb);
432 if (cbs.size() <= 0) {
433 mOpModeWatchers.removeAt(i);
434 }
435 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700436 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
437 ArrayList<Callback> cbs = mPackageModeWatchers.valueAt(i);
438 cbs.remove(cb);
439 if (cbs.size() <= 0) {
440 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800441 }
442 }
443 }
444 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800445 }
446
447 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700448 public IBinder getToken(IBinder clientToken) {
449 synchronized (this) {
450 ClientState cs = mClients.get(clientToken);
451 if (cs == null) {
452 cs = new ClientState(clientToken);
453 mClients.put(clientToken, cs);
454 }
455 return cs;
456 }
457 }
458
459 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800460 public int checkOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800461 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800462 verifyIncomingOp(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800463 synchronized (this) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800464 Op op = getOpLocked(AppOpsManager.opToSwitch(code), uid, packageName, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800465 if (op == null) {
466 return AppOpsManager.MODE_ALLOWED;
467 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800468 return op.mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800469 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800470 }
471
472 @Override
473 public int noteOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800474 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800475 verifyIncomingOp(code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800476 synchronized (this) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800477 Ops ops = getOpsLocked(uid, packageName, true);
478 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800479 if (DEBUG) Log.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
480 + " package " + packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800481 return AppOpsManager.MODE_IGNORED;
482 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800483 Op op = getOpLocked(ops, code, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800484 if (op.duration == -1) {
485 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
486 + " code " + code + " time=" + op.time + " duration=" + op.duration);
487 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800488 op.duration = 0;
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800489 final int switchCode = AppOpsManager.opToSwitch(code);
490 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
491 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
492 if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
493 + switchCode + " (" + code + ") uid " + uid + " package " + packageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800494 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800495 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800496 }
497 if (DEBUG) Log.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
498 + " package " + packageName);
499 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800500 op.rejectTime = 0;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800501 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800502 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800503 }
504
505 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700506 public int startOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800507 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800508 verifyIncomingOp(code);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700509 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800510 synchronized (this) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800511 Ops ops = getOpsLocked(uid, packageName, true);
512 if (ops == null) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800513 if (DEBUG) Log.d(TAG, "startOperation: no op for code " + code + " uid " + uid
514 + " package " + packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800515 return AppOpsManager.MODE_IGNORED;
516 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800517 Op op = getOpLocked(ops, code, true);
518 final int switchCode = AppOpsManager.opToSwitch(code);
519 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
520 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
521 if (DEBUG) Log.d(TAG, "startOperation: reject #" + op.mode + " for code "
522 + switchCode + " (" + code + ") uid " + uid + " package " + packageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800523 op.rejectTime = System.currentTimeMillis();
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800524 return switchOp.mode;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800525 }
526 if (DEBUG) Log.d(TAG, "startOperation: allowing code " + code + " uid " + uid
527 + " package " + packageName);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800528 if (op.nesting == 0) {
529 op.time = System.currentTimeMillis();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800530 op.rejectTime = 0;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800531 op.duration = -1;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800532 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800533 op.nesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700534 if (client.mStartedOps != null) {
535 client.mStartedOps.add(op);
536 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800537 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800538 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800539 }
540
541 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700542 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800543 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800544 verifyIncomingOp(code);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700545 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800546 synchronized (this) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800547 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800548 if (op == null) {
549 return;
550 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700551 if (client.mStartedOps != null) {
552 if (!client.mStartedOps.remove(op)) {
553 throw new IllegalStateException("Operation not started: uid" + op.uid
554 + " pkg=" + op.packageName + " op=" + op.op);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800555 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800556 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700557 finishOperationLocked(op);
558 }
559 }
560
561 void finishOperationLocked(Op op) {
562 if (op.nesting <= 1) {
563 if (op.nesting == 1) {
564 op.duration = (int)(System.currentTimeMillis() - op.time);
565 op.time += op.duration;
566 } else {
567 Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
568 + op.packageName + " code " + op.op + " time=" + op.time
569 + " duration=" + op.duration + " nesting=" + op.nesting);
570 }
571 op.nesting = 0;
572 } else {
573 op.nesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800574 }
575 }
576
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800577 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800578 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800579 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800580 }
581 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800582 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800583 }
584 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
585 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800586 }
587
Dianne Hackborn961321f2013-02-05 17:22:41 -0800588 private void verifyIncomingOp(int op) {
589 if (op >= 0 && op < AppOpsManager._NUM_OP) {
590 return;
591 }
592 throw new IllegalArgumentException("Bad operation #" + op);
593 }
594
Dianne Hackborn72e39832013-01-18 18:36:09 -0800595 private Ops getOpsLocked(int uid, String packageName, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800596 HashMap<String, Ops> pkgOps = mUidOps.get(uid);
597 if (pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800598 if (!edit) {
599 return null;
600 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800601 pkgOps = new HashMap<String, Ops>();
602 mUidOps.put(uid, pkgOps);
603 }
Dianne Hackborn514074f2013-02-11 10:52:46 -0800604 if (uid == 0) {
605 packageName = "root";
606 } else if (uid == Process.SHELL_UID) {
607 packageName = "com.android.shell";
608 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800609 Ops ops = pkgOps.get(packageName);
610 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800611 if (!edit) {
612 return null;
613 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800614 // This is the first time we have seen this package name under this uid,
615 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -0800616 if (uid != 0) {
617 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800618 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800619 int pkgUid = -1;
620 try {
621 pkgUid = mContext.getPackageManager().getPackageUid(packageName,
622 UserHandle.getUserId(uid));
623 } catch (NameNotFoundException e) {
Dianne Hackborn713df152013-05-17 11:27:57 -0700624 if ("media".equals(packageName)) {
625 pkgUid = Process.MEDIA_UID;
626 }
Dianne Hackborn514074f2013-02-11 10:52:46 -0800627 }
628 if (pkgUid != uid) {
629 // Oops! The package name is not valid for the uid they are calling
630 // under. Abort.
631 Slog.w(TAG, "Bad call: specified package " + packageName
632 + " under uid " + uid + " but it is really " + pkgUid);
633 return null;
634 }
635 } finally {
636 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800637 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800638 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800639 ops = new Ops(packageName, uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800640 pkgOps.put(packageName, ops);
641 }
Dianne Hackborn72e39832013-01-18 18:36:09 -0800642 return ops;
643 }
644
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800645 private void scheduleWriteLocked() {
646 if (!mWriteScheduled) {
647 mWriteScheduled = true;
648 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
649 }
650 }
651
652 private void scheduleWriteNowLocked() {
653 if (!mWriteScheduled) {
654 mWriteScheduled = true;
655 }
656 mHandler.removeCallbacks(mWriteRunner);
657 mHandler.post(mWriteRunner);
658 }
659
Dianne Hackborn72e39832013-01-18 18:36:09 -0800660 private Op getOpLocked(int code, int uid, String packageName, boolean edit) {
661 Ops ops = getOpsLocked(uid, packageName, edit);
662 if (ops == null) {
663 return null;
664 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800665 return getOpLocked(ops, code, edit);
666 }
667
668 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800669 Op op = ops.get(code);
670 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800671 if (!edit) {
672 return null;
673 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700674 op = new Op(ops.uid, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800675 ops.put(code, op);
676 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800677 if (edit) {
678 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -0800679 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800680 return op;
681 }
682
Dianne Hackborn35654b62013-01-14 17:38:02 -0800683 void readState() {
684 synchronized (mFile) {
685 synchronized (this) {
686 FileInputStream stream;
687 try {
688 stream = mFile.openRead();
689 } catch (FileNotFoundException e) {
690 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
691 return;
692 }
693 boolean success = false;
694 try {
695 XmlPullParser parser = Xml.newPullParser();
696 parser.setInput(stream, null);
697 int type;
698 while ((type = parser.next()) != XmlPullParser.START_TAG
699 && type != XmlPullParser.END_DOCUMENT) {
700 ;
701 }
702
703 if (type != XmlPullParser.START_TAG) {
704 throw new IllegalStateException("no start tag found");
705 }
706
707 int outerDepth = parser.getDepth();
708 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
709 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
710 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
711 continue;
712 }
713
714 String tagName = parser.getName();
715 if (tagName.equals("pkg")) {
716 readPackage(parser);
717 } else {
718 Slog.w(TAG, "Unknown element under <app-ops>: "
719 + parser.getName());
720 XmlUtils.skipCurrentTag(parser);
721 }
722 }
723 success = true;
724 } catch (IllegalStateException e) {
725 Slog.w(TAG, "Failed parsing " + e);
726 } catch (NullPointerException e) {
727 Slog.w(TAG, "Failed parsing " + e);
728 } catch (NumberFormatException e) {
729 Slog.w(TAG, "Failed parsing " + e);
730 } catch (XmlPullParserException e) {
731 Slog.w(TAG, "Failed parsing " + e);
732 } catch (IOException e) {
733 Slog.w(TAG, "Failed parsing " + e);
734 } catch (IndexOutOfBoundsException e) {
735 Slog.w(TAG, "Failed parsing " + e);
736 } finally {
737 if (!success) {
738 mUidOps.clear();
739 }
740 try {
741 stream.close();
742 } catch (IOException e) {
743 }
744 }
745 }
746 }
747 }
748
749 void readPackage(XmlPullParser parser) throws NumberFormatException,
750 XmlPullParserException, IOException {
751 String pkgName = parser.getAttributeValue(null, "n");
752 int outerDepth = parser.getDepth();
753 int type;
754 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
755 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
756 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
757 continue;
758 }
759
760 String tagName = parser.getName();
761 if (tagName.equals("uid")) {
762 readUid(parser, pkgName);
763 } else {
764 Slog.w(TAG, "Unknown element under <pkg>: "
765 + parser.getName());
766 XmlUtils.skipCurrentTag(parser);
767 }
768 }
769 }
770
771 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
772 XmlPullParserException, IOException {
773 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
774 int outerDepth = parser.getDepth();
775 int type;
776 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
777 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
778 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
779 continue;
780 }
781
782 String tagName = parser.getName();
783 if (tagName.equals("op")) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700784 Op op = new Op(uid, pkgName, Integer.parseInt(parser.getAttributeValue(null, "n")));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800785 String mode = parser.getAttributeValue(null, "m");
786 if (mode != null) {
787 op.mode = Integer.parseInt(mode);
788 }
789 String time = parser.getAttributeValue(null, "t");
790 if (time != null) {
791 op.time = Long.parseLong(time);
792 }
793 time = parser.getAttributeValue(null, "r");
794 if (time != null) {
795 op.rejectTime = Long.parseLong(time);
796 }
797 String dur = parser.getAttributeValue(null, "d");
798 if (dur != null) {
799 op.duration = Integer.parseInt(dur);
800 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800801 HashMap<String, Ops> pkgOps = mUidOps.get(uid);
802 if (pkgOps == null) {
803 pkgOps = new HashMap<String, Ops>();
804 mUidOps.put(uid, pkgOps);
805 }
806 Ops ops = pkgOps.get(pkgName);
807 if (ops == null) {
808 ops = new Ops(pkgName, uid);
809 pkgOps.put(pkgName, ops);
810 }
811 ops.put(op.op, op);
812 } else {
813 Slog.w(TAG, "Unknown element under <pkg>: "
814 + parser.getName());
815 XmlUtils.skipCurrentTag(parser);
816 }
817 }
818 }
819
820 void writeState() {
821 synchronized (mFile) {
822 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
823
824 FileOutputStream stream;
825 try {
826 stream = mFile.startWrite();
827 } catch (IOException e) {
828 Slog.w(TAG, "Failed to write state: " + e);
829 return;
830 }
831
832 try {
833 XmlSerializer out = new FastXmlSerializer();
834 out.setOutput(stream, "utf-8");
835 out.startDocument(null, true);
836 out.startTag(null, "app-ops");
837
838 if (allOps != null) {
839 String lastPkg = null;
840 for (int i=0; i<allOps.size(); i++) {
841 AppOpsManager.PackageOps pkg = allOps.get(i);
842 if (!pkg.getPackageName().equals(lastPkg)) {
843 if (lastPkg != null) {
844 out.endTag(null, "pkg");
845 }
846 lastPkg = pkg.getPackageName();
847 out.startTag(null, "pkg");
848 out.attribute(null, "n", lastPkg);
849 }
850 out.startTag(null, "uid");
851 out.attribute(null, "n", Integer.toString(pkg.getUid()));
852 List<AppOpsManager.OpEntry> ops = pkg.getOps();
853 for (int j=0; j<ops.size(); j++) {
854 AppOpsManager.OpEntry op = ops.get(j);
855 out.startTag(null, "op");
856 out.attribute(null, "n", Integer.toString(op.getOp()));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800857 if (op.getMode() != AppOpsManager.MODE_ALLOWED) {
858 out.attribute(null, "m", Integer.toString(op.getMode()));
859 }
860 long time = op.getTime();
861 if (time != 0) {
862 out.attribute(null, "t", Long.toString(time));
863 }
864 time = op.getRejectTime();
865 if (time != 0) {
866 out.attribute(null, "r", Long.toString(time));
867 }
868 int dur = op.getDuration();
869 if (dur != 0) {
870 out.attribute(null, "d", Integer.toString(dur));
871 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800872 out.endTag(null, "op");
873 }
874 out.endTag(null, "uid");
875 }
876 if (lastPkg != null) {
877 out.endTag(null, "pkg");
878 }
879 }
880
881 out.endTag(null, "app-ops");
882 out.endDocument();
883 mFile.finishWrite(stream);
884 } catch (IOException e) {
885 Slog.w(TAG, "Failed to write state, restoring backup.", e);
886 mFile.failWrite(stream);
887 }
888 }
889 }
890
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800891 @Override
892 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
893 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
894 != PackageManager.PERMISSION_GRANTED) {
895 pw.println("Permission Denial: can't dump ApOps service from from pid="
896 + Binder.getCallingPid()
897 + ", uid=" + Binder.getCallingUid());
898 return;
899 }
900
901 synchronized (this) {
902 pw.println("Current AppOps Service state:");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800903 final long now = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700904 boolean needSep = false;
905 if (mOpModeWatchers.size() > 0) {
906 needSep = true;
907 pw.println(" Op mode watchers:");
908 for (int i=0; i<mOpModeWatchers.size(); i++) {
909 pw.print(" Op "); pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
910 pw.println(":");
911 ArrayList<Callback> callbacks = mOpModeWatchers.valueAt(i);
912 for (int j=0; j<callbacks.size(); j++) {
913 pw.print(" #"); pw.print(j); pw.print(": ");
914 pw.println(callbacks.get(j));
915 }
916 }
917 }
918 if (mPackageModeWatchers.size() > 0) {
919 needSep = true;
920 pw.println(" Package mode watchers:");
921 for (int i=0; i<mPackageModeWatchers.size(); i++) {
922 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
923 pw.println(":");
924 ArrayList<Callback> callbacks = mPackageModeWatchers.valueAt(i);
925 for (int j=0; j<callbacks.size(); j++) {
926 pw.print(" #"); pw.print(j); pw.print(": ");
927 pw.println(callbacks.get(j));
928 }
929 }
930 }
931 if (mModeWatchers.size() > 0) {
932 needSep = true;
933 pw.println(" All mode watchers:");
934 for (int i=0; i<mModeWatchers.size(); i++) {
935 pw.print(" "); pw.print(mModeWatchers.keyAt(i));
936 pw.print(" -> "); pw.println(mModeWatchers.valueAt(i));
937 }
938 }
939 if (mClients.size() > 0) {
940 needSep = true;
941 pw.println(" Clients:");
942 for (int i=0; i<mClients.size(); i++) {
943 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
944 ClientState cs = mClients.valueAt(i);
945 pw.print(" "); pw.println(cs);
946 if (cs.mStartedOps != null && cs.mStartedOps.size() > 0) {
947 pw.println(" Started ops:");
948 for (int j=0; j<cs.mStartedOps.size(); j++) {
949 Op op = cs.mStartedOps.get(j);
950 pw.print(" "); pw.print("uid="); pw.print(op.uid);
951 pw.print(" pkg="); pw.print(op.packageName);
952 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
953 }
954 }
955 }
956 }
957 if (needSep) {
958 pw.println();
959 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800960 for (int i=0; i<mUidOps.size(); i++) {
961 pw.print(" Uid "); UserHandle.formatUid(pw, mUidOps.keyAt(i)); pw.println(":");
962 HashMap<String, Ops> pkgOps = mUidOps.valueAt(i);
963 for (Ops ops : pkgOps.values()) {
964 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
965 for (int j=0; j<ops.size(); j++) {
966 Op op = ops.valueAt(j);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800967 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
968 pw.print(": mode="); pw.print(op.mode);
969 if (op.time != 0) {
970 pw.print("; time="); TimeUtils.formatDuration(now-op.time, pw);
971 pw.print(" ago");
972 }
973 if (op.rejectTime != 0) {
974 pw.print("; rejectTime="); TimeUtils.formatDuration(now-op.rejectTime, pw);
975 pw.print(" ago");
976 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800977 if (op.duration == -1) {
978 pw.println(" (running)");
979 } else {
980 pw.print("; duration=");
981 TimeUtils.formatDuration(op.duration, pw);
982 pw.println();
983 }
984 }
985 }
986 }
987 }
988 }
989}