blob: aff994c147328a6ae4914d4f3fa9f2b3c8da8be7 [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 Hackborn35654b62013-01-14 17:38:02 -080028import java.util.List;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080029
30import android.app.AppOpsManager;
31import android.content.Context;
32import android.content.pm.PackageManager;
33import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn35654b62013-01-14 17:38:02 -080034import android.os.AsyncTask;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080035import android.os.Binder;
Dianne Hackborn35654b62013-01-14 17:38:02 -080036import android.os.Handler;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080037import android.os.Process;
38import android.os.ServiceManager;
39import android.os.UserHandle;
40import android.util.AtomicFile;
41import android.util.Slog;
42import android.util.SparseArray;
43import android.util.TimeUtils;
Dianne Hackborn35654b62013-01-14 17:38:02 -080044import android.util.Xml;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080045
46import com.android.internal.app.IAppOpsService;
Dianne Hackborn35654b62013-01-14 17:38:02 -080047import com.android.internal.util.FastXmlSerializer;
48import com.android.internal.util.XmlUtils;
49
50import org.xmlpull.v1.XmlPullParser;
51import org.xmlpull.v1.XmlPullParserException;
52import org.xmlpull.v1.XmlSerializer;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080053
54public class AppOpsService extends IAppOpsService.Stub {
55 static final String TAG = "AppOps";
Dianne Hackborn35654b62013-01-14 17:38:02 -080056 static final boolean DEBUG = false;
57
58 // Write at most every 30 minutes.
59 static final long WRITE_DELAY = DEBUG ? 1000 : 30*60*1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080060
61 Context mContext;
62 final AtomicFile mFile;
Dianne Hackborn35654b62013-01-14 17:38:02 -080063 final Handler mHandler;
64
65 boolean mWriteScheduled;
66 final Runnable mWriteRunner = new Runnable() {
67 public void run() {
68 synchronized (AppOpsService.this) {
69 mWriteScheduled = false;
70 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
71 @Override protected Void doInBackground(Void... params) {
72 writeState();
73 return null;
74 }
75 };
76 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
77 }
78 }
79 };
Dianne Hackborna06de0f2012-12-11 16:34:47 -080080
81 final SparseArray<HashMap<String, Ops>> mUidOps
82 = new SparseArray<HashMap<String, Ops>>();
83
84 final static class Ops extends SparseArray<Op> {
85 public final String packageName;
Dianne Hackborn35654b62013-01-14 17:38:02 -080086 public final int uid;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080087
Dianne Hackborn35654b62013-01-14 17:38:02 -080088 public Ops(String _packageName, int _uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080089 packageName = _packageName;
Dianne Hackborn35654b62013-01-14 17:38:02 -080090 uid = _uid;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080091 }
92 }
93
94 final static class Op {
95 public final int op;
96 public int duration;
97 public long time;
Dianne Hackborn35654b62013-01-14 17:38:02 -080098 public int nesting;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080099
100 public Op(int _op) {
101 op = _op;
102 }
103 }
104
Dianne Hackborn35654b62013-01-14 17:38:02 -0800105 public AppOpsService(File storagePath) {
106 mFile = new AtomicFile(storagePath);
107 mHandler = new Handler();
108 readState();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800109 }
110
111 public void publish(Context context) {
112 mContext = context;
113 ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
114 }
115
116 public void shutdown() {
117 Slog.w(TAG, "Writing app ops before shutdown...");
Dianne Hackborn35654b62013-01-14 17:38:02 -0800118 boolean doWrite = false;
119 synchronized (this) {
120 if (mWriteScheduled) {
121 mWriteScheduled = false;
122 doWrite = true;
123 }
124 }
125 if (doWrite) {
126 writeState();
127 }
128 }
129
130 @Override
131 public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
132 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
133 Binder.getCallingPid(), Binder.getCallingUid(), null);
134 ArrayList<AppOpsManager.PackageOps> res = null;
135 synchronized (this) {
136 for (int i=0; i<mUidOps.size(); i++) {
137 HashMap<String, Ops> packages = mUidOps.valueAt(i);
138 for (Ops pkgOps : packages.values()) {
139 ArrayList<AppOpsManager.OpEntry> resOps = null;
140 if (ops == null) {
141 resOps = new ArrayList<AppOpsManager.OpEntry>();
142 for (int j=0; j<pkgOps.size(); j++) {
143 Op curOp = pkgOps.valueAt(j);
144 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.time,
145 curOp.duration));
146 }
147 } else {
148 for (int j=0; j<ops.length; j++) {
149 Op curOp = pkgOps.get(ops[j]);
150 if (curOp != null) {
151 if (resOps == null) {
152 resOps = new ArrayList<AppOpsManager.OpEntry>();
153 }
154 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.time,
155 curOp.duration));
156 }
157 }
158 }
159 if (resOps != null) {
160 if (res == null) {
161 res = new ArrayList<AppOpsManager.PackageOps>();
162 }
163 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
164 pkgOps.packageName, pkgOps.uid, resOps);
165 res.add(resPackage);
166 }
167 }
168 }
169 }
170 return res;
171 }
172
173 @Override
174 public int checkOperation(int code, int uid, String packageName) {
175 uid = handleIncomingUid(uid);
176 synchronized (this) {
177 Op op = getOpLocked(code, uid, packageName, false);
178 if (op == null) {
179 return AppOpsManager.MODE_ALLOWED;
180 }
181 }
182 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800183 }
184
185 @Override
186 public int noteOperation(int code, int uid, String packageName) {
187 uid = handleIncomingUid(uid);
188 synchronized (this) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800189 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800190 if (op == null) {
191 return AppOpsManager.MODE_IGNORED;
192 }
193 if (op.duration == -1) {
194 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
195 + " code " + code + " time=" + op.time + " duration=" + op.duration);
196 }
197 op.time = System.currentTimeMillis();
198 op.duration = 0;
199 }
200 return AppOpsManager.MODE_ALLOWED;
201 }
202
203 @Override
204 public int startOperation(int code, int uid, String packageName) {
205 uid = handleIncomingUid(uid);
206 synchronized (this) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800207 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800208 if (op == null) {
209 return AppOpsManager.MODE_IGNORED;
210 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800211 if (op.nesting == 0) {
212 op.time = System.currentTimeMillis();
213 op.duration = -1;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800214 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800215 op.nesting++;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800216 }
217 return AppOpsManager.MODE_ALLOWED;
218 }
219
220 @Override
221 public void finishOperation(int code, int uid, String packageName) {
222 uid = handleIncomingUid(uid);
223 synchronized (this) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800224 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800225 if (op == null) {
226 return;
227 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800228 if (op.nesting <= 1) {
229 if (op.nesting == 1) {
230 op.duration = (int)(System.currentTimeMillis() - op.time);
231 } else {
232 Slog.w(TAG, "Finishing op nesting under-run: uid " + uid + " pkg " + packageName
233 + " code " + code + " time=" + op.time + " duration=" + op.duration
234 + " nesting=" + op.nesting);
235 }
236 } else {
237 op.nesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800238 }
239 }
240 }
241
242 private int handleIncomingUid(int uid) {
243 if (uid == Binder.getCallingUid()) {
244 return uid;
245 }
246 if (Binder.getCallingPid() == Process.myPid()) {
247 return uid;
248 }
249 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
250 Binder.getCallingPid(), Binder.getCallingUid(), null);
251 return uid;
252 }
253
Dianne Hackborn35654b62013-01-14 17:38:02 -0800254 private Op getOpLocked(int code, int uid, String packageName, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800255 HashMap<String, Ops> pkgOps = mUidOps.get(uid);
256 if (pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800257 if (!edit) {
258 return null;
259 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800260 pkgOps = new HashMap<String, Ops>();
261 mUidOps.put(uid, pkgOps);
262 }
263 Ops ops = pkgOps.get(packageName);
264 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800265 if (!edit) {
266 return null;
267 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800268 // This is the first time we have seen this package name under this uid,
269 // so let's make sure it is valid.
Dianne Hackborn002a54e2013-01-10 17:34:55 -0800270 final long ident = Binder.clearCallingIdentity();
271 try {
272 int pkgUid = -1;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800273 try {
Dianne Hackborn002a54e2013-01-10 17:34:55 -0800274 pkgUid = mContext.getPackageManager().getPackageUid(packageName,
275 UserHandle.getUserId(uid));
276 } catch (NameNotFoundException e) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800277 }
Dianne Hackborn002a54e2013-01-10 17:34:55 -0800278 if (pkgUid != uid) {
279 // Oops! The package name is not valid for the uid they are calling
280 // under. Abort.
281 Slog.w(TAG, "Bad call: specified package " + packageName
282 + " under uid " + uid + " but it is really " + pkgUid);
283 return null;
284 }
285 } finally {
286 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800287 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800288 ops = new Ops(packageName, uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800289 pkgOps.put(packageName, ops);
290 }
291 Op op = ops.get(code);
292 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800293 if (!edit) {
294 return null;
295 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800296 op = new Op(code);
297 ops.put(code, op);
298 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800299 if (edit && !mWriteScheduled) {
300 mWriteScheduled = true;
301 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
302 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800303 return op;
304 }
305
Dianne Hackborn35654b62013-01-14 17:38:02 -0800306 void readState() {
307 synchronized (mFile) {
308 synchronized (this) {
309 FileInputStream stream;
310 try {
311 stream = mFile.openRead();
312 } catch (FileNotFoundException e) {
313 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
314 return;
315 }
316 boolean success = false;
317 try {
318 XmlPullParser parser = Xml.newPullParser();
319 parser.setInput(stream, null);
320 int type;
321 while ((type = parser.next()) != XmlPullParser.START_TAG
322 && type != XmlPullParser.END_DOCUMENT) {
323 ;
324 }
325
326 if (type != XmlPullParser.START_TAG) {
327 throw new IllegalStateException("no start tag found");
328 }
329
330 int outerDepth = parser.getDepth();
331 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
332 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
333 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
334 continue;
335 }
336
337 String tagName = parser.getName();
338 if (tagName.equals("pkg")) {
339 readPackage(parser);
340 } else {
341 Slog.w(TAG, "Unknown element under <app-ops>: "
342 + parser.getName());
343 XmlUtils.skipCurrentTag(parser);
344 }
345 }
346 success = true;
347 } catch (IllegalStateException e) {
348 Slog.w(TAG, "Failed parsing " + e);
349 } catch (NullPointerException e) {
350 Slog.w(TAG, "Failed parsing " + e);
351 } catch (NumberFormatException e) {
352 Slog.w(TAG, "Failed parsing " + e);
353 } catch (XmlPullParserException e) {
354 Slog.w(TAG, "Failed parsing " + e);
355 } catch (IOException e) {
356 Slog.w(TAG, "Failed parsing " + e);
357 } catch (IndexOutOfBoundsException e) {
358 Slog.w(TAG, "Failed parsing " + e);
359 } finally {
360 if (!success) {
361 mUidOps.clear();
362 }
363 try {
364 stream.close();
365 } catch (IOException e) {
366 }
367 }
368 }
369 }
370 }
371
372 void readPackage(XmlPullParser parser) throws NumberFormatException,
373 XmlPullParserException, IOException {
374 String pkgName = parser.getAttributeValue(null, "n");
375 int outerDepth = parser.getDepth();
376 int type;
377 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
378 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
379 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
380 continue;
381 }
382
383 String tagName = parser.getName();
384 if (tagName.equals("uid")) {
385 readUid(parser, pkgName);
386 } else {
387 Slog.w(TAG, "Unknown element under <pkg>: "
388 + parser.getName());
389 XmlUtils.skipCurrentTag(parser);
390 }
391 }
392 }
393
394 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
395 XmlPullParserException, IOException {
396 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
397 int outerDepth = parser.getDepth();
398 int type;
399 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
400 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
401 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
402 continue;
403 }
404
405 String tagName = parser.getName();
406 if (tagName.equals("op")) {
407 Op op = new Op(Integer.parseInt(parser.getAttributeValue(null, "n")));
408 op.time = Long.parseLong(parser.getAttributeValue(null, "t"));
409 op.duration = Integer.parseInt(parser.getAttributeValue(null, "d"));
410 HashMap<String, Ops> pkgOps = mUidOps.get(uid);
411 if (pkgOps == null) {
412 pkgOps = new HashMap<String, Ops>();
413 mUidOps.put(uid, pkgOps);
414 }
415 Ops ops = pkgOps.get(pkgName);
416 if (ops == null) {
417 ops = new Ops(pkgName, uid);
418 pkgOps.put(pkgName, ops);
419 }
420 ops.put(op.op, op);
421 } else {
422 Slog.w(TAG, "Unknown element under <pkg>: "
423 + parser.getName());
424 XmlUtils.skipCurrentTag(parser);
425 }
426 }
427 }
428
429 void writeState() {
430 synchronized (mFile) {
431 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
432
433 FileOutputStream stream;
434 try {
435 stream = mFile.startWrite();
436 } catch (IOException e) {
437 Slog.w(TAG, "Failed to write state: " + e);
438 return;
439 }
440
441 try {
442 XmlSerializer out = new FastXmlSerializer();
443 out.setOutput(stream, "utf-8");
444 out.startDocument(null, true);
445 out.startTag(null, "app-ops");
446
447 if (allOps != null) {
448 String lastPkg = null;
449 for (int i=0; i<allOps.size(); i++) {
450 AppOpsManager.PackageOps pkg = allOps.get(i);
451 if (!pkg.getPackageName().equals(lastPkg)) {
452 if (lastPkg != null) {
453 out.endTag(null, "pkg");
454 }
455 lastPkg = pkg.getPackageName();
456 out.startTag(null, "pkg");
457 out.attribute(null, "n", lastPkg);
458 }
459 out.startTag(null, "uid");
460 out.attribute(null, "n", Integer.toString(pkg.getUid()));
461 List<AppOpsManager.OpEntry> ops = pkg.getOps();
462 for (int j=0; j<ops.size(); j++) {
463 AppOpsManager.OpEntry op = ops.get(j);
464 out.startTag(null, "op");
465 out.attribute(null, "n", Integer.toString(op.getOp()));
466 out.attribute(null, "t", Long.toString(op.getTime()));
467 out.attribute(null, "d", Integer.toString(op.getDuration()));
468 out.endTag(null, "op");
469 }
470 out.endTag(null, "uid");
471 }
472 if (lastPkg != null) {
473 out.endTag(null, "pkg");
474 }
475 }
476
477 out.endTag(null, "app-ops");
478 out.endDocument();
479 mFile.finishWrite(stream);
480 } catch (IOException e) {
481 Slog.w(TAG, "Failed to write state, restoring backup.", e);
482 mFile.failWrite(stream);
483 }
484 }
485 }
486
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800487 @Override
488 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
489 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
490 != PackageManager.PERMISSION_GRANTED) {
491 pw.println("Permission Denial: can't dump ApOps service from from pid="
492 + Binder.getCallingPid()
493 + ", uid=" + Binder.getCallingUid());
494 return;
495 }
496
497 synchronized (this) {
498 pw.println("Current AppOps Service state:");
499 for (int i=0; i<mUidOps.size(); i++) {
500 pw.print(" Uid "); UserHandle.formatUid(pw, mUidOps.keyAt(i)); pw.println(":");
501 HashMap<String, Ops> pkgOps = mUidOps.valueAt(i);
502 for (Ops ops : pkgOps.values()) {
503 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
504 for (int j=0; j<ops.size(); j++) {
505 Op op = ops.valueAt(j);
506 pw.print(" "); pw.print(AppOpsManager.opToString(op.op));
507 pw.print(": time=");
508 TimeUtils.formatDuration(System.currentTimeMillis()-op.time, pw);
509 pw.print(" ago");
510 if (op.duration == -1) {
511 pw.println(" (running)");
512 } else {
513 pw.print("; duration=");
514 TimeUtils.formatDuration(op.duration, pw);
515 pw.println();
516 }
517 }
518 }
519 }
520 }
521 }
522}