AppOpsService.java revision b64afe17064f126eb782c42a238db65f080fc8f0
1/*
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;
21import java.io.FileInputStream;
22import java.io.FileNotFoundException;
23import java.io.FileOutputStream;
24import java.io.IOException;
25import java.io.PrintWriter;
26import java.util.ArrayList;
27import java.util.HashMap;
28import java.util.Iterator;
29import java.util.List;
30import java.util.Map;
31
32import android.app.ActivityThread;
33import android.app.AppOpsManager;
34import android.content.Context;
35import android.content.pm.ApplicationInfo;
36import android.content.pm.IPackageManager;
37import android.content.pm.PackageManager;
38import android.content.pm.PackageManager.NameNotFoundException;
39import android.media.AudioAttributes;
40import android.os.AsyncTask;
41import android.os.Binder;
42import android.os.Bundle;
43import android.os.Handler;
44import android.os.IBinder;
45import android.os.Process;
46import android.os.RemoteException;
47import android.os.ServiceManager;
48import android.os.UserHandle;
49import android.util.ArrayMap;
50import android.util.ArraySet;
51import android.util.AtomicFile;
52import android.util.Log;
53import android.util.Pair;
54import android.util.Slog;
55import android.util.SparseArray;
56import android.util.SparseIntArray;
57import android.util.TimeUtils;
58import android.util.Xml;
59
60import com.android.internal.app.IAppOpsService;
61import com.android.internal.app.IAppOpsCallback;
62import com.android.internal.util.FastXmlSerializer;
63import com.android.internal.util.XmlUtils;
64
65import org.xmlpull.v1.XmlPullParser;
66import org.xmlpull.v1.XmlPullParserException;
67import org.xmlpull.v1.XmlSerializer;
68
69public class AppOpsService extends IAppOpsService.Stub {
70    static final String TAG = "AppOps";
71    static final boolean DEBUG = false;
72
73    // Write at most every 30 minutes.
74    static final long WRITE_DELAY = DEBUG ? 1000 : 30*60*1000;
75
76    Context mContext;
77    final AtomicFile mFile;
78    final Handler mHandler;
79
80    boolean mWriteScheduled;
81    final Runnable mWriteRunner = new Runnable() {
82        public void run() {
83            synchronized (AppOpsService.this) {
84                mWriteScheduled = false;
85                AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
86                    @Override protected Void doInBackground(Void... params) {
87                        writeState();
88                        return null;
89                    }
90                };
91                task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
92            }
93        }
94    };
95
96    final SparseArray<HashMap<String, Ops>> mUidOps
97            = new SparseArray<HashMap<String, Ops>>();
98
99    private int mDeviceOwnerUid;
100    private final SparseIntArray mProfileOwnerUids = new SparseIntArray();
101    private final SparseArray<boolean[]> mOpRestrictions = new SparseArray<boolean[]>();
102
103    public final static class Ops extends SparseArray<Op> {
104        public final String packageName;
105        public final int uid;
106        public final boolean isPrivileged;
107
108        public Ops(String _packageName, int _uid, boolean _isPrivileged) {
109            packageName = _packageName;
110            uid = _uid;
111            isPrivileged = _isPrivileged;
112        }
113    }
114
115    public final static class Op {
116        public final int uid;
117        public final String packageName;
118        public final int op;
119        public int mode;
120        public int duration;
121        public long time;
122        public long rejectTime;
123        public int nesting;
124
125        public Op(int _uid, String _packageName, int _op) {
126            uid = _uid;
127            packageName = _packageName;
128            op = _op;
129            mode = AppOpsManager.opToDefaultMode(op);
130        }
131    }
132
133    final SparseArray<ArrayList<Callback>> mOpModeWatchers
134            = new SparseArray<ArrayList<Callback>>();
135    final ArrayMap<String, ArrayList<Callback>> mPackageModeWatchers
136            = new ArrayMap<String, ArrayList<Callback>>();
137    final ArrayMap<IBinder, Callback> mModeWatchers
138            = new ArrayMap<IBinder, Callback>();
139    final SparseArray<SparseArray<Restriction>> mAudioRestrictions
140            = new SparseArray<SparseArray<Restriction>>();
141
142    public final class Callback implements DeathRecipient {
143        final IAppOpsCallback mCallback;
144
145        public Callback(IAppOpsCallback callback) {
146            mCallback = callback;
147            try {
148                mCallback.asBinder().linkToDeath(this, 0);
149            } catch (RemoteException e) {
150            }
151        }
152
153        public void unlinkToDeath() {
154            mCallback.asBinder().unlinkToDeath(this, 0);
155        }
156
157        @Override
158        public void binderDied() {
159            stopWatchingMode(mCallback);
160        }
161    }
162
163    final ArrayMap<IBinder, ClientState> mClients = new ArrayMap<IBinder, ClientState>();
164
165    public final class ClientState extends Binder implements DeathRecipient {
166        final IBinder mAppToken;
167        final int mPid;
168        final ArrayList<Op> mStartedOps;
169
170        public ClientState(IBinder appToken) {
171            mAppToken = appToken;
172            mPid = Binder.getCallingPid();
173            if (appToken instanceof Binder) {
174                // For local clients, there is no reason to track them.
175                mStartedOps = null;
176            } else {
177                mStartedOps = new ArrayList<Op>();
178                try {
179                    mAppToken.linkToDeath(this, 0);
180                } catch (RemoteException e) {
181                }
182            }
183        }
184
185        @Override
186        public String toString() {
187            return "ClientState{" +
188                    "mAppToken=" + mAppToken +
189                    ", " + (mStartedOps != null ? ("pid=" + mPid) : "local") +
190                    '}';
191        }
192
193        @Override
194        public void binderDied() {
195            synchronized (AppOpsService.this) {
196                for (int i=mStartedOps.size()-1; i>=0; i--) {
197                    finishOperationLocked(mStartedOps.get(i));
198                }
199                mClients.remove(mAppToken);
200            }
201        }
202    }
203
204    public AppOpsService(File storagePath, Handler handler) {
205        mFile = new AtomicFile(storagePath);
206        mHandler = handler;
207        readState();
208    }
209
210    public void publish(Context context) {
211        mContext = context;
212        ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
213    }
214
215    public void systemReady() {
216        synchronized (this) {
217            boolean changed = false;
218            for (int i=0; i<mUidOps.size(); i++) {
219                HashMap<String, Ops> pkgs = mUidOps.valueAt(i);
220                Iterator<Ops> it = pkgs.values().iterator();
221                while (it.hasNext()) {
222                    Ops ops = it.next();
223                    int curUid;
224                    try {
225                        curUid = mContext.getPackageManager().getPackageUid(ops.packageName,
226                                UserHandle.getUserId(ops.uid));
227                    } catch (NameNotFoundException e) {
228                        curUid = -1;
229                    }
230                    if (curUid != ops.uid) {
231                        Slog.i(TAG, "Pruning old package " + ops.packageName
232                                + "/" + ops.uid + ": new uid=" + curUid);
233                        it.remove();
234                        changed = true;
235                    }
236                }
237                if (pkgs.size() <= 0) {
238                    mUidOps.removeAt(i);
239                }
240            }
241            if (changed) {
242                scheduleWriteLocked();
243            }
244        }
245    }
246
247    public void packageRemoved(int uid, String packageName) {
248        synchronized (this) {
249            HashMap<String, Ops> pkgs = mUidOps.get(uid);
250            if (pkgs != null) {
251                if (pkgs.remove(packageName) != null) {
252                    if (pkgs.size() <= 0) {
253                        mUidOps.remove(uid);
254                    }
255                    scheduleWriteLocked();
256                }
257            }
258        }
259    }
260
261    public void uidRemoved(int uid) {
262        synchronized (this) {
263            if (mUidOps.indexOfKey(uid) >= 0) {
264                mUidOps.remove(uid);
265                scheduleWriteLocked();
266            }
267        }
268    }
269
270    public void shutdown() {
271        Slog.w(TAG, "Writing app ops before shutdown...");
272        boolean doWrite = false;
273        synchronized (this) {
274            if (mWriteScheduled) {
275                mWriteScheduled = false;
276                doWrite = true;
277            }
278        }
279        if (doWrite) {
280            writeState();
281        }
282    }
283
284    private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
285        ArrayList<AppOpsManager.OpEntry> resOps = null;
286        if (ops == null) {
287            resOps = new ArrayList<AppOpsManager.OpEntry>();
288            for (int j=0; j<pkgOps.size(); j++) {
289                Op curOp = pkgOps.valueAt(j);
290                resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
291                        curOp.rejectTime, curOp.duration));
292            }
293        } else {
294            for (int j=0; j<ops.length; j++) {
295                Op curOp = pkgOps.get(ops[j]);
296                if (curOp != null) {
297                    if (resOps == null) {
298                        resOps = new ArrayList<AppOpsManager.OpEntry>();
299                    }
300                    resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
301                            curOp.rejectTime, curOp.duration));
302                }
303            }
304        }
305        return resOps;
306    }
307
308    @Override
309    public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
310        mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
311                Binder.getCallingPid(), Binder.getCallingUid(), null);
312        ArrayList<AppOpsManager.PackageOps> res = null;
313        synchronized (this) {
314            for (int i=0; i<mUidOps.size(); i++) {
315                HashMap<String, Ops> packages = mUidOps.valueAt(i);
316                for (Ops pkgOps : packages.values()) {
317                    ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
318                    if (resOps != null) {
319                        if (res == null) {
320                            res = new ArrayList<AppOpsManager.PackageOps>();
321                        }
322                        AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
323                                pkgOps.packageName, pkgOps.uid, resOps);
324                        res.add(resPackage);
325                    }
326                }
327            }
328        }
329        return res;
330    }
331
332    @Override
333    public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
334            int[] ops) {
335        mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
336                Binder.getCallingPid(), Binder.getCallingUid(), null);
337        synchronized (this) {
338            Ops pkgOps = getOpsLocked(uid, packageName, false);
339            if (pkgOps == null) {
340                return null;
341            }
342            ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
343            if (resOps == null) {
344                return null;
345            }
346            ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
347            AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
348                    pkgOps.packageName, pkgOps.uid, resOps);
349            res.add(resPackage);
350            return res;
351        }
352    }
353
354    private void pruneOp(Op op, int uid, String packageName) {
355        if (op.time == 0 && op.rejectTime == 0) {
356            Ops ops = getOpsLocked(uid, packageName, false);
357            if (ops != null) {
358                ops.remove(op.op);
359                if (ops.size() <= 0) {
360                    HashMap<String, Ops> pkgOps = mUidOps.get(uid);
361                    if (pkgOps != null) {
362                        pkgOps.remove(ops.packageName);
363                        if (pkgOps.size() <= 0) {
364                            mUidOps.remove(uid);
365                        }
366                    }
367                }
368            }
369        }
370    }
371
372    @Override
373    public void setMode(int code, int uid, String packageName, int mode) {
374        if (Binder.getCallingPid() != Process.myPid()) {
375            mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
376                    Binder.getCallingPid(), Binder.getCallingUid(), null);
377        }
378        verifyIncomingOp(code);
379        ArrayList<Callback> repCbs = null;
380        code = AppOpsManager.opToSwitch(code);
381        synchronized (this) {
382            Op op = getOpLocked(code, uid, packageName, true);
383            if (op != null) {
384                if (op.mode != mode) {
385                    op.mode = mode;
386                    ArrayList<Callback> cbs = mOpModeWatchers.get(code);
387                    if (cbs != null) {
388                        if (repCbs == null) {
389                            repCbs = new ArrayList<Callback>();
390                        }
391                        repCbs.addAll(cbs);
392                    }
393                    cbs = mPackageModeWatchers.get(packageName);
394                    if (cbs != null) {
395                        if (repCbs == null) {
396                            repCbs = new ArrayList<Callback>();
397                        }
398                        repCbs.addAll(cbs);
399                    }
400                    if (mode == AppOpsManager.opToDefaultMode(op.op)) {
401                        // If going into the default mode, prune this op
402                        // if there is nothing else interesting in it.
403                        pruneOp(op, uid, packageName);
404                    }
405                    scheduleWriteNowLocked();
406                }
407            }
408        }
409        if (repCbs != null) {
410            for (int i=0; i<repCbs.size(); i++) {
411                try {
412                    repCbs.get(i).mCallback.opChanged(code, packageName);
413                } catch (RemoteException e) {
414                }
415            }
416        }
417    }
418
419    private static HashMap<Callback, ArrayList<Pair<String, Integer>>> addCallbacks(
420            HashMap<Callback, ArrayList<Pair<String, Integer>>> callbacks,
421            String packageName, int op, ArrayList<Callback> cbs) {
422        if (cbs == null) {
423            return callbacks;
424        }
425        if (callbacks == null) {
426            callbacks = new HashMap<Callback, ArrayList<Pair<String, Integer>>>();
427        }
428        for (int i=0; i<cbs.size(); i++) {
429            Callback cb = cbs.get(i);
430            ArrayList<Pair<String, Integer>> reports = callbacks.get(cb);
431            if (reports == null) {
432                reports = new ArrayList<Pair<String, Integer>>();
433                callbacks.put(cb, reports);
434            }
435            reports.add(new Pair<String, Integer>(packageName, op));
436        }
437        return callbacks;
438    }
439
440    @Override
441    public void resetAllModes() {
442        mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
443                Binder.getCallingPid(), Binder.getCallingUid(), null);
444        HashMap<Callback, ArrayList<Pair<String, Integer>>> callbacks = null;
445        synchronized (this) {
446            boolean changed = false;
447            for (int i=mUidOps.size()-1; i>=0; i--) {
448                HashMap<String, Ops> packages = mUidOps.valueAt(i);
449                Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
450                while (it.hasNext()) {
451                    Map.Entry<String, Ops> ent = it.next();
452                    String packageName = ent.getKey();
453                    Ops pkgOps = ent.getValue();
454                    for (int j=pkgOps.size()-1; j>=0; j--) {
455                        Op curOp = pkgOps.valueAt(j);
456                        if (AppOpsManager.opAllowsReset(curOp.op)
457                                && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
458                            curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
459                            changed = true;
460                            callbacks = addCallbacks(callbacks, packageName, curOp.op,
461                                    mOpModeWatchers.get(curOp.op));
462                            callbacks = addCallbacks(callbacks, packageName, curOp.op,
463                                    mPackageModeWatchers.get(packageName));
464                            if (curOp.time == 0 && curOp.rejectTime == 0) {
465                                pkgOps.removeAt(j);
466                            }
467                        }
468                    }
469                    if (pkgOps.size() == 0) {
470                        it.remove();
471                    }
472                }
473                if (packages.size() == 0) {
474                    mUidOps.removeAt(i);
475                }
476            }
477            if (changed) {
478                scheduleWriteNowLocked();
479            }
480        }
481        if (callbacks != null) {
482            for (Map.Entry<Callback, ArrayList<Pair<String, Integer>>> ent : callbacks.entrySet()) {
483                Callback cb = ent.getKey();
484                ArrayList<Pair<String, Integer>> reports = ent.getValue();
485                for (int i=0; i<reports.size(); i++) {
486                    Pair<String, Integer> rep = reports.get(i);
487                    try {
488                        cb.mCallback.opChanged(rep.second, rep.first);
489                    } catch (RemoteException e) {
490                    }
491                }
492            }
493        }
494    }
495
496    @Override
497    public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
498        synchronized (this) {
499            op = AppOpsManager.opToSwitch(op);
500            Callback cb = mModeWatchers.get(callback.asBinder());
501            if (cb == null) {
502                cb = new Callback(callback);
503                mModeWatchers.put(callback.asBinder(), cb);
504            }
505            if (op != AppOpsManager.OP_NONE) {
506                ArrayList<Callback> cbs = mOpModeWatchers.get(op);
507                if (cbs == null) {
508                    cbs = new ArrayList<Callback>();
509                    mOpModeWatchers.put(op, cbs);
510                }
511                cbs.add(cb);
512            }
513            if (packageName != null) {
514                ArrayList<Callback> cbs = mPackageModeWatchers.get(packageName);
515                if (cbs == null) {
516                    cbs = new ArrayList<Callback>();
517                    mPackageModeWatchers.put(packageName, cbs);
518                }
519                cbs.add(cb);
520            }
521        }
522    }
523
524    @Override
525    public void stopWatchingMode(IAppOpsCallback callback) {
526        synchronized (this) {
527            Callback cb = mModeWatchers.remove(callback.asBinder());
528            if (cb != null) {
529                cb.unlinkToDeath();
530                for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
531                    ArrayList<Callback> cbs = mOpModeWatchers.valueAt(i);
532                    cbs.remove(cb);
533                    if (cbs.size() <= 0) {
534                        mOpModeWatchers.removeAt(i);
535                    }
536                }
537                for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
538                    ArrayList<Callback> cbs = mPackageModeWatchers.valueAt(i);
539                    cbs.remove(cb);
540                    if (cbs.size() <= 0) {
541                        mPackageModeWatchers.removeAt(i);
542                    }
543                }
544            }
545        }
546    }
547
548    @Override
549    public IBinder getToken(IBinder clientToken) {
550        synchronized (this) {
551            ClientState cs = mClients.get(clientToken);
552            if (cs == null) {
553                cs = new ClientState(clientToken);
554                mClients.put(clientToken, cs);
555            }
556            return cs;
557        }
558    }
559
560    @Override
561    public int checkOperation(int code, int uid, String packageName) {
562        verifyIncomingUid(uid);
563        verifyIncomingOp(code);
564        synchronized (this) {
565            if (isOpRestricted(uid, code, packageName)) {
566                return AppOpsManager.MODE_IGNORED;
567            }
568            Op op = getOpLocked(AppOpsManager.opToSwitch(code), uid, packageName, false);
569            if (op == null) {
570                return AppOpsManager.opToDefaultMode(code);
571            }
572            return op.mode;
573        }
574    }
575
576    @Override
577    public int checkAudioOperation(int code, int usage, int uid, String packageName) {
578        synchronized (this) {
579            final int mode = checkRestrictionLocked(code, usage, uid, packageName);
580            if (mode != AppOpsManager.MODE_ALLOWED) {
581                return mode;
582            }
583        }
584        return checkOperation(code, uid, packageName);
585    }
586
587    private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
588        final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
589        if (usageRestrictions != null) {
590            final Restriction r = usageRestrictions.get(usage);
591            if (r != null && !r.exceptionPackages.contains(packageName)) {
592                return r.mode;
593            }
594        }
595        return AppOpsManager.MODE_ALLOWED;
596    }
597
598    @Override
599    public void setAudioRestriction(int code, int usage, int uid, int mode,
600            String[] exceptionPackages) {
601        verifyIncomingUid(uid);
602        verifyIncomingOp(code);
603        synchronized (this) {
604            SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
605            if (usageRestrictions == null) {
606                usageRestrictions = new SparseArray<Restriction>();
607                mAudioRestrictions.put(code, usageRestrictions);
608            }
609            usageRestrictions.remove(usage);
610            if (mode != AppOpsManager.MODE_ALLOWED) {
611                final Restriction r = new Restriction();
612                r.mode = mode;
613                if (exceptionPackages != null) {
614                    final int N = exceptionPackages.length;
615                    r.exceptionPackages = new ArraySet<String>(N);
616                    for (int i = 0; i < N; i++) {
617                        final String pkg = exceptionPackages[i];
618                        if (pkg != null) {
619                            r.exceptionPackages.add(pkg.trim());
620                        }
621                    }
622                }
623                usageRestrictions.put(usage, r);
624            }
625        }
626    }
627
628    @Override
629    public int checkPackage(int uid, String packageName) {
630        synchronized (this) {
631            if (getOpsLocked(uid, packageName, true) != null) {
632                return AppOpsManager.MODE_ALLOWED;
633            } else {
634                return AppOpsManager.MODE_ERRORED;
635            }
636        }
637    }
638
639    @Override
640    public int noteOperation(int code, int uid, String packageName) {
641        verifyIncomingUid(uid);
642        verifyIncomingOp(code);
643        synchronized (this) {
644            Ops ops = getOpsLocked(uid, packageName, true);
645            if (ops == null) {
646                if (DEBUG) Log.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
647                        + " package " + packageName);
648                return AppOpsManager.MODE_ERRORED;
649            }
650            Op op = getOpLocked(ops, code, true);
651            if (isOpRestricted(uid, code, packageName)) {
652                return AppOpsManager.MODE_IGNORED;
653            }
654            if (op.duration == -1) {
655                Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
656                        + " code " + code + " time=" + op.time + " duration=" + op.duration);
657            }
658            op.duration = 0;
659            final int switchCode = AppOpsManager.opToSwitch(code);
660            final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
661            if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
662                if (DEBUG) Log.d(TAG, "noteOperation: reject #" + op.mode + " for code "
663                        + switchCode + " (" + code + ") uid " + uid + " package " + packageName);
664                op.rejectTime = System.currentTimeMillis();
665                return switchOp.mode;
666            }
667            if (DEBUG) Log.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
668                    + " package " + packageName);
669            op.time = System.currentTimeMillis();
670            op.rejectTime = 0;
671            return AppOpsManager.MODE_ALLOWED;
672        }
673    }
674
675    @Override
676    public int startOperation(IBinder token, int code, int uid, String packageName) {
677        verifyIncomingUid(uid);
678        verifyIncomingOp(code);
679        ClientState client = (ClientState)token;
680        synchronized (this) {
681            Ops ops = getOpsLocked(uid, packageName, true);
682            if (ops == null) {
683                if (DEBUG) Log.d(TAG, "startOperation: no op for code " + code + " uid " + uid
684                        + " package " + packageName);
685                return AppOpsManager.MODE_ERRORED;
686            }
687            Op op = getOpLocked(ops, code, true);
688            if (isOpRestricted(uid, code, packageName)) {
689                return AppOpsManager.MODE_IGNORED;
690            }
691            final int switchCode = AppOpsManager.opToSwitch(code);
692            final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
693            if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
694                if (DEBUG) Log.d(TAG, "startOperation: reject #" + op.mode + " for code "
695                        + switchCode + " (" + code + ") uid " + uid + " package " + packageName);
696                op.rejectTime = System.currentTimeMillis();
697                return switchOp.mode;
698            }
699            if (DEBUG) Log.d(TAG, "startOperation: allowing code " + code + " uid " + uid
700                    + " package " + packageName);
701            if (op.nesting == 0) {
702                op.time = System.currentTimeMillis();
703                op.rejectTime = 0;
704                op.duration = -1;
705            }
706            op.nesting++;
707            if (client.mStartedOps != null) {
708                client.mStartedOps.add(op);
709            }
710            return AppOpsManager.MODE_ALLOWED;
711        }
712    }
713
714    @Override
715    public void finishOperation(IBinder token, int code, int uid, String packageName) {
716        verifyIncomingUid(uid);
717        verifyIncomingOp(code);
718        ClientState client = (ClientState)token;
719        synchronized (this) {
720            Op op = getOpLocked(code, uid, packageName, true);
721            if (op == null) {
722                return;
723            }
724            if (client.mStartedOps != null) {
725                if (!client.mStartedOps.remove(op)) {
726                    throw new IllegalStateException("Operation not started: uid" + op.uid
727                            + " pkg=" + op.packageName + " op=" + op.op);
728                }
729            }
730            finishOperationLocked(op);
731        }
732    }
733
734    void finishOperationLocked(Op op) {
735        if (op.nesting <= 1) {
736            if (op.nesting == 1) {
737                op.duration = (int)(System.currentTimeMillis() - op.time);
738                op.time += op.duration;
739            } else {
740                Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
741                        + op.packageName + " code " + op.op + " time=" + op.time
742                        + " duration=" + op.duration + " nesting=" + op.nesting);
743            }
744            op.nesting = 0;
745        } else {
746            op.nesting--;
747        }
748    }
749
750    private void verifyIncomingUid(int uid) {
751        if (uid == Binder.getCallingUid()) {
752            return;
753        }
754        if (Binder.getCallingPid() == Process.myPid()) {
755            return;
756        }
757        mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
758                Binder.getCallingPid(), Binder.getCallingUid(), null);
759    }
760
761    private void verifyIncomingOp(int op) {
762        if (op >= 0 && op < AppOpsManager._NUM_OP) {
763            return;
764        }
765        throw new IllegalArgumentException("Bad operation #" + op);
766    }
767
768    private Ops getOpsLocked(int uid, String packageName, boolean edit) {
769        HashMap<String, Ops> pkgOps = mUidOps.get(uid);
770        if (pkgOps == null) {
771            if (!edit) {
772                return null;
773            }
774            pkgOps = new HashMap<String, Ops>();
775            mUidOps.put(uid, pkgOps);
776        }
777        if (uid == 0) {
778            packageName = "root";
779        } else if (uid == Process.SHELL_UID) {
780            packageName = "com.android.shell";
781        }
782        Ops ops = pkgOps.get(packageName);
783        if (ops == null) {
784            if (!edit) {
785                return null;
786            }
787            boolean isPrivileged = false;
788            // This is the first time we have seen this package name under this uid,
789            // so let's make sure it is valid.
790            if (uid != 0) {
791                final long ident = Binder.clearCallingIdentity();
792                try {
793                    int pkgUid = -1;
794                    try {
795                        ApplicationInfo appInfo = ActivityThread.getPackageManager()
796                                .getApplicationInfo(packageName, 0, UserHandle.getUserId(uid));
797                        if (appInfo != null) {
798                            pkgUid = appInfo.uid;
799                            isPrivileged = (appInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
800                        } else {
801                            if ("media".equals(packageName)) {
802                                pkgUid = Process.MEDIA_UID;
803                                isPrivileged = false;
804                            }
805                        }
806                    } catch (RemoteException e) {
807                        Slog.w(TAG, "Could not contact PackageManager", e);
808                    }
809                    if (pkgUid != uid) {
810                        // Oops!  The package name is not valid for the uid they are calling
811                        // under.  Abort.
812                        Slog.w(TAG, "Bad call: specified package " + packageName
813                                + " under uid " + uid + " but it is really " + pkgUid);
814                        return null;
815                    }
816                } finally {
817                    Binder.restoreCallingIdentity(ident);
818                }
819            }
820            ops = new Ops(packageName, uid, isPrivileged);
821            pkgOps.put(packageName, ops);
822        }
823        return ops;
824    }
825
826    private void scheduleWriteLocked() {
827        if (!mWriteScheduled) {
828            mWriteScheduled = true;
829            mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
830        }
831    }
832
833    private void scheduleWriteNowLocked() {
834        if (!mWriteScheduled) {
835            mWriteScheduled = true;
836        }
837        mHandler.removeCallbacks(mWriteRunner);
838        mHandler.post(mWriteRunner);
839    }
840
841    private Op getOpLocked(int code, int uid, String packageName, boolean edit) {
842        Ops ops = getOpsLocked(uid, packageName, edit);
843        if (ops == null) {
844            return null;
845        }
846        return getOpLocked(ops, code, edit);
847    }
848
849    private Op getOpLocked(Ops ops, int code, boolean edit) {
850        Op op = ops.get(code);
851        if (op == null) {
852            if (!edit) {
853                return null;
854            }
855            op = new Op(ops.uid, ops.packageName, code);
856            ops.put(code, op);
857        }
858        if (edit) {
859            scheduleWriteLocked();
860        }
861        return op;
862    }
863
864    private boolean isOpRestricted(int uid, int code, String packageName) {
865        int userHandle = UserHandle.getUserId(uid);
866        boolean[] opRestrictions = mOpRestrictions.get(userHandle);
867        if ((opRestrictions != null) && opRestrictions[code]) {
868            if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
869                synchronized (this) {
870                    Ops ops = getOpsLocked(uid, packageName, true);
871                    if ((ops != null) && ops.isPrivileged) {
872                        return false;
873                    }
874                }
875            }
876            if (userHandle == UserHandle.USER_OWNER) {
877                if (uid != mDeviceOwnerUid) {
878                    return true;
879                }
880            } else {
881                if (uid != mProfileOwnerUids.get(userHandle, -1)) {
882                    return true;
883                }
884            }
885        }
886        return false;
887    }
888
889    void readState() {
890        synchronized (mFile) {
891            synchronized (this) {
892                FileInputStream stream;
893                try {
894                    stream = mFile.openRead();
895                } catch (FileNotFoundException e) {
896                    Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
897                    return;
898                }
899                boolean success = false;
900                try {
901                    XmlPullParser parser = Xml.newPullParser();
902                    parser.setInput(stream, null);
903                    int type;
904                    while ((type = parser.next()) != XmlPullParser.START_TAG
905                            && type != XmlPullParser.END_DOCUMENT) {
906                        ;
907                    }
908
909                    if (type != XmlPullParser.START_TAG) {
910                        throw new IllegalStateException("no start tag found");
911                    }
912
913                    int outerDepth = parser.getDepth();
914                    while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
915                            && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
916                        if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
917                            continue;
918                        }
919
920                        String tagName = parser.getName();
921                        if (tagName.equals("pkg")) {
922                            readPackage(parser);
923                        } else {
924                            Slog.w(TAG, "Unknown element under <app-ops>: "
925                                    + parser.getName());
926                            XmlUtils.skipCurrentTag(parser);
927                        }
928                    }
929                    success = true;
930                } catch (IllegalStateException e) {
931                    Slog.w(TAG, "Failed parsing " + e);
932                } catch (NullPointerException e) {
933                    Slog.w(TAG, "Failed parsing " + e);
934                } catch (NumberFormatException e) {
935                    Slog.w(TAG, "Failed parsing " + e);
936                } catch (XmlPullParserException e) {
937                    Slog.w(TAG, "Failed parsing " + e);
938                } catch (IOException e) {
939                    Slog.w(TAG, "Failed parsing " + e);
940                } catch (IndexOutOfBoundsException e) {
941                    Slog.w(TAG, "Failed parsing " + e);
942                } finally {
943                    if (!success) {
944                        mUidOps.clear();
945                    }
946                    try {
947                        stream.close();
948                    } catch (IOException e) {
949                    }
950                }
951            }
952        }
953    }
954
955    void readPackage(XmlPullParser parser) throws NumberFormatException,
956            XmlPullParserException, IOException {
957        String pkgName = parser.getAttributeValue(null, "n");
958        int outerDepth = parser.getDepth();
959        int type;
960        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
961                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
962            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
963                continue;
964            }
965
966            String tagName = parser.getName();
967            if (tagName.equals("uid")) {
968                readUid(parser, pkgName);
969            } else {
970                Slog.w(TAG, "Unknown element under <pkg>: "
971                        + parser.getName());
972                XmlUtils.skipCurrentTag(parser);
973            }
974        }
975    }
976
977    void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
978            XmlPullParserException, IOException {
979        int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
980        String isPrivilegedString = parser.getAttributeValue(null, "p");
981        boolean isPrivileged = false;
982        if (isPrivilegedString == null) {
983            try {
984                IPackageManager packageManager = ActivityThread.getPackageManager();
985                if (packageManager != null) {
986                    ApplicationInfo appInfo = ActivityThread.getPackageManager()
987                            .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
988                    if (appInfo != null) {
989                        isPrivileged = (appInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
990                    }
991                } else {
992                    // Could not load data, don't add to cache so it will be loaded later.
993                    return;
994                }
995            } catch (RemoteException e) {
996                Slog.w(TAG, "Could not contact PackageManager", e);
997            }
998        } else {
999            isPrivileged = Boolean.parseBoolean(isPrivilegedString);
1000        }
1001        int outerDepth = parser.getDepth();
1002        int type;
1003        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1004                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1005            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1006                continue;
1007            }
1008
1009            String tagName = parser.getName();
1010            if (tagName.equals("op")) {
1011                Op op = new Op(uid, pkgName, Integer.parseInt(parser.getAttributeValue(null, "n")));
1012                String mode = parser.getAttributeValue(null, "m");
1013                if (mode != null) {
1014                    op.mode = Integer.parseInt(mode);
1015                }
1016                String time = parser.getAttributeValue(null, "t");
1017                if (time != null) {
1018                    op.time = Long.parseLong(time);
1019                }
1020                time = parser.getAttributeValue(null, "r");
1021                if (time != null) {
1022                    op.rejectTime = Long.parseLong(time);
1023                }
1024                String dur = parser.getAttributeValue(null, "d");
1025                if (dur != null) {
1026                    op.duration = Integer.parseInt(dur);
1027                }
1028                HashMap<String, Ops> pkgOps = mUidOps.get(uid);
1029                if (pkgOps == null) {
1030                    pkgOps = new HashMap<String, Ops>();
1031                    mUidOps.put(uid, pkgOps);
1032                }
1033                Ops ops = pkgOps.get(pkgName);
1034                if (ops == null) {
1035                    ops = new Ops(pkgName, uid, isPrivileged);
1036                    pkgOps.put(pkgName, ops);
1037                }
1038                ops.put(op.op, op);
1039            } else {
1040                Slog.w(TAG, "Unknown element under <pkg>: "
1041                        + parser.getName());
1042                XmlUtils.skipCurrentTag(parser);
1043            }
1044        }
1045    }
1046
1047    void writeState() {
1048        synchronized (mFile) {
1049            List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
1050
1051            FileOutputStream stream;
1052            try {
1053                stream = mFile.startWrite();
1054            } catch (IOException e) {
1055                Slog.w(TAG, "Failed to write state: " + e);
1056                return;
1057            }
1058
1059            try {
1060                XmlSerializer out = new FastXmlSerializer();
1061                out.setOutput(stream, "utf-8");
1062                out.startDocument(null, true);
1063                out.startTag(null, "app-ops");
1064
1065                if (allOps != null) {
1066                    String lastPkg = null;
1067                    for (int i=0; i<allOps.size(); i++) {
1068                        AppOpsManager.PackageOps pkg = allOps.get(i);
1069                        if (!pkg.getPackageName().equals(lastPkg)) {
1070                            if (lastPkg != null) {
1071                                out.endTag(null, "pkg");
1072                            }
1073                            lastPkg = pkg.getPackageName();
1074                            out.startTag(null, "pkg");
1075                            out.attribute(null, "n", lastPkg);
1076                        }
1077                        out.startTag(null, "uid");
1078                        out.attribute(null, "n", Integer.toString(pkg.getUid()));
1079                        synchronized (this) {
1080                            Ops ops = getOpsLocked(pkg.getUid(), pkg.getPackageName(), false);
1081                            // Should always be present as the list of PackageOps is generated
1082                            // from Ops.
1083                            if (ops != null) {
1084                                out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
1085                            } else {
1086                                out.attribute(null, "p", Boolean.toString(false));
1087                            }
1088                        }
1089                        List<AppOpsManager.OpEntry> ops = pkg.getOps();
1090                        for (int j=0; j<ops.size(); j++) {
1091                            AppOpsManager.OpEntry op = ops.get(j);
1092                            out.startTag(null, "op");
1093                            out.attribute(null, "n", Integer.toString(op.getOp()));
1094                            if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
1095                                out.attribute(null, "m", Integer.toString(op.getMode()));
1096                            }
1097                            long time = op.getTime();
1098                            if (time != 0) {
1099                                out.attribute(null, "t", Long.toString(time));
1100                            }
1101                            time = op.getRejectTime();
1102                            if (time != 0) {
1103                                out.attribute(null, "r", Long.toString(time));
1104                            }
1105                            int dur = op.getDuration();
1106                            if (dur != 0) {
1107                                out.attribute(null, "d", Integer.toString(dur));
1108                            }
1109                            out.endTag(null, "op");
1110                        }
1111                        out.endTag(null, "uid");
1112                    }
1113                    if (lastPkg != null) {
1114                        out.endTag(null, "pkg");
1115                    }
1116                }
1117
1118                out.endTag(null, "app-ops");
1119                out.endDocument();
1120                mFile.finishWrite(stream);
1121            } catch (IOException e) {
1122                Slog.w(TAG, "Failed to write state, restoring backup.", e);
1123                mFile.failWrite(stream);
1124            }
1125        }
1126    }
1127
1128    @Override
1129    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1130        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1131                != PackageManager.PERMISSION_GRANTED) {
1132            pw.println("Permission Denial: can't dump ApOps service from from pid="
1133                    + Binder.getCallingPid()
1134                    + ", uid=" + Binder.getCallingUid());
1135            return;
1136        }
1137
1138        synchronized (this) {
1139            pw.println("Current AppOps Service state:");
1140            final long now = System.currentTimeMillis();
1141            boolean needSep = false;
1142            if (mOpModeWatchers.size() > 0) {
1143                needSep = true;
1144                pw.println("  Op mode watchers:");
1145                for (int i=0; i<mOpModeWatchers.size(); i++) {
1146                    pw.print("    Op "); pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
1147                    pw.println(":");
1148                    ArrayList<Callback> callbacks = mOpModeWatchers.valueAt(i);
1149                    for (int j=0; j<callbacks.size(); j++) {
1150                        pw.print("      #"); pw.print(j); pw.print(": ");
1151                        pw.println(callbacks.get(j));
1152                    }
1153                }
1154            }
1155            if (mPackageModeWatchers.size() > 0) {
1156                needSep = true;
1157                pw.println("  Package mode watchers:");
1158                for (int i=0; i<mPackageModeWatchers.size(); i++) {
1159                    pw.print("    Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
1160                    pw.println(":");
1161                    ArrayList<Callback> callbacks = mPackageModeWatchers.valueAt(i);
1162                    for (int j=0; j<callbacks.size(); j++) {
1163                        pw.print("      #"); pw.print(j); pw.print(": ");
1164                        pw.println(callbacks.get(j));
1165                    }
1166                }
1167            }
1168            if (mModeWatchers.size() > 0) {
1169                needSep = true;
1170                pw.println("  All mode watchers:");
1171                for (int i=0; i<mModeWatchers.size(); i++) {
1172                    pw.print("    "); pw.print(mModeWatchers.keyAt(i));
1173                    pw.print(" -> "); pw.println(mModeWatchers.valueAt(i));
1174                }
1175            }
1176            if (mClients.size() > 0) {
1177                needSep = true;
1178                pw.println("  Clients:");
1179                for (int i=0; i<mClients.size(); i++) {
1180                    pw.print("    "); pw.print(mClients.keyAt(i)); pw.println(":");
1181                    ClientState cs = mClients.valueAt(i);
1182                    pw.print("      "); pw.println(cs);
1183                    if (cs.mStartedOps != null && cs.mStartedOps.size() > 0) {
1184                        pw.println("      Started ops:");
1185                        for (int j=0; j<cs.mStartedOps.size(); j++) {
1186                            Op op = cs.mStartedOps.get(j);
1187                            pw.print("        "); pw.print("uid="); pw.print(op.uid);
1188                            pw.print(" pkg="); pw.print(op.packageName);
1189                            pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
1190                        }
1191                    }
1192                }
1193            }
1194            if (mAudioRestrictions.size() > 0) {
1195                boolean printedHeader = false;
1196                for (int o=0; o<mAudioRestrictions.size(); o++) {
1197                    final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
1198                    final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
1199                    for (int i=0; i<restrictions.size(); i++) {
1200                        if (!printedHeader){
1201                            pw.println("  Audio Restrictions:");
1202                            printedHeader = true;
1203                            needSep = true;
1204                        }
1205                        final int usage = restrictions.keyAt(i);
1206                        pw.print("    "); pw.print(op);
1207                        pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
1208                        Restriction r = restrictions.valueAt(i);
1209                        pw.print(": mode="); pw.println(r.mode);
1210                        if (!r.exceptionPackages.isEmpty()) {
1211                            pw.println("      Exceptions:");
1212                            for (int j=0; j<r.exceptionPackages.size(); j++) {
1213                                pw.print("        "); pw.println(r.exceptionPackages.valueAt(j));
1214                            }
1215                        }
1216                    }
1217                }
1218            }
1219            if (needSep) {
1220                pw.println();
1221            }
1222            for (int i=0; i<mUidOps.size(); i++) {
1223                pw.print("  Uid "); UserHandle.formatUid(pw, mUidOps.keyAt(i)); pw.println(":");
1224                HashMap<String, Ops> pkgOps = mUidOps.valueAt(i);
1225                for (Ops ops : pkgOps.values()) {
1226                    pw.print("    Package "); pw.print(ops.packageName); pw.println(":");
1227                    for (int j=0; j<ops.size(); j++) {
1228                        Op op = ops.valueAt(j);
1229                        pw.print("      "); pw.print(AppOpsManager.opToName(op.op));
1230                        pw.print(": mode="); pw.print(op.mode);
1231                        if (op.time != 0) {
1232                            pw.print("; time="); TimeUtils.formatDuration(now-op.time, pw);
1233                            pw.print(" ago");
1234                        }
1235                        if (op.rejectTime != 0) {
1236                            pw.print("; rejectTime="); TimeUtils.formatDuration(now-op.rejectTime, pw);
1237                            pw.print(" ago");
1238                        }
1239                        if (op.duration == -1) {
1240                            pw.println(" (running)");
1241                        } else {
1242                            pw.print("; duration=");
1243                                    TimeUtils.formatDuration(op.duration, pw);
1244                                    pw.println();
1245                        }
1246                    }
1247                }
1248            }
1249        }
1250    }
1251
1252    private static final class Restriction {
1253        private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
1254        int mode;
1255        ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
1256    }
1257
1258    @Override
1259    public void setDeviceOwner(String packageName) throws RemoteException {
1260        checkSystemUid("setDeviceOwner");
1261        try {
1262            mDeviceOwnerUid = mContext.getPackageManager().getPackageUid(packageName,
1263                    UserHandle.USER_OWNER);
1264        } catch (NameNotFoundException e) {
1265            Log.e(TAG, "Could not find Device Owner UID");
1266            mDeviceOwnerUid = -1;
1267            throw new IllegalArgumentException("Could not find device owner package "
1268                    + packageName);
1269        }
1270    }
1271
1272    @Override
1273    public void setProfileOwner(String packageName, int userHandle) throws RemoteException {
1274        checkSystemUid("setProfileOwner");
1275        try {
1276            int uid = mContext.getPackageManager().getPackageUid(packageName,
1277                    userHandle);
1278            mProfileOwnerUids.put(userHandle, uid);
1279        } catch (NameNotFoundException e) {
1280            Log.e(TAG, "Could not find Profile Owner UID");
1281            mProfileOwnerUids.put(userHandle, -1);
1282            throw new IllegalArgumentException("Could not find profile owner package "
1283                    + packageName);
1284        }
1285    }
1286
1287    @Override
1288    public void setUserRestrictions(Bundle restrictions, int userHandle) throws RemoteException {
1289        checkSystemUid("setUserRestrictions");
1290        boolean[] opRestrictions = mOpRestrictions.get(userHandle);
1291        if (opRestrictions == null) {
1292            opRestrictions = new boolean[AppOpsManager._NUM_OP];
1293            mOpRestrictions.put(userHandle, opRestrictions);
1294        }
1295        for (int i = 0; i < opRestrictions.length; ++i) {
1296            String restriction = AppOpsManager.opToRestriction(i);
1297            if (restriction != null) {
1298                opRestrictions[i] = restrictions.getBoolean(restriction, false);
1299            } else {
1300                opRestrictions[i] = false;
1301            }
1302        }
1303    }
1304
1305    @Override
1306    public void removeUser(int userHandle) throws RemoteException {
1307        checkSystemUid("removeUser");
1308        mOpRestrictions.remove(userHandle);
1309        final int index = mProfileOwnerUids.indexOfKey(userHandle);
1310        if (index >= 0) {
1311            mProfileOwnerUids.removeAt(index);
1312        }
1313    }
1314
1315    private void checkSystemUid(String function) {
1316        int uid = Binder.getCallingUid();
1317        if (uid != Process.SYSTEM_UID) {
1318            throw new SecurityException(function + " must by called by the system");
1319        }
1320    }
1321
1322}
1323