blob: 61b1dcc3177ca353ed18facea7a18aaf970fce95 [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
Philip P. Moltmanne683f192017-06-23 14:05:04 -070019import android.Manifest;
20import android.app.ActivityManager;
21import android.app.ActivityThread;
22import android.app.AppGlobals;
23import android.app.AppOpsManager;
Dianne Hackbornd5254412018-05-11 18:02:58 -070024import android.app.AppOpsManagerInternal;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070025import android.content.ContentResolver;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070026import android.content.Context;
27import android.content.pm.ApplicationInfo;
28import android.content.pm.IPackageManager;
29import android.content.pm.PackageManager;
30import android.content.pm.PackageManagerInternal;
31import android.content.pm.UserInfo;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070032import android.database.ContentObserver;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070033import android.media.AudioAttributes;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070034import android.net.Uri;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070035import android.os.AsyncTask;
36import android.os.Binder;
37import android.os.Bundle;
38import android.os.Handler;
39import android.os.IBinder;
40import android.os.Process;
41import android.os.RemoteException;
42import android.os.ResultReceiver;
43import android.os.ServiceManager;
44import android.os.ShellCallback;
45import android.os.ShellCommand;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -070046import android.os.SystemClock;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070047import android.os.UserHandle;
48import android.os.UserManager;
49import android.os.storage.StorageManagerInternal;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070050import android.provider.Settings;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070051import android.util.ArrayMap;
52import android.util.ArraySet;
53import android.util.AtomicFile;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070054import android.util.KeyValueListParser;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070055import android.util.Slog;
56import android.util.SparseArray;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -070057import android.util.SparseBooleanArray;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070058import android.util.SparseIntArray;
59import android.util.TimeUtils;
60import android.util.Xml;
61
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070062import com.android.internal.annotations.VisibleForTesting;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -080063import com.android.internal.app.IAppOpsActiveCallback;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070064import com.android.internal.app.IAppOpsCallback;
65import com.android.internal.app.IAppOpsService;
66import com.android.internal.os.Zygote;
67import com.android.internal.util.ArrayUtils;
68import com.android.internal.util.DumpUtils;
69import com.android.internal.util.FastXmlSerializer;
70import com.android.internal.util.Preconditions;
71import com.android.internal.util.XmlUtils;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -080072import com.android.internal.util.function.pooled.PooledLambda;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -050073
Philip P. Moltmanne683f192017-06-23 14:05:04 -070074import libcore.util.EmptyArray;
75
76import org.xmlpull.v1.XmlPullParser;
77import org.xmlpull.v1.XmlPullParserException;
78import org.xmlpull.v1.XmlSerializer;
79
Dianne Hackborna06de0f2012-12-11 16:34:47 -080080import java.io.File;
81import java.io.FileDescriptor;
Dianne Hackborn35654b62013-01-14 17:38:02 -080082import java.io.FileInputStream;
83import java.io.FileNotFoundException;
84import java.io.FileOutputStream;
85import java.io.IOException;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080086import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010087import java.nio.charset.StandardCharsets;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -070088import java.text.SimpleDateFormat;
Dianne Hackborn35654b62013-01-14 17:38:02 -080089import java.util.ArrayList;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -070090import java.util.Arrays;
Svetoslav215b44a2015-08-04 19:03:40 -070091import java.util.Collections;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -070092import java.util.Date;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080093import java.util.HashMap;
Dianne Hackbornc2293022013-02-06 23:14:49 -080094import java.util.Iterator;
Dianne Hackborn35654b62013-01-14 17:38:02 -080095import java.util.List;
Dianne Hackborn607b4142013-08-02 18:10:10 -070096import java.util.Map;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080097
Dianne Hackborne93ab412018-05-14 17:52:30 -070098import static android.app.AppOpsManager._NUM_UID_STATE;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -070099import static android.app.AppOpsManager.UID_STATE_BACKGROUND;
100import static android.app.AppOpsManager.UID_STATE_CACHED;
101import static android.app.AppOpsManager.UID_STATE_FOREGROUND;
102import static android.app.AppOpsManager.UID_STATE_FOREGROUND_SERVICE;
Dianne Hackborne93ab412018-05-14 17:52:30 -0700103import static android.app.AppOpsManager.UID_STATE_LAST_NON_RESTRICTED;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700104import static android.app.AppOpsManager.UID_STATE_PERSISTENT;
105import static android.app.AppOpsManager.UID_STATE_TOP;
106
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800107public class AppOpsService extends IAppOpsService.Stub {
108 static final String TAG = "AppOps";
Dianne Hackborn35654b62013-01-14 17:38:02 -0800109 static final boolean DEBUG = false;
110
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700111 private static final int NO_VERSION = -1;
112 /** Increment by one every time and add the corresponding upgrade logic in
113 * {@link #upgradeLocked(int)} below. The first version was 1 */
114 private static final int CURRENT_VERSION = 1;
115
Dianne Hackborn35654b62013-01-14 17:38:02 -0800116 // Write at most every 30 minutes.
117 static final long WRITE_DELAY = DEBUG ? 1000 : 30*60*1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800118
Svet Ganov3a95f832018-03-23 17:44:30 -0700119 // Constant meaning that any UID should be matched when dispatching callbacks
120 private static final int UID_ANY = -2;
121
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700122 // Map from process states to the uid states we track.
123 private static final int[] PROCESS_STATE_TO_UID_STATE = new int[] {
124 UID_STATE_PERSISTENT, // ActivityManager.PROCESS_STATE_PERSISTENT
125 UID_STATE_PERSISTENT, // ActivityManager.PROCESS_STATE_PERSISTENT_UI
126 UID_STATE_TOP, // ActivityManager.PROCESS_STATE_TOP
127 UID_STATE_FOREGROUND_SERVICE, // ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
128 UID_STATE_FOREGROUND, // ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
129 UID_STATE_FOREGROUND, // ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND
130 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND
131 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_TRANSIENT_BACKGROUND
132 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_BACKUP
133 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_SERVICE
134 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_RECEIVER
135 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_TOP_SLEEPING
136 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_HEAVY_WEIGHT
137 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_HOME
138 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_LAST_ACTIVITY
139 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY
140 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT
141 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_RECENT
142 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_EMPTY
143 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_NONEXISTENT
144 };
145
146 static final String[] UID_STATE_NAMES = new String[] {
147 "pers ", // UID_STATE_PERSISTENT
148 "top ", // UID_STATE_TOP
149 "fgsvc", // UID_STATE_FOREGROUND_SERVICE
150 "fg ", // UID_STATE_FOREGROUND
151 "bg ", // UID_STATE_BACKGROUND
152 "cch ", // UID_STATE_CACHED
153 };
154
155 static final String[] UID_STATE_TIME_ATTRS = new String[] {
156 "tp", // UID_STATE_PERSISTENT
157 "tt", // UID_STATE_TOP
158 "tfs", // UID_STATE_FOREGROUND_SERVICE
159 "tf", // UID_STATE_FOREGROUND
160 "tb", // UID_STATE_BACKGROUND
161 "tc", // UID_STATE_CACHED
162 };
163
164 static final String[] UID_STATE_REJECT_ATTRS = new String[] {
165 "rp", // UID_STATE_PERSISTENT
166 "rt", // UID_STATE_TOP
167 "rfs", // UID_STATE_FOREGROUND_SERVICE
168 "rf", // UID_STATE_FOREGROUND
169 "rb", // UID_STATE_BACKGROUND
170 "rc", // UID_STATE_CACHED
171 };
172
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800173 Context mContext;
174 final AtomicFile mFile;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800175 final Handler mHandler;
176
Dianne Hackbornd5254412018-05-11 18:02:58 -0700177 private final AppOpsManagerInternalImpl mAppOpsManagerInternal
178 = new AppOpsManagerInternalImpl();
179
Dianne Hackborn35654b62013-01-14 17:38:02 -0800180 boolean mWriteScheduled;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800181 boolean mFastWriteScheduled;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800182 final Runnable mWriteRunner = new Runnable() {
183 public void run() {
184 synchronized (AppOpsService.this) {
185 mWriteScheduled = false;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800186 mFastWriteScheduled = false;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800187 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
188 @Override protected Void doInBackground(Void... params) {
189 writeState();
190 return null;
191 }
192 };
193 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
194 }
195 }
196 };
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800197
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700198 @VisibleForTesting
199 final SparseArray<UidState> mUidStates = new SparseArray<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800200
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700201 long mLastUptime;
202
Ruben Brunk29931bc2016-03-11 00:24:26 -0800203 /*
204 * These are app op restrictions imposed per user from various parties.
Ruben Brunk29931bc2016-03-11 00:24:26 -0800205 */
Svetoslav Ganova8bbd762016-05-13 17:08:16 -0700206 private final ArrayMap<IBinder, ClientRestrictionState> mOpUserRestrictions = new ArrayMap<>();
Jason Monk62062992014-05-06 09:55:28 -0400207
Dianne Hackbornd5254412018-05-11 18:02:58 -0700208 SparseIntArray mProfileOwners;
209
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700210 /**
211 * All times are in milliseconds. These constants are kept synchronized with the system
212 * global Settings. Any access to this class or its fields should be done while
213 * holding the AppOpsService lock.
214 */
215 private final class Constants extends ContentObserver {
216 // Key names stored in the settings value.
Dianne Hackborne93ab412018-05-14 17:52:30 -0700217 private static final String KEY_TOP_STATE_SETTLE_TIME = "top_state_settle_time";
218 private static final String KEY_FG_SERVICE_STATE_SETTLE_TIME
219 = "fg_service_state_settle_time";
220 private static final String KEY_BG_STATE_SETTLE_TIME = "bg_state_settle_time";
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700221
222 /**
Dianne Hackborne93ab412018-05-14 17:52:30 -0700223 * How long we want for a drop in uid state from top to settle before applying it.
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700224 * @see Settings.Global#APP_OPS_CONSTANTS
Dianne Hackborne93ab412018-05-14 17:52:30 -0700225 * @see #KEY_TOP_STATE_SETTLE_TIME
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700226 */
Dianne Hackborne93ab412018-05-14 17:52:30 -0700227 public long TOP_STATE_SETTLE_TIME;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700228
Dianne Hackborne93ab412018-05-14 17:52:30 -0700229 /**
230 * How long we want for a drop in uid state from foreground to settle before applying it.
231 * @see Settings.Global#APP_OPS_CONSTANTS
232 * @see #KEY_FG_SERVICE_STATE_SETTLE_TIME
233 */
234 public long FG_SERVICE_STATE_SETTLE_TIME;
235
236 /**
237 * How long we want for a drop in uid state from background to settle before applying it.
238 * @see Settings.Global#APP_OPS_CONSTANTS
239 * @see #KEY_BG_STATE_SETTLE_TIME
240 */
241 public long BG_STATE_SETTLE_TIME;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700242
243 private final KeyValueListParser mParser = new KeyValueListParser(',');
244 private ContentResolver mResolver;
245
246 public Constants(Handler handler) {
247 super(handler);
248 updateConstants();
249 }
250
251 public void startMonitoring(ContentResolver resolver) {
252 mResolver = resolver;
253 mResolver.registerContentObserver(
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700254 Settings.Global.getUriFor(Settings.Global.APP_OPS_CONSTANTS),
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700255 false, this);
256 updateConstants();
257 }
258
259 @Override
260 public void onChange(boolean selfChange, Uri uri) {
261 updateConstants();
262 }
263
264 private void updateConstants() {
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700265 String value = mResolver != null ? Settings.Global.getString(mResolver,
266 Settings.Global.APP_OPS_CONSTANTS) : "";
267
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700268 synchronized (AppOpsService.this) {
269 try {
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700270 mParser.setString(value);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700271 } catch (IllegalArgumentException e) {
272 // Failed to parse the settings string, log this and move on
273 // with defaults.
274 Slog.e(TAG, "Bad app ops settings", e);
275 }
Dianne Hackborne93ab412018-05-14 17:52:30 -0700276 TOP_STATE_SETTLE_TIME = mParser.getDurationMillis(
277 KEY_TOP_STATE_SETTLE_TIME, 30 * 1000L);
278 FG_SERVICE_STATE_SETTLE_TIME = mParser.getDurationMillis(
279 KEY_FG_SERVICE_STATE_SETTLE_TIME, 10 * 1000L);
280 BG_STATE_SETTLE_TIME = mParser.getDurationMillis(
281 KEY_BG_STATE_SETTLE_TIME, 1 * 1000L);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700282 }
283 }
284
285 void dump(PrintWriter pw) {
286 pw.println(" Settings:");
287
Dianne Hackborne93ab412018-05-14 17:52:30 -0700288 pw.print(" "); pw.print(KEY_TOP_STATE_SETTLE_TIME); pw.print("=");
289 TimeUtils.formatDuration(TOP_STATE_SETTLE_TIME, pw);
290 pw.print(" "); pw.print(KEY_FG_SERVICE_STATE_SETTLE_TIME); pw.print("=");
291 TimeUtils.formatDuration(FG_SERVICE_STATE_SETTLE_TIME, pw);
292 pw.print(" "); pw.print(KEY_BG_STATE_SETTLE_TIME); pw.print("=");
293 TimeUtils.formatDuration(BG_STATE_SETTLE_TIME, pw);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700294 pw.println();
295 }
296 }
297
298 private final Constants mConstants;
299
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700300 @VisibleForTesting
301 static final class UidState {
Svet Ganov2af57082015-07-30 08:44:20 -0700302 public final int uid;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700303
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700304 public int state = UID_STATE_CACHED;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700305 public int pendingState = UID_STATE_CACHED;
306 public long pendingStateCommitTime;
307
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700308 public int startNesting;
Svet Ganov2af57082015-07-30 08:44:20 -0700309 public ArrayMap<String, Ops> pkgOps;
310 public SparseIntArray opModes;
311
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700312 // true indicates there is an interested observer, false there isn't but it has such an op
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700313 public SparseBooleanArray foregroundOps;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700314 public boolean hasForegroundWatchers;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700315
Svet Ganov2af57082015-07-30 08:44:20 -0700316 public UidState(int uid) {
317 this.uid = uid;
318 }
319
320 public void clear() {
321 pkgOps = null;
322 opModes = null;
323 }
324
325 public boolean isDefault() {
326 return (pkgOps == null || pkgOps.isEmpty())
327 && (opModes == null || opModes.size() <= 0);
328 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700329
330 int evalMode(int mode) {
331 if (mode == AppOpsManager.MODE_FOREGROUND) {
Dianne Hackborne93ab412018-05-14 17:52:30 -0700332 return state <= UID_STATE_LAST_NON_RESTRICTED
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700333 ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED;
334 }
335 return mode;
336 }
337
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700338 private void evalForegroundWatchers(int op, SparseArray<ArraySet<ModeCallback>> watchers,
339 SparseBooleanArray which) {
340 boolean curValue = which.get(op, false);
341 ArraySet<ModeCallback> callbacks = watchers.get(op);
342 if (callbacks != null) {
343 for (int cbi = callbacks.size() - 1; !curValue && cbi >= 0; cbi--) {
344 if ((callbacks.valueAt(cbi).mFlags
345 & AppOpsManager.WATCH_FOREGROUND_CHANGES) != 0) {
346 hasForegroundWatchers = true;
347 curValue = true;
348 }
349 }
350 }
351 which.put(op, curValue);
352 }
353
354 public void evalForegroundOps(SparseArray<ArraySet<ModeCallback>> watchers) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700355 SparseBooleanArray which = null;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700356 hasForegroundWatchers = false;
357 if (opModes != null) {
358 for (int i = opModes.size() - 1; i >= 0; i--) {
359 if (opModes.valueAt(i) == AppOpsManager.MODE_FOREGROUND) {
360 if (which == null) {
361 which = new SparseBooleanArray();
362 }
363 evalForegroundWatchers(opModes.keyAt(i), watchers, which);
364 }
365 }
366 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700367 if (pkgOps != null) {
368 for (int i = pkgOps.size() - 1; i >= 0; i--) {
369 Ops ops = pkgOps.valueAt(i);
370 for (int j = ops.size() - 1; j >= 0; j--) {
371 if (ops.valueAt(j).mode == AppOpsManager.MODE_FOREGROUND) {
372 if (which == null) {
373 which = new SparseBooleanArray();
374 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700375 evalForegroundWatchers(ops.keyAt(j), watchers, which);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700376 }
377 }
378 }
379 }
380 foregroundOps = which;
381 }
Svet Ganov2af57082015-07-30 08:44:20 -0700382 }
383
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700384 final static class Ops extends SparseArray<Op> {
385 final String packageName;
386 final UidState uidState;
387 final boolean isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800388
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700389 Ops(String _packageName, UidState _uidState, boolean _isPrivileged) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800390 packageName = _packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700391 uidState = _uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400392 isPrivileged = _isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800393 }
394 }
395
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700396 final static class Op {
397 final UidState uidState;
398 final int uid;
399 final String packageName;
400 final int op;
401 int proxyUid = -1;
402 String proxyPackageName;
403 int mode;
404 int duration;
405 long time[] = new long[_NUM_UID_STATE];
406 long rejectTime[] = new long[_NUM_UID_STATE];
407 int startNesting;
408 long startRealtime;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800409
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700410 Op(UidState _uidState, String _packageName, int _op) {
411 uidState = _uidState;
412 uid = _uidState.uid;
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700413 packageName = _packageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800414 op = _op;
David Braunf5d83192013-09-16 13:43:51 -0700415 mode = AppOpsManager.opToDefaultMode(op);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800416 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700417
418 boolean hasAnyTime() {
419 for (int i = 0; i < AppOpsManager._NUM_UID_STATE; i++) {
420 if (time[i] != 0) {
421 return true;
422 }
423 if (rejectTime[i] != 0) {
424 return true;
425 }
426 }
427 return false;
428 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700429
430 int getMode() {
431 return uidState.evalMode(mode);
432 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800433 }
434
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800435 final SparseArray<ArraySet<ModeCallback>> mOpModeWatchers = new SparseArray<>();
436 final ArrayMap<String, ArraySet<ModeCallback>> mPackageModeWatchers = new ArrayMap<>();
437 final ArrayMap<IBinder, ModeCallback> mModeWatchers = new ArrayMap<>();
438 final ArrayMap<IBinder, SparseArray<ActiveCallback>> mActiveWatchers = new ArrayMap<>();
Dianne Hackborn68d76552017-02-27 15:32:03 -0800439 final SparseArray<SparseArray<Restriction>> mAudioRestrictions = new SparseArray<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800440
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700441 final class ModeCallback implements DeathRecipient {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800442 final IAppOpsCallback mCallback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700443 final int mWatchingUid;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700444 final int mFlags;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700445 final int mCallingUid;
446 final int mCallingPid;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800447
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700448 ModeCallback(IAppOpsCallback callback, int watchingUid, int flags, int callingUid,
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700449 int callingPid) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800450 mCallback = callback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700451 mWatchingUid = watchingUid;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700452 mFlags = flags;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700453 mCallingUid = callingUid;
454 mCallingPid = callingPid;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800455 try {
456 mCallback.asBinder().linkToDeath(this, 0);
457 } catch (RemoteException e) {
458 }
459 }
460
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700461 public boolean isWatchingUid(int uid) {
462 return uid == UID_ANY || mWatchingUid < 0 || mWatchingUid == uid;
463 }
464
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700465 @Override
466 public String toString() {
467 StringBuilder sb = new StringBuilder(128);
468 sb.append("ModeCallback{");
469 sb.append(Integer.toHexString(System.identityHashCode(this)));
470 sb.append(" watchinguid=");
471 UserHandle.formatUid(sb, mWatchingUid);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700472 sb.append(" flags=0x");
473 sb.append(Integer.toHexString(mFlags));
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700474 sb.append(" from uid=");
475 UserHandle.formatUid(sb, mCallingUid);
476 sb.append(" pid=");
477 sb.append(mCallingPid);
478 sb.append('}');
479 return sb.toString();
480 }
481
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700482 void unlinkToDeath() {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800483 mCallback.asBinder().unlinkToDeath(this, 0);
484 }
485
486 @Override
487 public void binderDied() {
488 stopWatchingMode(mCallback);
489 }
490 }
491
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700492 final class ActiveCallback implements DeathRecipient {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800493 final IAppOpsActiveCallback mCallback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700494 final int mWatchingUid;
495 final int mCallingUid;
496 final int mCallingPid;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800497
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700498 ActiveCallback(IAppOpsActiveCallback callback, int watchingUid, int callingUid,
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700499 int callingPid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800500 mCallback = callback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700501 mWatchingUid = watchingUid;
502 mCallingUid = callingUid;
503 mCallingPid = callingPid;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800504 try {
505 mCallback.asBinder().linkToDeath(this, 0);
506 } catch (RemoteException e) {
507 }
508 }
509
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700510 @Override
511 public String toString() {
512 StringBuilder sb = new StringBuilder(128);
513 sb.append("ActiveCallback{");
514 sb.append(Integer.toHexString(System.identityHashCode(this)));
515 sb.append(" watchinguid=");
516 UserHandle.formatUid(sb, mWatchingUid);
517 sb.append(" from uid=");
518 UserHandle.formatUid(sb, mCallingUid);
519 sb.append(" pid=");
520 sb.append(mCallingPid);
521 sb.append('}');
522 return sb.toString();
523 }
524
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700525 void destroy() {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800526 mCallback.asBinder().unlinkToDeath(this, 0);
527 }
528
529 @Override
530 public void binderDied() {
531 stopWatchingActive(mCallback);
532 }
533 }
534
Svet Ganova7a0db62018-02-27 20:08:01 -0800535 final ArrayMap<IBinder, ClientState> mClients = new ArrayMap<>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700536
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700537 final class ClientState extends Binder implements DeathRecipient {
Svet Ganovf7b47252018-02-26 11:11:27 -0800538 final ArrayList<Op> mStartedOps = new ArrayList<>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700539 final IBinder mAppToken;
540 final int mPid;
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700541
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700542 ClientState(IBinder appToken) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700543 mAppToken = appToken;
544 mPid = Binder.getCallingPid();
Svet Ganovf7b47252018-02-26 11:11:27 -0800545 // Watch only for remote processes dying
546 if (!(appToken instanceof Binder)) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700547 try {
548 mAppToken.linkToDeath(this, 0);
549 } catch (RemoteException e) {
Svet Ganovf7b47252018-02-26 11:11:27 -0800550 /* do nothing */
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700551 }
552 }
553 }
554
555 @Override
556 public String toString() {
557 return "ClientState{" +
558 "mAppToken=" + mAppToken +
Svet Ganovf7b47252018-02-26 11:11:27 -0800559 ", " + "pid=" + mPid +
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700560 '}';
561 }
562
563 @Override
564 public void binderDied() {
565 synchronized (AppOpsService.this) {
566 for (int i=mStartedOps.size()-1; i>=0; i--) {
Svet Ganova7a0db62018-02-27 20:08:01 -0800567 finishOperationLocked(mStartedOps.get(i), /*finishNested*/ true);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700568 }
569 mClients.remove(mAppToken);
570 }
571 }
572 }
573
Jeff Brown6f357d32014-01-15 20:40:55 -0800574 public AppOpsService(File storagePath, Handler handler) {
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600575 LockGuard.installLock(this, LockGuard.INDEX_APP_OPS);
Dianne Hackborne17b4452018-01-10 13:15:40 -0800576 mFile = new AtomicFile(storagePath, "appops");
Jeff Brown6f357d32014-01-15 20:40:55 -0800577 mHandler = handler;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700578 mConstants = new Constants(mHandler);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800579 readState();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800580 }
David Braunf5d83192013-09-16 13:43:51 -0700581
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800582 public void publish(Context context) {
583 mContext = context;
584 ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
Dianne Hackbornd5254412018-05-11 18:02:58 -0700585 LocalServices.addService(AppOpsManagerInternal.class, mAppOpsManagerInternal);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800586 }
587
Dianne Hackborn514074f2013-02-11 10:52:46 -0800588 public void systemReady() {
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700589 mConstants.startMonitoring(mContext.getContentResolver());
590
Dianne Hackborn514074f2013-02-11 10:52:46 -0800591 synchronized (this) {
592 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700593 for (int i = mUidStates.size() - 1; i >= 0; i--) {
594 UidState uidState = mUidStates.valueAt(i);
595
596 String[] packageNames = getPackagesForUid(uidState.uid);
597 if (ArrayUtils.isEmpty(packageNames)) {
598 uidState.clear();
599 mUidStates.removeAt(i);
600 changed = true;
601 continue;
602 }
603
604 ArrayMap<String, Ops> pkgs = uidState.pkgOps;
605 if (pkgs == null) {
606 continue;
607 }
608
Dianne Hackborn514074f2013-02-11 10:52:46 -0800609 Iterator<Ops> it = pkgs.values().iterator();
610 while (it.hasNext()) {
611 Ops ops = it.next();
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700612 int curUid = -1;
Dianne Hackborn514074f2013-02-11 10:52:46 -0800613 try {
Jeff Sharkeycd654482016-01-08 17:42:11 -0700614 curUid = AppGlobals.getPackageManager().getPackageUid(ops.packageName,
615 PackageManager.MATCH_UNINSTALLED_PACKAGES,
Svet Ganov2af57082015-07-30 08:44:20 -0700616 UserHandle.getUserId(ops.uidState.uid));
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700617 } catch (RemoteException ignored) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800618 }
Svet Ganov2af57082015-07-30 08:44:20 -0700619 if (curUid != ops.uidState.uid) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800620 Slog.i(TAG, "Pruning old package " + ops.packageName
Svet Ganov2af57082015-07-30 08:44:20 -0700621 + "/" + ops.uidState + ": new uid=" + curUid);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800622 it.remove();
623 changed = true;
624 }
625 }
Svet Ganov2af57082015-07-30 08:44:20 -0700626
627 if (uidState.isDefault()) {
628 mUidStates.removeAt(i);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800629 }
630 }
631 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800632 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800633 }
634 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700635
Suprabh Shuklaaef25132017-01-23 18:09:03 -0800636 PackageManagerInternal packageManagerInternal = LocalServices.getService(
637 PackageManagerInternal.class);
638 packageManagerInternal.setExternalSourcesPolicy(
639 new PackageManagerInternal.ExternalSourcesPolicy() {
640 @Override
641 public int getPackageTrustedToInstallApps(String packageName, int uid) {
642 int appOpMode = checkOperation(AppOpsManager.OP_REQUEST_INSTALL_PACKAGES,
643 uid, packageName);
644 switch (appOpMode) {
645 case AppOpsManager.MODE_ALLOWED:
646 return PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
647 case AppOpsManager.MODE_ERRORED:
648 return PackageManagerInternal.ExternalSourcesPolicy.USER_BLOCKED;
649 default:
650 return PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT;
651 }
652 }
653 });
654
Sudheer Shanka2250d562016-11-07 15:41:02 -0800655 StorageManagerInternal storageManagerInternal = LocalServices.getService(
656 StorageManagerInternal.class);
657 storageManagerInternal.addExternalStoragePolicy(
658 new StorageManagerInternal.ExternalStorageMountPolicy() {
Svet Ganov6ee871e2015-07-10 14:29:33 -0700659 @Override
660 public int getMountMode(int uid, String packageName) {
661 if (Process.isIsolated(uid)) {
662 return Zygote.MOUNT_EXTERNAL_NONE;
663 }
664 if (noteOperation(AppOpsManager.OP_READ_EXTERNAL_STORAGE, uid,
665 packageName) != AppOpsManager.MODE_ALLOWED) {
666 return Zygote.MOUNT_EXTERNAL_NONE;
667 }
668 if (noteOperation(AppOpsManager.OP_WRITE_EXTERNAL_STORAGE, uid,
669 packageName) != AppOpsManager.MODE_ALLOWED) {
670 return Zygote.MOUNT_EXTERNAL_READ;
671 }
672 return Zygote.MOUNT_EXTERNAL_WRITE;
673 }
674
675 @Override
676 public boolean hasExternalStorage(int uid, String packageName) {
677 final int mountMode = getMountMode(uid, packageName);
678 return mountMode == Zygote.MOUNT_EXTERNAL_READ
679 || mountMode == Zygote.MOUNT_EXTERNAL_WRITE;
680 }
681 });
Dianne Hackborn514074f2013-02-11 10:52:46 -0800682 }
683
684 public void packageRemoved(int uid, String packageName) {
685 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700686 UidState uidState = mUidStates.get(uid);
687 if (uidState == null) {
688 return;
689 }
690
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800691 Ops ops = null;
Svet Ganov2af57082015-07-30 08:44:20 -0700692
693 // Remove any package state if such.
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800694 if (uidState.pkgOps != null) {
695 ops = uidState.pkgOps.remove(packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700696 }
697
698 // If we just nuked the last package state check if the UID is valid.
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800699 if (ops != null && uidState.pkgOps.isEmpty()
Svet Ganov2af57082015-07-30 08:44:20 -0700700 && getPackagesForUid(uid).length <= 0) {
701 mUidStates.remove(uid);
702 }
703
Svet Ganova7a0db62018-02-27 20:08:01 -0800704 // Finish ops other packages started on behalf of the package.
705 final int clientCount = mClients.size();
706 for (int i = 0; i < clientCount; i++) {
707 final ClientState client = mClients.valueAt(i);
708 if (client.mStartedOps == null) {
709 continue;
710 }
711 final int opCount = client.mStartedOps.size();
712 for (int j = opCount - 1; j >= 0; j--) {
713 final Op op = client.mStartedOps.get(j);
714 if (uid == op.uid && packageName.equals(op.packageName)) {
715 finishOperationLocked(op, /*finishNested*/ true);
716 client.mStartedOps.remove(j);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700717 if (op.startNesting <= 0) {
Svet Ganova7a0db62018-02-27 20:08:01 -0800718 scheduleOpActiveChangedIfNeededLocked(op.op,
719 uid, packageName, false);
720 }
721 }
722 }
723 }
724
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800725 if (ops != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700726 scheduleFastWriteLocked();
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800727
728 final int opCount = ops.size();
729 for (int i = 0; i < opCount; i++) {
730 final Op op = ops.valueAt(i);
731 if (op.duration == -1) {
732 scheduleOpActiveChangedIfNeededLocked(
733 op.op, op.uid, op.packageName, false);
734 }
735 }
Dianne Hackborn514074f2013-02-11 10:52:46 -0800736 }
737 }
738 }
739
740 public void uidRemoved(int uid) {
741 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700742 if (mUidStates.indexOfKey(uid) >= 0) {
743 mUidStates.remove(uid);
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800744 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800745 }
746 }
747 }
748
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700749 public void updateUidProcState(int uid, int procState) {
750 synchronized (this) {
751 final UidState uidState = getUidStateLocked(uid, true);
752 final int newState = PROCESS_STATE_TO_UID_STATE[procState];
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700753 if (uidState != null && uidState.pendingState != newState) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700754 final int oldPendingState = uidState.pendingState;
755 uidState.pendingState = newState;
Dianne Hackborne93ab412018-05-14 17:52:30 -0700756 if (newState < uidState.state || newState <= UID_STATE_LAST_NON_RESTRICTED) {
757 // We are moving to a more important state, or the new state is in the
758 // foreground, then always do it immediately.
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700759 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700760 } else if (uidState.pendingStateCommitTime == 0) {
761 // We are moving to a less important state for the first time,
762 // delay the application for a bit.
Dianne Hackborne93ab412018-05-14 17:52:30 -0700763 final long settleTime;
764 if (uidState.state <= UID_STATE_TOP) {
765 settleTime = mConstants.TOP_STATE_SETTLE_TIME;
766 } else if (uidState.state <= UID_STATE_FOREGROUND_SERVICE) {
767 settleTime = mConstants.FG_SERVICE_STATE_SETTLE_TIME;
768 } else {
769 settleTime = mConstants.BG_STATE_SETTLE_TIME;
770 }
771 uidState.pendingStateCommitTime = SystemClock.uptimeMillis() + settleTime;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700772 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700773 if (uidState.startNesting != 0) {
774 // There is some actively running operation... need to find it
775 // and appropriately update its state.
776 final long now = System.currentTimeMillis();
777 for (int i = uidState.pkgOps.size() - 1; i >= 0; i--) {
778 final Ops ops = uidState.pkgOps.valueAt(i);
779 for (int j = ops.size() - 1; j >= 0; j--) {
780 final Op op = ops.valueAt(j);
781 if (op.startNesting > 0) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700782 op.time[oldPendingState] = now;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700783 op.time[newState] = now;
784 }
785 }
786 }
787 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700788 }
789 }
790 }
791
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800792 public void shutdown() {
793 Slog.w(TAG, "Writing app ops before shutdown...");
Dianne Hackborn35654b62013-01-14 17:38:02 -0800794 boolean doWrite = false;
795 synchronized (this) {
796 if (mWriteScheduled) {
797 mWriteScheduled = false;
798 doWrite = true;
799 }
800 }
801 if (doWrite) {
802 writeState();
803 }
804 }
805
Dianne Hackborn72e39832013-01-18 18:36:09 -0800806 private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
807 ArrayList<AppOpsManager.OpEntry> resOps = null;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700808 final long elapsedNow = SystemClock.elapsedRealtime();
Dianne Hackborn72e39832013-01-18 18:36:09 -0800809 if (ops == null) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700810 resOps = new ArrayList<>();
Dianne Hackborn72e39832013-01-18 18:36:09 -0800811 for (int j=0; j<pkgOps.size(); j++) {
812 Op curOp = pkgOps.valueAt(j);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700813 long duration = curOp.duration == -1
814 ? (elapsedNow - curOp.startRealtime)
815 : curOp.duration;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800816 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700817 curOp.rejectTime, (int) duration, curOp.proxyUid,
Svet Ganov99b60432015-06-27 13:15:22 -0700818 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800819 }
820 } else {
821 for (int j=0; j<ops.length; j++) {
822 Op curOp = pkgOps.get(ops[j]);
823 if (curOp != null) {
824 if (resOps == null) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700825 resOps = new ArrayList<>();
Dianne Hackborn72e39832013-01-18 18:36:09 -0800826 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700827 long duration = curOp.duration == -1
828 ? (elapsedNow - curOp.startRealtime)
829 : curOp.duration;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800830 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700831 curOp.rejectTime, (int) duration, curOp.proxyUid,
Svet Ganov99b60432015-06-27 13:15:22 -0700832 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800833 }
834 }
835 }
836 return resOps;
837 }
838
Dianne Hackbornc7214a32017-04-11 13:32:47 -0700839 private ArrayList<AppOpsManager.OpEntry> collectOps(SparseIntArray uidOps, int[] ops) {
840 ArrayList<AppOpsManager.OpEntry> resOps = null;
841 if (ops == null) {
842 resOps = new ArrayList<>();
843 for (int j=0; j<uidOps.size(); j++) {
844 resOps.add(new AppOpsManager.OpEntry(uidOps.keyAt(j), uidOps.valueAt(j),
845 0, 0, 0, -1, null));
846 }
847 } else {
848 for (int j=0; j<ops.length; j++) {
849 int index = uidOps.indexOfKey(ops[j]);
850 if (index >= 0) {
851 if (resOps == null) {
852 resOps = new ArrayList<>();
853 }
854 resOps.add(new AppOpsManager.OpEntry(uidOps.keyAt(index), uidOps.valueAt(index),
855 0, 0, 0, -1, null));
856 }
857 }
858 }
859 return resOps;
860 }
861
Dianne Hackborn35654b62013-01-14 17:38:02 -0800862 @Override
863 public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
864 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
865 Binder.getCallingPid(), Binder.getCallingUid(), null);
866 ArrayList<AppOpsManager.PackageOps> res = null;
867 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700868 final int uidStateCount = mUidStates.size();
869 for (int i = 0; i < uidStateCount; i++) {
870 UidState uidState = mUidStates.valueAt(i);
871 if (uidState.pkgOps == null || uidState.pkgOps.isEmpty()) {
872 continue;
873 }
874 ArrayMap<String, Ops> packages = uidState.pkgOps;
875 final int packageCount = packages.size();
876 for (int j = 0; j < packageCount; j++) {
877 Ops pkgOps = packages.valueAt(j);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800878 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800879 if (resOps != null) {
880 if (res == null) {
881 res = new ArrayList<AppOpsManager.PackageOps>();
882 }
883 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700884 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800885 res.add(resPackage);
886 }
887 }
888 }
889 }
890 return res;
891 }
892
893 @Override
Dianne Hackborn72e39832013-01-18 18:36:09 -0800894 public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
895 int[] ops) {
896 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
897 Binder.getCallingPid(), Binder.getCallingUid(), null);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000898 String resolvedPackageName = resolvePackageName(uid, packageName);
899 if (resolvedPackageName == null) {
900 return Collections.emptyList();
901 }
Dianne Hackborn72e39832013-01-18 18:36:09 -0800902 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -0700903 Ops pkgOps = getOpsRawLocked(uid, resolvedPackageName, false /* edit */,
904 false /* uidMismatchExpected */);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800905 if (pkgOps == null) {
906 return null;
907 }
908 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
909 if (resOps == null) {
910 return null;
911 }
912 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
913 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700914 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800915 res.add(resPackage);
916 return res;
917 }
918 }
919
Dianne Hackbornc7214a32017-04-11 13:32:47 -0700920 @Override
921 public List<AppOpsManager.PackageOps> getUidOps(int uid, int[] ops) {
922 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
923 Binder.getCallingPid(), Binder.getCallingUid(), null);
924 synchronized (this) {
925 UidState uidState = getUidStateLocked(uid, false);
926 if (uidState == null) {
927 return null;
928 }
929 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(uidState.opModes, ops);
930 if (resOps == null) {
931 return null;
932 }
933 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
934 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
935 null, uidState.uid, resOps);
936 res.add(resPackage);
937 return res;
938 }
939 }
940
Dianne Hackborn607b4142013-08-02 18:10:10 -0700941 private void pruneOp(Op op, int uid, String packageName) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700942 if (!op.hasAnyTime()) {
Yohei Yukawaa965d652017-10-12 15:02:26 -0700943 Ops ops = getOpsRawLocked(uid, packageName, false /* edit */,
944 false /* uidMismatchExpected */);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700945 if (ops != null) {
946 ops.remove(op.op);
947 if (ops.size() <= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -0700948 UidState uidState = ops.uidState;
949 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700950 if (pkgOps != null) {
951 pkgOps.remove(ops.packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700952 if (pkgOps.isEmpty()) {
953 uidState.pkgOps = null;
954 }
955 if (uidState.isDefault()) {
956 mUidStates.remove(uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -0700957 }
958 }
959 }
960 }
961 }
962 }
963
Dianne Hackbornd5254412018-05-11 18:02:58 -0700964 void enforceManageAppOpsModes(int callingPid, int callingUid, int targetUid) {
965 if (callingPid == Process.myPid()) {
966 return;
967 }
968 final int callingUser = UserHandle.getUserId(callingUid);
969 synchronized (this) {
970 if (mProfileOwners != null && mProfileOwners.get(callingUser, -1) == callingUid) {
971 if (targetUid >= 0 && callingUser == UserHandle.getUserId(targetUid)) {
972 // Profile owners are allowed to change modes but only for apps
973 // within their user.
974 return;
975 }
976 }
977 }
978 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
979 Binder.getCallingPid(), Binder.getCallingUid(), null);
980 }
981
Dianne Hackborn72e39832013-01-18 18:36:09 -0800982 @Override
Svet Ganov2af57082015-07-30 08:44:20 -0700983 public void setUidMode(int code, int uid, int mode) {
Dianne Hackbornd5254412018-05-11 18:02:58 -0700984 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
Svet Ganov2af57082015-07-30 08:44:20 -0700985 verifyIncomingOp(code);
986 code = AppOpsManager.opToSwitch(code);
987
988 synchronized (this) {
989 final int defaultMode = AppOpsManager.opToDefaultMode(code);
990
991 UidState uidState = getUidStateLocked(uid, false);
992 if (uidState == null) {
993 if (mode == defaultMode) {
994 return;
995 }
996 uidState = new UidState(uid);
997 uidState.opModes = new SparseIntArray();
998 uidState.opModes.put(code, mode);
999 mUidStates.put(uid, uidState);
1000 scheduleWriteLocked();
1001 } else if (uidState.opModes == null) {
1002 if (mode != defaultMode) {
1003 uidState.opModes = new SparseIntArray();
1004 uidState.opModes.put(code, mode);
1005 scheduleWriteLocked();
1006 }
1007 } else {
1008 if (uidState.opModes.get(code) == mode) {
1009 return;
1010 }
1011 if (mode == defaultMode) {
1012 uidState.opModes.delete(code);
1013 if (uidState.opModes.size() <= 0) {
1014 uidState.opModes = null;
1015 }
1016 } else {
1017 uidState.opModes.put(code, mode);
1018 }
1019 scheduleWriteLocked();
1020 }
1021 }
1022
Svetoslav215b44a2015-08-04 19:03:40 -07001023 String[] uidPackageNames = getPackagesForUid(uid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001024 ArrayMap<ModeCallback, ArraySet<String>> callbackSpecs = null;
Svet Ganov2af57082015-07-30 08:44:20 -07001025
riddle_hsu40b300f2015-11-23 13:22:03 +08001026 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001027 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001028 if (callbacks != null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001029 final int callbackCount = callbacks.size();
1030 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001031 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +08001032 ArraySet<String> changedPackages = new ArraySet<>();
1033 Collections.addAll(changedPackages, uidPackageNames);
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001034 if (callbackSpecs == null) {
1035 callbackSpecs = new ArrayMap<>();
1036 }
riddle_hsu40b300f2015-11-23 13:22:03 +08001037 callbackSpecs.put(callback, changedPackages);
1038 }
1039 }
1040
1041 for (String uidPackageName : uidPackageNames) {
1042 callbacks = mPackageModeWatchers.get(uidPackageName);
1043 if (callbacks != null) {
1044 if (callbackSpecs == null) {
1045 callbackSpecs = new ArrayMap<>();
Svet Ganov2af57082015-07-30 08:44:20 -07001046 }
riddle_hsu40b300f2015-11-23 13:22:03 +08001047 final int callbackCount = callbacks.size();
1048 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001049 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +08001050 ArraySet<String> changedPackages = callbackSpecs.get(callback);
1051 if (changedPackages == null) {
1052 changedPackages = new ArraySet<>();
1053 callbackSpecs.put(callback, changedPackages);
1054 }
1055 changedPackages.add(uidPackageName);
1056 }
Svet Ganov2af57082015-07-30 08:44:20 -07001057 }
1058 }
1059 }
1060
1061 if (callbackSpecs == null) {
1062 return;
1063 }
1064
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001065 for (int i = 0; i < callbackSpecs.size(); i++) {
1066 final ModeCallback callback = callbackSpecs.keyAt(i);
1067 final ArraySet<String> reportedPackageNames = callbackSpecs.valueAt(i);
1068 if (reportedPackageNames == null) {
1069 mHandler.sendMessage(PooledLambda.obtainMessage(
1070 AppOpsService::notifyOpChanged,
1071 this, callback, code, uid, (String) null));
1072
1073 } else {
1074 final int reportedPackageCount = reportedPackageNames.size();
1075 for (int j = 0; j < reportedPackageCount; j++) {
1076 final String reportedPackageName = reportedPackageNames.valueAt(j);
1077 mHandler.sendMessage(PooledLambda.obtainMessage(
1078 AppOpsService::notifyOpChanged,
1079 this, callback, code, uid, reportedPackageName));
Svet Ganov2af57082015-07-30 08:44:20 -07001080 }
1081 }
Svet Ganov2af57082015-07-30 08:44:20 -07001082 }
1083 }
1084
1085 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001086 public void setMode(int code, int uid, String packageName, int mode) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07001087 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001088 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001089 ArraySet<ModeCallback> repCbs = null;
Dianne Hackbornc2293022013-02-06 23:14:49 -08001090 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001091 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -07001092 UidState uidState = getUidStateLocked(uid, false);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001093 Op op = getOpLocked(code, uid, packageName, true);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001094 if (op != null) {
1095 if (op.mode != mode) {
1096 op.mode = mode;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001097 if (uidState != null) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001098 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001099 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001100 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001101 if (cbs != null) {
1102 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001103 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001104 }
1105 repCbs.addAll(cbs);
1106 }
1107 cbs = mPackageModeWatchers.get(packageName);
1108 if (cbs != null) {
1109 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001110 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001111 }
1112 repCbs.addAll(cbs);
1113 }
David Braunf5d83192013-09-16 13:43:51 -07001114 if (mode == AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001115 // If going into the default mode, prune this op
1116 // if there is nothing else interesting in it.
Dianne Hackborn607b4142013-08-02 18:10:10 -07001117 pruneOp(op, uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001118 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001119 scheduleFastWriteLocked();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001120 }
1121 }
1122 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001123 if (repCbs != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001124 mHandler.sendMessage(PooledLambda.obtainMessage(
1125 AppOpsService::notifyOpChanged,
1126 this, repCbs, code, uid, packageName));
Dianne Hackbornc2293022013-02-06 23:14:49 -08001127 }
1128 }
1129
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001130 private void notifyOpChanged(ArraySet<ModeCallback> callbacks, int code,
1131 int uid, String packageName) {
1132 for (int i = 0; i < callbacks.size(); i++) {
1133 final ModeCallback callback = callbacks.valueAt(i);
1134 notifyOpChanged(callback, code, uid, packageName);
1135 }
1136 }
1137
1138 private void notifyOpChanged(ModeCallback callback, int code,
1139 int uid, String packageName) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001140 if (uid != UID_ANY && callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001141 return;
1142 }
1143 // There are components watching for mode changes such as window manager
1144 // and location manager which are in our process. The callbacks in these
1145 // components may require permissions our remote caller does not have.
1146 final long identity = Binder.clearCallingIdentity();
1147 try {
1148 callback.mCallback.opChanged(code, uid, packageName);
1149 } catch (RemoteException e) {
1150 /* ignore */
1151 } finally {
1152 Binder.restoreCallingIdentity(identity);
1153 }
1154 }
1155
1156 private static HashMap<ModeCallback, ArrayList<ChangeRec>> addCallbacks(
1157 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks,
1158 int op, int uid, String packageName, ArraySet<ModeCallback> cbs) {
Dianne Hackborn607b4142013-08-02 18:10:10 -07001159 if (cbs == null) {
1160 return callbacks;
1161 }
1162 if (callbacks == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001163 callbacks = new HashMap<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001164 }
Svet Ganov2af57082015-07-30 08:44:20 -07001165 boolean duplicate = false;
Dianne Hackborn68d76552017-02-27 15:32:03 -08001166 final int N = cbs.size();
1167 for (int i=0; i<N; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001168 ModeCallback cb = cbs.valueAt(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001169 ArrayList<ChangeRec> reports = callbacks.get(cb);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001170 if (reports == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001171 reports = new ArrayList<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001172 callbacks.put(cb, reports);
Svet Ganov2af57082015-07-30 08:44:20 -07001173 } else {
1174 final int reportCount = reports.size();
1175 for (int j = 0; j < reportCount; j++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001176 ChangeRec report = reports.get(j);
1177 if (report.op == op && report.pkg.equals(packageName)) {
Svet Ganov2af57082015-07-30 08:44:20 -07001178 duplicate = true;
1179 break;
1180 }
1181 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001182 }
Svet Ganov2af57082015-07-30 08:44:20 -07001183 if (!duplicate) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001184 reports.add(new ChangeRec(op, uid, packageName));
Svet Ganov2af57082015-07-30 08:44:20 -07001185 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001186 }
1187 return callbacks;
1188 }
1189
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001190 static final class ChangeRec {
1191 final int op;
1192 final int uid;
1193 final String pkg;
1194
1195 ChangeRec(int _op, int _uid, String _pkg) {
1196 op = _op;
1197 uid = _uid;
1198 pkg = _pkg;
1199 }
1200 }
1201
Dianne Hackborn607b4142013-08-02 18:10:10 -07001202 @Override
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001203 public void resetAllModes(int reqUserId, String reqPackageName) {
1204 final int callingPid = Binder.getCallingPid();
1205 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001206 reqUserId = ActivityManager.handleIncomingUser(callingPid, callingUid, reqUserId,
1207 true, true, "resetAllModes", null);
Svet Ganov2af57082015-07-30 08:44:20 -07001208
1209 int reqUid = -1;
1210 if (reqPackageName != null) {
1211 try {
1212 reqUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -07001213 reqPackageName, PackageManager.MATCH_UNINSTALLED_PACKAGES, reqUserId);
Svet Ganov2af57082015-07-30 08:44:20 -07001214 } catch (RemoteException e) {
1215 /* ignore - local call */
1216 }
1217 }
1218
Dianne Hackbornd5254412018-05-11 18:02:58 -07001219 enforceManageAppOpsModes(callingPid, callingUid, reqUid);
1220
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001221 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks = null;
Dianne Hackborn607b4142013-08-02 18:10:10 -07001222 synchronized (this) {
1223 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -07001224 for (int i = mUidStates.size() - 1; i >= 0; i--) {
1225 UidState uidState = mUidStates.valueAt(i);
1226
1227 SparseIntArray opModes = uidState.opModes;
1228 if (opModes != null && (uidState.uid == reqUid || reqUid == -1)) {
1229 final int uidOpCount = opModes.size();
1230 for (int j = uidOpCount - 1; j >= 0; j--) {
1231 final int code = opModes.keyAt(j);
1232 if (AppOpsManager.opAllowsReset(code)) {
1233 opModes.removeAt(j);
1234 if (opModes.size() <= 0) {
1235 uidState.opModes = null;
1236 }
1237 for (String packageName : getPackagesForUid(uidState.uid)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001238 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -07001239 mOpModeWatchers.get(code));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001240 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -07001241 mPackageModeWatchers.get(packageName));
1242 }
1243 }
1244 }
1245 }
1246
1247 if (uidState.pkgOps == null) {
1248 continue;
1249 }
1250
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001251 if (reqUserId != UserHandle.USER_ALL
Svet Ganov2af57082015-07-30 08:44:20 -07001252 && reqUserId != UserHandle.getUserId(uidState.uid)) {
Alexandra Gherghinad6a98972014-08-04 17:05:34 +01001253 // Skip any ops for a different user
1254 continue;
1255 }
Svet Ganov2af57082015-07-30 08:44:20 -07001256
1257 Map<String, Ops> packages = uidState.pkgOps;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001258 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001259 boolean uidChanged = false;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001260 while (it.hasNext()) {
1261 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001262 String packageName = ent.getKey();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001263 if (reqPackageName != null && !reqPackageName.equals(packageName)) {
1264 // Skip any ops for a different package
1265 continue;
1266 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001267 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001268 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -07001269 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -07001270 if (AppOpsManager.opAllowsReset(curOp.op)
1271 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -07001272 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001273 changed = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001274 uidChanged = true;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001275 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -07001276 mOpModeWatchers.get(curOp.op));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001277 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -07001278 mPackageModeWatchers.get(packageName));
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001279 if (!curOp.hasAnyTime()) {
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001280 pkgOps.removeAt(j);
1281 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001282 }
1283 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001284 if (pkgOps.size() == 0) {
1285 it.remove();
1286 }
1287 }
Svet Ganov2af57082015-07-30 08:44:20 -07001288 if (uidState.isDefault()) {
1289 mUidStates.remove(uidState.uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001290 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001291 if (uidChanged) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001292 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001293 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001294 }
Svet Ganov2af57082015-07-30 08:44:20 -07001295
Dianne Hackborn607b4142013-08-02 18:10:10 -07001296 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001297 scheduleFastWriteLocked();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001298 }
1299 }
1300 if (callbacks != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001301 for (Map.Entry<ModeCallback, ArrayList<ChangeRec>> ent : callbacks.entrySet()) {
1302 ModeCallback cb = ent.getKey();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001303 ArrayList<ChangeRec> reports = ent.getValue();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001304 for (int i=0; i<reports.size(); i++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001305 ChangeRec rep = reports.get(i);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001306 mHandler.sendMessage(PooledLambda.obtainMessage(
1307 AppOpsService::notifyOpChanged,
1308 this, cb, rep.op, rep.uid, rep.pkg));
Dianne Hackborn607b4142013-08-02 18:10:10 -07001309 }
1310 }
1311 }
1312 }
1313
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001314 private void evalAllForegroundOpsLocked() {
1315 for (int uidi = mUidStates.size() - 1; uidi >= 0; uidi--) {
1316 final UidState uidState = mUidStates.valueAt(uidi);
1317 if (uidState.foregroundOps != null) {
1318 uidState.evalForegroundOps(mOpModeWatchers);
1319 }
1320 }
1321 }
1322
Dianne Hackbornc2293022013-02-06 23:14:49 -08001323 @Override
1324 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001325 startWatchingModeWithFlags(op, packageName, 0, callback);
1326 }
1327
1328 @Override
1329 public void startWatchingModeWithFlags(int op, String packageName, int flags,
1330 IAppOpsCallback callback) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001331 int watchedUid = -1;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001332 final int callingUid = Binder.getCallingUid();
1333 final int callingPid = Binder.getCallingPid();
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001334 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
1335 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001336 watchedUid = callingUid;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001337 }
1338 Preconditions.checkArgumentInRange(op, AppOpsManager.OP_NONE,
1339 AppOpsManager._NUM_OP - 1, "Invalid op code: " + op);
Svetoslav Ganov8de59712015-12-09 18:25:13 -08001340 if (callback == null) {
1341 return;
1342 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001343 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -07001344 op = (op != AppOpsManager.OP_NONE) ? AppOpsManager.opToSwitch(op) : op;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001345 ModeCallback cb = mModeWatchers.get(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -08001346 if (cb == null) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001347 cb = new ModeCallback(callback, watchedUid, flags, callingUid, callingPid);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001348 mModeWatchers.put(callback.asBinder(), cb);
1349 }
1350 if (op != AppOpsManager.OP_NONE) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001351 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(op);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001352 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08001353 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001354 mOpModeWatchers.put(op, cbs);
1355 }
1356 cbs.add(cb);
1357 }
1358 if (packageName != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001359 ArraySet<ModeCallback> cbs = mPackageModeWatchers.get(packageName);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001360 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08001361 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001362 mPackageModeWatchers.put(packageName, cbs);
1363 }
1364 cbs.add(cb);
1365 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001366 evalAllForegroundOpsLocked();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001367 }
1368 }
1369
1370 @Override
1371 public void stopWatchingMode(IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -08001372 if (callback == null) {
1373 return;
1374 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001375 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001376 ModeCallback cb = mModeWatchers.remove(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -08001377 if (cb != null) {
1378 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001379 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001380 ArraySet<ModeCallback> cbs = mOpModeWatchers.valueAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001381 cbs.remove(cb);
1382 if (cbs.size() <= 0) {
1383 mOpModeWatchers.removeAt(i);
1384 }
1385 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001386 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001387 ArraySet<ModeCallback> cbs = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001388 cbs.remove(cb);
1389 if (cbs.size() <= 0) {
1390 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001391 }
1392 }
1393 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001394 evalAllForegroundOpsLocked();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001395 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001396 }
1397
1398 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001399 public IBinder getToken(IBinder clientToken) {
1400 synchronized (this) {
1401 ClientState cs = mClients.get(clientToken);
1402 if (cs == null) {
1403 cs = new ClientState(clientToken);
1404 mClients.put(clientToken, cs);
1405 }
1406 return cs;
1407 }
1408 }
1409
1410 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -08001411 public int checkOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001412 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001413 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001414 String resolvedPackageName = resolvePackageName(uid, packageName);
1415 if (resolvedPackageName == null) {
1416 return AppOpsManager.MODE_IGNORED;
1417 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001418 synchronized (this) {
Svet Ganov442ed572016-08-17 17:29:43 -07001419 if (isOpRestrictedLocked(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001420 return AppOpsManager.MODE_IGNORED;
1421 }
Svet Ganov2af57082015-07-30 08:44:20 -07001422 code = AppOpsManager.opToSwitch(code);
1423 UidState uidState = getUidStateLocked(uid, false);
Svet Ganovee438d42017-01-19 18:04:38 -08001424 if (uidState != null && uidState.opModes != null
1425 && uidState.opModes.indexOfKey(code) >= 0) {
1426 return uidState.opModes.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001427 }
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001428 Op op = getOpLocked(code, uid, resolvedPackageName, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001429 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -07001430 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001431 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001432 return op.mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001433 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001434 }
1435
1436 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001437 public int checkAudioOperation(int code, int usage, int uid, String packageName) {
Andrei Stingaceanuefc4a342016-03-22 14:43:01 +00001438 boolean suspended;
1439 try {
1440 suspended = isPackageSuspendedForUser(packageName, uid);
1441 } catch (IllegalArgumentException ex) {
1442 // Package not found.
1443 suspended = false;
1444 }
1445
1446 if (suspended) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001447 Slog.i(TAG, "Audio disabled for suspended package=" + packageName + " for uid=" + uid);
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001448 return AppOpsManager.MODE_IGNORED;
1449 }
1450
John Spurlock1af30c72014-03-10 08:33:35 -04001451 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001452 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -04001453 if (mode != AppOpsManager.MODE_ALLOWED) {
1454 return mode;
1455 }
1456 }
1457 return checkOperation(code, uid, packageName);
1458 }
1459
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001460 private boolean isPackageSuspendedForUser(String pkg, int uid) {
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001461 try {
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001462 return AppGlobals.getPackageManager().isPackageSuspendedForUser(
1463 pkg, UserHandle.getUserId(uid));
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001464 } catch (RemoteException re) {
1465 throw new SecurityException("Could not talk to package manager service");
1466 }
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001467 }
1468
John Spurlock7b414672014-07-18 13:02:39 -04001469 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
1470 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1471 if (usageRestrictions != null) {
1472 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001473 if (r != null && !r.exceptionPackages.contains(packageName)) {
1474 return r.mode;
1475 }
1476 }
1477 return AppOpsManager.MODE_ALLOWED;
1478 }
1479
1480 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001481 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -04001482 String[] exceptionPackages) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07001483 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
John Spurlock1af30c72014-03-10 08:33:35 -04001484 verifyIncomingUid(uid);
1485 verifyIncomingOp(code);
1486 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001487 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1488 if (usageRestrictions == null) {
1489 usageRestrictions = new SparseArray<Restriction>();
1490 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -04001491 }
John Spurlock7b414672014-07-18 13:02:39 -04001492 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001493 if (mode != AppOpsManager.MODE_ALLOWED) {
1494 final Restriction r = new Restriction();
1495 r.mode = mode;
1496 if (exceptionPackages != null) {
1497 final int N = exceptionPackages.length;
1498 r.exceptionPackages = new ArraySet<String>(N);
1499 for (int i = 0; i < N; i++) {
1500 final String pkg = exceptionPackages[i];
1501 if (pkg != null) {
1502 r.exceptionPackages.add(pkg.trim());
1503 }
1504 }
1505 }
John Spurlock7b414672014-07-18 13:02:39 -04001506 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -04001507 }
1508 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001509
1510 mHandler.sendMessage(PooledLambda.obtainMessage(
Svet Ganov3a95f832018-03-23 17:44:30 -07001511 AppOpsService::notifyWatchersOfChange, this, code, UID_ANY));
John Spurlock1af30c72014-03-10 08:33:35 -04001512 }
1513
1514 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001515 public int checkPackage(int uid, String packageName) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001516 Preconditions.checkNotNull(packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001517 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001518 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1519 true /* uidMismatchExpected */);
1520 if (ops != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001521 return AppOpsManager.MODE_ALLOWED;
1522 } else {
1523 return AppOpsManager.MODE_ERRORED;
1524 }
1525 }
1526 }
1527
1528 @Override
Svet Ganov99b60432015-06-27 13:15:22 -07001529 public int noteProxyOperation(int code, String proxyPackageName,
1530 int proxiedUid, String proxiedPackageName) {
1531 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001532 final int proxyUid = Binder.getCallingUid();
1533 String resolveProxyPackageName = resolvePackageName(proxyUid, proxyPackageName);
1534 if (resolveProxyPackageName == null) {
1535 return AppOpsManager.MODE_IGNORED;
1536 }
1537 final int proxyMode = noteOperationUnchecked(code, proxyUid,
1538 resolveProxyPackageName, -1, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001539 if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
1540 return proxyMode;
1541 }
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001542 String resolveProxiedPackageName = resolvePackageName(proxiedUid, proxiedPackageName);
1543 if (resolveProxiedPackageName == null) {
1544 return AppOpsManager.MODE_IGNORED;
1545 }
1546 return noteOperationUnchecked(code, proxiedUid, resolveProxiedPackageName,
1547 proxyMode, resolveProxyPackageName);
Svet Ganov99b60432015-06-27 13:15:22 -07001548 }
1549
1550 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001551 public int noteOperation(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001552 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001553 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001554 String resolvedPackageName = resolvePackageName(uid, packageName);
1555 if (resolvedPackageName == null) {
1556 return AppOpsManager.MODE_IGNORED;
1557 }
1558 return noteOperationUnchecked(code, uid, resolvedPackageName, 0, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001559 }
1560
1561 private int noteOperationUnchecked(int code, int uid, String packageName,
1562 int proxyUid, String proxyPackageName) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001563 synchronized (this) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001564 final Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
Yohei Yukawaa965d652017-10-12 15:02:26 -07001565 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001566 if (ops == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001567 if (DEBUG) Slog.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001568 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001569 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001570 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001571 final Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07001572 if (isOpRestrictedLocked(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001573 return AppOpsManager.MODE_IGNORED;
1574 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001575 final UidState uidState = ops.uidState;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001576 if (op.duration == -1) {
1577 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001578 + " code " + code + " time=" + op.time[uidState.state]
1579 + " duration=" + op.duration);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001580 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001581 op.duration = 0;
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001582 final int switchCode = AppOpsManager.opToSwitch(code);
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001583 // If there is a non-default per UID policy (we set UID op mode only if
1584 // non-default) it takes over, otherwise use the per package policy.
1585 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001586 final int uidMode = uidState.evalMode(uidState.opModes.get(switchCode));
Svet Ganov2af57082015-07-30 08:44:20 -07001587 if (uidMode != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001588 if (DEBUG) Slog.d(TAG, "noteOperation: uid reject #" + uidMode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07001589 + switchCode + " (" + code + ") uid " + uid + " package "
1590 + packageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001591 op.rejectTime[uidState.state] = System.currentTimeMillis();
Svet Ganov2af57082015-07-30 08:44:20 -07001592 return uidMode;
1593 }
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001594 } else {
1595 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001596 final int mode = switchOp.getMode();
1597 if (mode != AppOpsManager.MODE_ALLOWED) {
1598 if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + mode + " for code "
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001599 + switchCode + " (" + code + ") uid " + uid + " package "
1600 + packageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001601 op.rejectTime[uidState.state] = System.currentTimeMillis();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001602 return mode;
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001603 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001604 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001605 if (DEBUG) Slog.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001606 + " package " + packageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001607 op.time[uidState.state] = System.currentTimeMillis();
1608 op.rejectTime[uidState.state] = 0;
Svet Ganov99b60432015-06-27 13:15:22 -07001609 op.proxyUid = proxyUid;
1610 op.proxyPackageName = proxyPackageName;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001611 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001612 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001613 }
1614
1615 @Override
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001616 public void startWatchingActive(int[] ops, IAppOpsActiveCallback callback) {
Svet Ganovf7b47252018-02-26 11:11:27 -08001617 int watchedUid = -1;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001618 final int callingUid = Binder.getCallingUid();
1619 final int callingPid = Binder.getCallingPid();
Svet Ganovf7b47252018-02-26 11:11:27 -08001620 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
1621 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001622 watchedUid = callingUid;
Svet Ganovf7b47252018-02-26 11:11:27 -08001623 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001624 if (ops != null) {
1625 Preconditions.checkArrayElementsInRange(ops, 0,
1626 AppOpsManager._NUM_OP - 1, "Invalid op code in: " + Arrays.toString(ops));
1627 }
1628 if (callback == null) {
1629 return;
1630 }
1631 synchronized (this) {
1632 SparseArray<ActiveCallback> callbacks = mActiveWatchers.get(callback.asBinder());
1633 if (callbacks == null) {
1634 callbacks = new SparseArray<>();
1635 mActiveWatchers.put(callback.asBinder(), callbacks);
1636 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001637 final ActiveCallback activeCallback = new ActiveCallback(callback, watchedUid,
1638 callingUid, callingPid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001639 for (int op : ops) {
1640 callbacks.put(op, activeCallback);
1641 }
1642 }
1643 }
1644
1645 @Override
1646 public void stopWatchingActive(IAppOpsActiveCallback callback) {
1647 if (callback == null) {
1648 return;
1649 }
1650 synchronized (this) {
1651 final SparseArray<ActiveCallback> activeCallbacks =
1652 mActiveWatchers.remove(callback.asBinder());
1653 if (activeCallbacks == null) {
1654 return;
1655 }
1656 final int callbackCount = activeCallbacks.size();
1657 for (int i = 0; i < callbackCount; i++) {
1658 // Apps ops are mapped to a singleton
1659 if (i == 0) {
1660 activeCallbacks.valueAt(i).destroy();
1661 }
1662 }
1663 }
1664 }
1665
1666 @Override
Svet Ganovf7b47252018-02-26 11:11:27 -08001667 public int startOperation(IBinder token, int code, int uid, String packageName,
1668 boolean startIfModeDefault) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001669 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001670 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001671 String resolvedPackageName = resolvePackageName(uid, packageName);
1672 if (resolvedPackageName == null) {
1673 return AppOpsManager.MODE_IGNORED;
1674 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001675 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001676 synchronized (this) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001677 final Ops ops = getOpsRawLocked(uid, resolvedPackageName, true /* edit */,
Yohei Yukawaa965d652017-10-12 15:02:26 -07001678 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001679 if (ops == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001680 if (DEBUG) Slog.d(TAG, "startOperation: no op for code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001681 + " package " + resolvedPackageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001682 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001683 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001684 final Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07001685 if (isOpRestrictedLocked(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001686 return AppOpsManager.MODE_IGNORED;
1687 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001688 final int switchCode = AppOpsManager.opToSwitch(code);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001689 final UidState uidState = ops.uidState;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001690 // If there is a non-default per UID policy (we set UID op mode only if
1691 // non-default) it takes over, otherwise use the per package policy.
1692 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001693 final int uidMode = uidState.evalMode(uidState.opModes.get(switchCode));
Svet Ganovf7b47252018-02-26 11:11:27 -08001694 if (uidMode != AppOpsManager.MODE_ALLOWED
1695 && (!startIfModeDefault || uidMode != AppOpsManager.MODE_DEFAULT)) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001696 if (DEBUG) Slog.d(TAG, "noteOperation: uid reject #" + uidMode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07001697 + switchCode + " (" + code + ") uid " + uid + " package "
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001698 + resolvedPackageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001699 op.rejectTime[uidState.state] = System.currentTimeMillis();
Svet Ganov2af57082015-07-30 08:44:20 -07001700 return uidMode;
1701 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001702 } else {
1703 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001704 final int mode = switchOp.getMode();
1705 if (mode != AppOpsManager.MODE_ALLOWED
1706 && (!startIfModeDefault || mode != AppOpsManager.MODE_DEFAULT)) {
1707 if (DEBUG) Slog.d(TAG, "startOperation: reject #" + mode + " for code "
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001708 + switchCode + " (" + code + ") uid " + uid + " package "
1709 + resolvedPackageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001710 op.rejectTime[uidState.state] = System.currentTimeMillis();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001711 return mode;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001712 }
Svet Ganov2af57082015-07-30 08:44:20 -07001713 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001714 if (DEBUG) Slog.d(TAG, "startOperation: allowing code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001715 + " package " + resolvedPackageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001716 if (op.startNesting == 0) {
1717 op.startRealtime = SystemClock.elapsedRealtime();
1718 op.time[uidState.state] = System.currentTimeMillis();
1719 op.rejectTime[uidState.state] = 0;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001720 op.duration = -1;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001721 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001722 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001723 op.startNesting++;
1724 uidState.startNesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001725 if (client.mStartedOps != null) {
1726 client.mStartedOps.add(op);
1727 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001728 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001729
1730 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001731 }
1732
1733 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001734 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001735 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001736 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001737 String resolvedPackageName = resolvePackageName(uid, packageName);
1738 if (resolvedPackageName == null) {
1739 return;
1740 }
1741 if (!(token instanceof ClientState)) {
1742 return;
1743 }
1744 ClientState client = (ClientState) token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001745 synchronized (this) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001746 Op op = getOpLocked(code, uid, resolvedPackageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001747 if (op == null) {
1748 return;
1749 }
Svet Ganovf7b47252018-02-26 11:11:27 -08001750 if (!client.mStartedOps.remove(op)) {
Svet Ganovf5d5af12018-03-18 11:51:17 -07001751 // We finish ops when packages get removed to guarantee no dangling
1752 // started ops. However, some part of the system may asynchronously
1753 // finish ops for an already gone package. Hence, finishing an op
1754 // for a non existing package is fine and we don't log as a wtf.
1755 final long identity = Binder.clearCallingIdentity();
1756 try {
1757 if (LocalServices.getService(PackageManagerInternal.class).getPackageUid(
1758 resolvedPackageName, 0, UserHandle.getUserId(uid)) < 0) {
1759 Slog.i(TAG, "Finishing op=" + AppOpsManager.opToName(code)
1760 + " for non-existing package=" + resolvedPackageName
1761 + " in uid=" + uid);
1762 return;
1763 }
1764 } finally {
1765 Binder.restoreCallingIdentity(identity);
1766 }
1767 Slog.wtf(TAG, "Operation not started: uid=" + op.uid + " pkg="
1768 + op.packageName + " op=" + AppOpsManager.opToName(op.op));
Svet Ganov31d83ae2018-03-15 10:45:56 -07001769 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001770 }
Svet Ganova7a0db62018-02-27 20:08:01 -08001771 finishOperationLocked(op, /*finishNested*/ false);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001772 if (op.startNesting <= 0) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001773 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, false);
1774 }
1775 }
1776 }
1777
1778 private void scheduleOpActiveChangedIfNeededLocked(int code, int uid, String packageName,
1779 boolean active) {
1780 ArraySet<ActiveCallback> dispatchedCallbacks = null;
1781 final int callbackListCount = mActiveWatchers.size();
1782 for (int i = 0; i < callbackListCount; i++) {
1783 final SparseArray<ActiveCallback> callbacks = mActiveWatchers.valueAt(i);
1784 ActiveCallback callback = callbacks.get(code);
1785 if (callback != null) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001786 if (callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
Svet Ganovf7b47252018-02-26 11:11:27 -08001787 continue;
1788 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001789 if (dispatchedCallbacks == null) {
1790 dispatchedCallbacks = new ArraySet<>();
1791 }
1792 dispatchedCallbacks.add(callback);
1793 }
1794 }
1795 if (dispatchedCallbacks == null) {
1796 return;
1797 }
1798 mHandler.sendMessage(PooledLambda.obtainMessage(
1799 AppOpsService::notifyOpActiveChanged,
1800 this, dispatchedCallbacks, code, uid, packageName, active));
1801 }
1802
1803 private void notifyOpActiveChanged(ArraySet<ActiveCallback> callbacks,
1804 int code, int uid, String packageName, boolean active) {
1805 // There are components watching for mode changes such as window manager
1806 // and location manager which are in our process. The callbacks in these
1807 // components may require permissions our remote caller does not have.
1808 final long identity = Binder.clearCallingIdentity();
1809 try {
1810 final int callbackCount = callbacks.size();
1811 for (int i = 0; i < callbackCount; i++) {
1812 final ActiveCallback callback = callbacks.valueAt(i);
1813 try {
1814 callback.mCallback.opActiveChanged(code, uid, packageName, active);
1815 } catch (RemoteException e) {
1816 /* do nothing */
1817 }
1818 }
1819 } finally {
1820 Binder.restoreCallingIdentity(identity);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001821 }
1822 }
1823
Svet Ganovb9d71a62015-04-30 10:38:13 -07001824 @Override
1825 public int permissionToOpCode(String permission) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001826 if (permission == null) {
1827 return AppOpsManager.OP_NONE;
1828 }
Svet Ganovb9d71a62015-04-30 10:38:13 -07001829 return AppOpsManager.permissionToOpCode(permission);
1830 }
1831
Svet Ganova7a0db62018-02-27 20:08:01 -08001832 void finishOperationLocked(Op op, boolean finishNested) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001833 if (op.startNesting <= 1 || finishNested) {
1834 if (op.startNesting == 1 || finishNested) {
1835 op.duration = (int)(SystemClock.elapsedRealtime() - op.startRealtime);
1836 op.time[op.uidState.state] = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001837 } else {
1838 Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
1839 + op.packageName + " code " + op.op + " time=" + op.time
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001840 + " duration=" + op.duration + " nesting=" + op.startNesting);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001841 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001842 if (op.startNesting >= 1) {
1843 op.uidState.startNesting -= op.startNesting;
1844 }
1845 op.startNesting = 0;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001846 } else {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001847 op.startNesting--;
1848 op.uidState.startNesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001849 }
1850 }
1851
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001852 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001853 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001854 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001855 }
1856 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001857 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001858 }
1859 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
1860 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001861 }
1862
Dianne Hackborn961321f2013-02-05 17:22:41 -08001863 private void verifyIncomingOp(int op) {
1864 if (op >= 0 && op < AppOpsManager._NUM_OP) {
1865 return;
1866 }
1867 throw new IllegalArgumentException("Bad operation #" + op);
1868 }
1869
Svet Ganov2af57082015-07-30 08:44:20 -07001870 private UidState getUidStateLocked(int uid, boolean edit) {
1871 UidState uidState = mUidStates.get(uid);
1872 if (uidState == null) {
1873 if (!edit) {
1874 return null;
1875 }
1876 uidState = new UidState(uid);
1877 mUidStates.put(uid, uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001878 } else {
1879 if (uidState.pendingStateCommitTime != 0) {
1880 if (uidState.pendingStateCommitTime < mLastUptime) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001881 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001882 } else {
1883 mLastUptime = SystemClock.uptimeMillis();
1884 if (uidState.pendingStateCommitTime < mLastUptime) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001885 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001886 }
1887 }
1888 }
Svet Ganov2af57082015-07-30 08:44:20 -07001889 }
1890 return uidState;
1891 }
1892
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001893 private void commitUidPendingStateLocked(UidState uidState) {
Dianne Hackborne93ab412018-05-14 17:52:30 -07001894 final boolean lastForeground = uidState.state <= UID_STATE_LAST_NON_RESTRICTED;
1895 final boolean nowForeground = uidState.pendingState <= UID_STATE_LAST_NON_RESTRICTED;
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001896 uidState.state = uidState.pendingState;
1897 uidState.pendingStateCommitTime = 0;
Dianne Hackborne93ab412018-05-14 17:52:30 -07001898 if (uidState.hasForegroundWatchers && lastForeground != nowForeground) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001899 for (int fgi = uidState.foregroundOps.size() - 1; fgi >= 0; fgi--) {
1900 if (!uidState.foregroundOps.valueAt(fgi)) {
1901 continue;
1902 }
1903 final int code = uidState.foregroundOps.keyAt(fgi);
1904
1905 final ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
1906 if (callbacks != null) {
1907 for (int cbi = callbacks.size() - 1; cbi >= 0; cbi--) {
1908 final ModeCallback callback = callbacks.valueAt(cbi);
1909 if ((callback.mFlags & AppOpsManager.WATCH_FOREGROUND_CHANGES) == 0
1910 || !callback.isWatchingUid(uidState.uid)) {
1911 continue;
1912 }
1913 boolean doAllPackages = uidState.opModes != null
1914 && uidState.opModes.get(code) == AppOpsManager.MODE_FOREGROUND;
1915 if (uidState.pkgOps != null) {
1916 for (int pkgi = uidState.pkgOps.size() - 1; pkgi >= 0; pkgi--) {
1917 final Op op = uidState.pkgOps.valueAt(pkgi).get(code);
1918 if (doAllPackages || (op != null
1919 && op.mode == AppOpsManager.MODE_FOREGROUND)) {
1920 mHandler.sendMessage(PooledLambda.obtainMessage(
1921 AppOpsService::notifyOpChanged,
1922 this, callback, code, uidState.uid,
1923 uidState.pkgOps.keyAt(pkgi)));
1924 }
1925 }
1926 }
1927 }
1928 }
1929 }
1930 }
1931 }
1932
Yohei Yukawaa965d652017-10-12 15:02:26 -07001933 private Ops getOpsRawLocked(int uid, String packageName, boolean edit,
1934 boolean uidMismatchExpected) {
Svet Ganov2af57082015-07-30 08:44:20 -07001935 UidState uidState = getUidStateLocked(uid, edit);
1936 if (uidState == null) {
1937 return null;
1938 }
1939
1940 if (uidState.pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001941 if (!edit) {
1942 return null;
1943 }
Svet Ganov2af57082015-07-30 08:44:20 -07001944 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001945 }
Svet Ganov2af57082015-07-30 08:44:20 -07001946
1947 Ops ops = uidState.pkgOps.get(packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001948 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001949 if (!edit) {
1950 return null;
1951 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001952 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001953 // This is the first time we have seen this package name under this uid,
1954 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -08001955 if (uid != 0) {
1956 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001957 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001958 int pkgUid = -1;
1959 try {
Jason Monk1c7c3192014-06-26 12:52:18 -04001960 ApplicationInfo appInfo = ActivityThread.getPackageManager()
Jeff Sharkeycd654482016-01-08 17:42:11 -07001961 .getApplicationInfo(packageName,
1962 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1963 UserHandle.getUserId(uid));
Jason Monk1c7c3192014-06-26 12:52:18 -04001964 if (appInfo != null) {
1965 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08001966 isPrivileged = (appInfo.privateFlags
1967 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04001968 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08001969 pkgUid = resolveUid(packageName);
1970 if (pkgUid >= 0) {
Chien-Yu Chen75cade02016-01-11 10:56:21 -08001971 isPrivileged = false;
Jason Monk1c7c3192014-06-26 12:52:18 -04001972 }
Dianne Hackborn713df152013-05-17 11:27:57 -07001973 }
Jason Monk1c7c3192014-06-26 12:52:18 -04001974 } catch (RemoteException e) {
1975 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001976 }
1977 if (pkgUid != uid) {
1978 // Oops! The package name is not valid for the uid they are calling
1979 // under. Abort.
Yohei Yukawaa965d652017-10-12 15:02:26 -07001980 if (!uidMismatchExpected) {
1981 RuntimeException ex = new RuntimeException("here");
1982 ex.fillInStackTrace();
1983 Slog.w(TAG, "Bad call: specified package " + packageName
1984 + " under uid " + uid + " but it is really " + pkgUid, ex);
1985 }
Dianne Hackborn514074f2013-02-11 10:52:46 -08001986 return null;
1987 }
1988 } finally {
1989 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001990 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001991 }
Svet Ganov2af57082015-07-30 08:44:20 -07001992 ops = new Ops(packageName, uidState, isPrivileged);
1993 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001994 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08001995 return ops;
1996 }
1997
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001998 private void scheduleWriteLocked() {
1999 if (!mWriteScheduled) {
2000 mWriteScheduled = true;
2001 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
2002 }
2003 }
2004
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002005 private void scheduleFastWriteLocked() {
2006 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002007 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002008 mFastWriteScheduled = true;
2009 mHandler.removeCallbacks(mWriteRunner);
2010 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002011 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002012 }
2013
Dianne Hackborn72e39832013-01-18 18:36:09 -08002014 private Op getOpLocked(int code, int uid, String packageName, boolean edit) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07002015 Ops ops = getOpsRawLocked(uid, packageName, edit,
2016 false /* uidMismatchExpected */);
Dianne Hackborn72e39832013-01-18 18:36:09 -08002017 if (ops == null) {
2018 return null;
2019 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002020 return getOpLocked(ops, code, edit);
2021 }
2022
2023 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002024 Op op = ops.get(code);
2025 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002026 if (!edit) {
2027 return null;
2028 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002029 op = new Op(ops.uidState, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002030 ops.put(code, op);
2031 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002032 if (edit) {
2033 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002034 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002035 return op;
2036 }
2037
Svet Ganov442ed572016-08-17 17:29:43 -07002038 private boolean isOpRestrictedLocked(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04002039 int userHandle = UserHandle.getUserId(uid);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002040 final int restrictionSetCount = mOpUserRestrictions.size();
Ruben Brunk29931bc2016-03-11 00:24:26 -08002041
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002042 for (int i = 0; i < restrictionSetCount; i++) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002043 // For each client, check that the given op is not restricted, or that the given
2044 // package is exempt from the restriction.
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002045 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07002046 if (restrictionState.hasRestriction(code, packageName, userHandle)) {
2047 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
2048 // If we are the system, bypass user restrictions for certain codes
2049 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07002050 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
2051 false /* uidMismatchExpected */);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07002052 if ((ops != null) && ops.isPrivileged) {
2053 return false;
2054 }
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002055 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002056 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002057 return true;
Jason Monk1c7c3192014-06-26 12:52:18 -04002058 }
Jason Monk62062992014-05-06 09:55:28 -04002059 }
2060 return false;
2061 }
2062
Dianne Hackborn35654b62013-01-14 17:38:02 -08002063 void readState() {
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002064 int oldVersion = NO_VERSION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08002065 synchronized (mFile) {
2066 synchronized (this) {
2067 FileInputStream stream;
2068 try {
2069 stream = mFile.openRead();
2070 } catch (FileNotFoundException e) {
2071 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
2072 return;
2073 }
2074 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002075 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002076 try {
2077 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002078 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08002079 int type;
2080 while ((type = parser.next()) != XmlPullParser.START_TAG
2081 && type != XmlPullParser.END_DOCUMENT) {
2082 ;
2083 }
2084
2085 if (type != XmlPullParser.START_TAG) {
2086 throw new IllegalStateException("no start tag found");
2087 }
2088
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002089 final String versionString = parser.getAttributeValue(null, "v");
2090 if (versionString != null) {
2091 oldVersion = Integer.parseInt(versionString);
2092 }
2093
Dianne Hackborn35654b62013-01-14 17:38:02 -08002094 int outerDepth = parser.getDepth();
2095 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2096 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2097 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2098 continue;
2099 }
2100
2101 String tagName = parser.getName();
2102 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00002103 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07002104 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07002105 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002106 } else {
2107 Slog.w(TAG, "Unknown element under <app-ops>: "
2108 + parser.getName());
2109 XmlUtils.skipCurrentTag(parser);
2110 }
2111 }
2112 success = true;
2113 } catch (IllegalStateException e) {
2114 Slog.w(TAG, "Failed parsing " + e);
2115 } catch (NullPointerException e) {
2116 Slog.w(TAG, "Failed parsing " + e);
2117 } catch (NumberFormatException e) {
2118 Slog.w(TAG, "Failed parsing " + e);
2119 } catch (XmlPullParserException e) {
2120 Slog.w(TAG, "Failed parsing " + e);
2121 } catch (IOException e) {
2122 Slog.w(TAG, "Failed parsing " + e);
2123 } catch (IndexOutOfBoundsException e) {
2124 Slog.w(TAG, "Failed parsing " + e);
2125 } finally {
2126 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07002127 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002128 }
2129 try {
2130 stream.close();
2131 } catch (IOException e) {
2132 }
2133 }
2134 }
2135 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002136 synchronized (this) {
2137 upgradeLocked(oldVersion);
2138 }
2139 }
2140
2141 private void upgradeRunAnyInBackgroundLocked() {
2142 for (int i = 0; i < mUidStates.size(); i++) {
2143 final UidState uidState = mUidStates.valueAt(i);
2144 if (uidState == null) {
2145 continue;
2146 }
2147 if (uidState.opModes != null) {
2148 final int idx = uidState.opModes.indexOfKey(AppOpsManager.OP_RUN_IN_BACKGROUND);
2149 if (idx >= 0) {
2150 uidState.opModes.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND,
2151 uidState.opModes.valueAt(idx));
2152 }
2153 }
2154 if (uidState.pkgOps == null) {
2155 continue;
2156 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002157 boolean changed = false;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002158 for (int j = 0; j < uidState.pkgOps.size(); j++) {
2159 Ops ops = uidState.pkgOps.valueAt(j);
2160 if (ops != null) {
2161 final Op op = ops.get(AppOpsManager.OP_RUN_IN_BACKGROUND);
2162 if (op != null && op.mode != AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002163 final Op copy = new Op(op.uidState, op.packageName,
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002164 AppOpsManager.OP_RUN_ANY_IN_BACKGROUND);
2165 copy.mode = op.mode;
2166 ops.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, copy);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002167 changed = true;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002168 }
2169 }
2170 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002171 if (changed) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002172 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002173 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002174 }
2175 }
2176
2177 private void upgradeLocked(int oldVersion) {
2178 if (oldVersion >= CURRENT_VERSION) {
2179 return;
2180 }
2181 Slog.d(TAG, "Upgrading app-ops xml from version " + oldVersion + " to " + CURRENT_VERSION);
2182 switch (oldVersion) {
2183 case NO_VERSION:
2184 upgradeRunAnyInBackgroundLocked();
2185 // fall through
2186 case 1:
2187 // for future upgrades
2188 }
2189 scheduleFastWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002190 }
2191
Svet Ganov2af57082015-07-30 08:44:20 -07002192 void readUidOps(XmlPullParser parser) throws NumberFormatException,
2193 XmlPullParserException, IOException {
2194 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
2195 int outerDepth = parser.getDepth();
2196 int type;
2197 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2198 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2199 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2200 continue;
2201 }
2202
2203 String tagName = parser.getName();
2204 if (tagName.equals("op")) {
2205 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
2206 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
2207 UidState uidState = getUidStateLocked(uid, true);
2208 if (uidState.opModes == null) {
2209 uidState.opModes = new SparseIntArray();
2210 }
2211 uidState.opModes.put(code, mode);
2212 } else {
2213 Slog.w(TAG, "Unknown element under <uid-ops>: "
2214 + parser.getName());
2215 XmlUtils.skipCurrentTag(parser);
2216 }
2217 }
2218 }
2219
Dave Burke0997c5bd2013-08-02 20:25:02 +00002220 void readPackage(XmlPullParser parser) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08002221 XmlPullParserException, IOException {
2222 String pkgName = parser.getAttributeValue(null, "n");
2223 int outerDepth = parser.getDepth();
2224 int type;
2225 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2226 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2227 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2228 continue;
2229 }
2230
2231 String tagName = parser.getName();
2232 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00002233 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002234 } else {
2235 Slog.w(TAG, "Unknown element under <pkg>: "
2236 + parser.getName());
2237 XmlUtils.skipCurrentTag(parser);
2238 }
2239 }
2240 }
2241
Dave Burke0997c5bd2013-08-02 20:25:02 +00002242 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08002243 XmlPullParserException, IOException {
2244 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Jason Monk1c7c3192014-06-26 12:52:18 -04002245 String isPrivilegedString = parser.getAttributeValue(null, "p");
2246 boolean isPrivileged = false;
2247 if (isPrivilegedString == null) {
2248 try {
2249 IPackageManager packageManager = ActivityThread.getPackageManager();
2250 if (packageManager != null) {
2251 ApplicationInfo appInfo = ActivityThread.getPackageManager()
2252 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
2253 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002254 isPrivileged = (appInfo.privateFlags
2255 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04002256 }
2257 } else {
2258 // Could not load data, don't add to cache so it will be loaded later.
2259 return;
2260 }
2261 } catch (RemoteException e) {
2262 Slog.w(TAG, "Could not contact PackageManager", e);
2263 }
2264 } else {
2265 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
2266 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002267 int outerDepth = parser.getDepth();
2268 int type;
2269 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2270 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2271 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2272 continue;
2273 }
2274
2275 String tagName = parser.getName();
2276 if (tagName.equals("op")) {
Svet Ganov2af57082015-07-30 08:44:20 -07002277 UidState uidState = getUidStateLocked(uid, true);
2278 if (uidState.pkgOps == null) {
2279 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002280 }
Svet Ganov2af57082015-07-30 08:44:20 -07002281
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002282 Op op = new Op(uidState, pkgName,
2283 Integer.parseInt(parser.getAttributeValue(null, "n")));
2284
2285 for (int i = parser.getAttributeCount()-1; i >= 0; i--) {
2286 final String name = parser.getAttributeName(i);
2287 final String value = parser.getAttributeValue(i);
2288 switch (name) {
2289 case "m":
2290 op.mode = Integer.parseInt(value);
2291 break;
2292 case "d":
2293 op.duration = Integer.parseInt(value);
2294 break;
2295 case "pu":
2296 op.proxyUid = Integer.parseInt(value);
2297 break;
2298 case "pp":
2299 op.proxyPackageName = value;
2300 break;
2301 case "tp":
2302 op.time[AppOpsManager.UID_STATE_PERSISTENT] = Long.parseLong(value);
2303 break;
2304 case "tt":
2305 op.time[AppOpsManager.UID_STATE_TOP] = Long.parseLong(value);
2306 break;
2307 case "tfs":
2308 op.time[AppOpsManager.UID_STATE_FOREGROUND_SERVICE]
2309 = Long.parseLong(value);
2310 break;
2311 case "tf":
2312 op.time[AppOpsManager.UID_STATE_FOREGROUND] = Long.parseLong(value);
2313 break;
2314 case "tb":
2315 op.time[AppOpsManager.UID_STATE_BACKGROUND] = Long.parseLong(value);
2316 break;
2317 case "tc":
2318 op.time[AppOpsManager.UID_STATE_CACHED] = Long.parseLong(value);
2319 break;
2320 case "rp":
2321 op.rejectTime[AppOpsManager.UID_STATE_PERSISTENT]
2322 = Long.parseLong(value);
2323 break;
2324 case "rt":
2325 op.rejectTime[AppOpsManager.UID_STATE_TOP] = Long.parseLong(value);
2326 break;
2327 case "rfs":
2328 op.rejectTime[AppOpsManager.UID_STATE_FOREGROUND_SERVICE]
2329 = Long.parseLong(value);
2330 break;
2331 case "rf":
2332 op.rejectTime[AppOpsManager.UID_STATE_FOREGROUND]
2333 = Long.parseLong(value);
2334 break;
2335 case "rb":
2336 op.rejectTime[AppOpsManager.UID_STATE_BACKGROUND]
2337 = Long.parseLong(value);
2338 break;
2339 case "rc":
2340 op.rejectTime[AppOpsManager.UID_STATE_CACHED]
2341 = Long.parseLong(value);
2342 break;
2343 case "t":
2344 // Backwards compat.
2345 op.time[AppOpsManager.UID_STATE_TOP] = Long.parseLong(value);
2346 break;
2347 case "r":
2348 // Backwards compat.
2349 op.rejectTime[AppOpsManager.UID_STATE_TOP] = Long.parseLong(value);
2350 break;
2351 default:
2352 Slog.w(TAG, "Unknown attribute in 'op' tag: " + name);
2353 break;
2354 }
2355 }
2356
Svet Ganov2af57082015-07-30 08:44:20 -07002357 Ops ops = uidState.pkgOps.get(pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002358 if (ops == null) {
Svet Ganov2af57082015-07-30 08:44:20 -07002359 ops = new Ops(pkgName, uidState, isPrivileged);
2360 uidState.pkgOps.put(pkgName, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002361 }
2362 ops.put(op.op, op);
2363 } else {
2364 Slog.w(TAG, "Unknown element under <pkg>: "
2365 + parser.getName());
2366 XmlUtils.skipCurrentTag(parser);
2367 }
2368 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002369 UidState uidState = getUidStateLocked(uid, false);
2370 if (uidState != null) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002371 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002372 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002373 }
2374
2375 void writeState() {
2376 synchronized (mFile) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002377 FileOutputStream stream;
2378 try {
2379 stream = mFile.startWrite();
2380 } catch (IOException e) {
2381 Slog.w(TAG, "Failed to write state: " + e);
2382 return;
2383 }
2384
Dianne Hackborne17b4452018-01-10 13:15:40 -08002385 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
2386
Dianne Hackborn35654b62013-01-14 17:38:02 -08002387 try {
2388 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002389 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08002390 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002391 out.startTag(null, "app-ops");
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002392 out.attribute(null, "v", String.valueOf(CURRENT_VERSION));
Svet Ganov2af57082015-07-30 08:44:20 -07002393
2394 final int uidStateCount = mUidStates.size();
2395 for (int i = 0; i < uidStateCount; i++) {
2396 UidState uidState = mUidStates.valueAt(i);
2397 if (uidState.opModes != null && uidState.opModes.size() > 0) {
2398 out.startTag(null, "uid");
2399 out.attribute(null, "n", Integer.toString(uidState.uid));
2400 SparseIntArray uidOpModes = uidState.opModes;
2401 final int opCount = uidOpModes.size();
2402 for (int j = 0; j < opCount; j++) {
2403 final int op = uidOpModes.keyAt(j);
2404 final int mode = uidOpModes.valueAt(j);
2405 out.startTag(null, "op");
2406 out.attribute(null, "n", Integer.toString(op));
2407 out.attribute(null, "m", Integer.toString(mode));
2408 out.endTag(null, "op");
2409 }
2410 out.endTag(null, "uid");
2411 }
2412 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002413
2414 if (allOps != null) {
2415 String lastPkg = null;
2416 for (int i=0; i<allOps.size(); i++) {
2417 AppOpsManager.PackageOps pkg = allOps.get(i);
2418 if (!pkg.getPackageName().equals(lastPkg)) {
2419 if (lastPkg != null) {
2420 out.endTag(null, "pkg");
2421 }
2422 lastPkg = pkg.getPackageName();
2423 out.startTag(null, "pkg");
2424 out.attribute(null, "n", lastPkg);
2425 }
2426 out.startTag(null, "uid");
2427 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04002428 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07002429 Ops ops = getOpsRawLocked(pkg.getUid(), pkg.getPackageName(),
2430 false /* edit */, false /* uidMismatchExpected */);
Jason Monk1c7c3192014-06-26 12:52:18 -04002431 // Should always be present as the list of PackageOps is generated
2432 // from Ops.
2433 if (ops != null) {
2434 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
2435 } else {
2436 out.attribute(null, "p", Boolean.toString(false));
2437 }
2438 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002439 List<AppOpsManager.OpEntry> ops = pkg.getOps();
2440 for (int j=0; j<ops.size(); j++) {
2441 AppOpsManager.OpEntry op = ops.get(j);
2442 out.startTag(null, "op");
2443 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07002444 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002445 out.attribute(null, "m", Integer.toString(op.getMode()));
2446 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002447 for (int k = 0; k < _NUM_UID_STATE; k++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002448 final long time = op.getLastTimeFor(k);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002449 if (time != 0) {
2450 out.attribute(null, UID_STATE_TIME_ATTRS[k],
2451 Long.toString(time));
2452 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002453 final long rejectTime = op.getLastRejectTimeFor(k);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002454 if (rejectTime != 0) {
2455 out.attribute(null, UID_STATE_REJECT_ATTRS[k],
2456 Long.toString(rejectTime));
2457 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002458 }
2459 int dur = op.getDuration();
2460 if (dur != 0) {
2461 out.attribute(null, "d", Integer.toString(dur));
2462 }
Svet Ganov99b60432015-06-27 13:15:22 -07002463 int proxyUid = op.getProxyUid();
2464 if (proxyUid != -1) {
2465 out.attribute(null, "pu", Integer.toString(proxyUid));
2466 }
2467 String proxyPackageName = op.getProxyPackageName();
2468 if (proxyPackageName != null) {
2469 out.attribute(null, "pp", proxyPackageName);
2470 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002471 out.endTag(null, "op");
2472 }
2473 out.endTag(null, "uid");
2474 }
2475 if (lastPkg != null) {
2476 out.endTag(null, "pkg");
2477 }
2478 }
2479
2480 out.endTag(null, "app-ops");
2481 out.endDocument();
2482 mFile.finishWrite(stream);
2483 } catch (IOException e) {
2484 Slog.w(TAG, "Failed to write state, restoring backup.", e);
2485 mFile.failWrite(stream);
2486 }
2487 }
2488 }
2489
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002490 static class Shell extends ShellCommand {
2491 final IAppOpsService mInterface;
2492 final AppOpsService mInternal;
2493
2494 int userId = UserHandle.USER_SYSTEM;
2495 String packageName;
2496 String opStr;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002497 String modeStr;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002498 int op;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002499 int mode;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002500 int packageUid;
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002501 int nonpackageUid;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05002502 final static Binder sBinder = new Binder();
2503 IBinder mToken;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002504
2505 Shell(IAppOpsService iface, AppOpsService internal) {
2506 mInterface = iface;
2507 mInternal = internal;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05002508 try {
2509 mToken = mInterface.getToken(sBinder);
2510 } catch (RemoteException e) {
2511 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002512 }
2513
2514 @Override
2515 public int onCommand(String cmd) {
2516 return onShellCommand(this, cmd);
2517 }
2518
2519 @Override
2520 public void onHelp() {
2521 PrintWriter pw = getOutPrintWriter();
2522 dumpCommandHelp(pw);
2523 }
2524
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002525 static private int strOpToOp(String op, PrintWriter err) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002526 try {
2527 return AppOpsManager.strOpToOp(op);
2528 } catch (IllegalArgumentException e) {
2529 }
2530 try {
2531 return Integer.parseInt(op);
2532 } catch (NumberFormatException e) {
2533 }
2534 try {
2535 return AppOpsManager.strDebugOpToOp(op);
2536 } catch (IllegalArgumentException e) {
2537 err.println("Error: " + e.getMessage());
2538 return -1;
2539 }
2540 }
2541
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002542 static int strModeToMode(String modeStr, PrintWriter err) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002543 for (int i = AppOpsManager.MODE_NAMES.length - 1; i >= 0; i--) {
2544 if (AppOpsManager.MODE_NAMES[i].equals(modeStr)) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002545 return i;
2546 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002547 }
2548 try {
2549 return Integer.parseInt(modeStr);
2550 } catch (NumberFormatException e) {
2551 }
2552 err.println("Error: Mode " + modeStr + " is not valid");
2553 return -1;
2554 }
2555
2556 int parseUserOpMode(int defMode, PrintWriter err) throws RemoteException {
2557 userId = UserHandle.USER_CURRENT;
2558 opStr = null;
2559 modeStr = null;
2560 for (String argument; (argument = getNextArg()) != null;) {
2561 if ("--user".equals(argument)) {
2562 userId = UserHandle.parseUserArg(getNextArgRequired());
2563 } else {
2564 if (opStr == null) {
2565 opStr = argument;
2566 } else if (modeStr == null) {
2567 modeStr = argument;
2568 break;
2569 }
2570 }
2571 }
2572 if (opStr == null) {
2573 err.println("Error: Operation not specified.");
2574 return -1;
2575 }
2576 op = strOpToOp(opStr, err);
2577 if (op < 0) {
2578 return -1;
2579 }
2580 if (modeStr != null) {
2581 if ((mode=strModeToMode(modeStr, err)) < 0) {
2582 return -1;
2583 }
2584 } else {
2585 mode = defMode;
2586 }
2587 return 0;
2588 }
2589
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002590 int parseUserPackageOp(boolean reqOp, PrintWriter err) throws RemoteException {
2591 userId = UserHandle.USER_CURRENT;
2592 packageName = null;
2593 opStr = null;
2594 for (String argument; (argument = getNextArg()) != null;) {
2595 if ("--user".equals(argument)) {
2596 userId = UserHandle.parseUserArg(getNextArgRequired());
2597 } else {
2598 if (packageName == null) {
2599 packageName = argument;
2600 } else if (opStr == null) {
2601 opStr = argument;
2602 break;
2603 }
2604 }
2605 }
2606 if (packageName == null) {
2607 err.println("Error: Package name not specified.");
2608 return -1;
2609 } else if (opStr == null && reqOp) {
2610 err.println("Error: Operation not specified.");
2611 return -1;
2612 }
2613 if (opStr != null) {
2614 op = strOpToOp(opStr, err);
2615 if (op < 0) {
2616 return -1;
2617 }
2618 } else {
2619 op = AppOpsManager.OP_NONE;
2620 }
2621 if (userId == UserHandle.USER_CURRENT) {
2622 userId = ActivityManager.getCurrentUser();
2623 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002624 nonpackageUid = -1;
2625 try {
2626 nonpackageUid = Integer.parseInt(packageName);
2627 } catch (NumberFormatException e) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002628 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002629 if (nonpackageUid == -1 && packageName.length() > 1 && packageName.charAt(0) == 'u'
2630 && packageName.indexOf('.') < 0) {
2631 int i = 1;
2632 while (i < packageName.length() && packageName.charAt(i) >= '0'
2633 && packageName.charAt(i) <= '9') {
2634 i++;
2635 }
2636 if (i > 1 && i < packageName.length()) {
2637 String userStr = packageName.substring(1, i);
2638 try {
2639 int user = Integer.parseInt(userStr);
2640 char type = packageName.charAt(i);
2641 i++;
2642 int startTypeVal = i;
2643 while (i < packageName.length() && packageName.charAt(i) >= '0'
2644 && packageName.charAt(i) <= '9') {
2645 i++;
2646 }
2647 if (i > startTypeVal) {
2648 String typeValStr = packageName.substring(startTypeVal, i);
2649 try {
2650 int typeVal = Integer.parseInt(typeValStr);
2651 if (type == 'a') {
2652 nonpackageUid = UserHandle.getUid(user,
2653 typeVal + Process.FIRST_APPLICATION_UID);
2654 } else if (type == 's') {
2655 nonpackageUid = UserHandle.getUid(user, typeVal);
2656 }
2657 } catch (NumberFormatException e) {
2658 }
2659 }
2660 } catch (NumberFormatException e) {
2661 }
2662 }
2663 }
2664 if (nonpackageUid != -1) {
2665 packageName = null;
2666 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08002667 packageUid = resolveUid(packageName);
2668 if (packageUid < 0) {
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002669 packageUid = AppGlobals.getPackageManager().getPackageUid(packageName,
2670 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
2671 }
2672 if (packageUid < 0) {
2673 err.println("Error: No UID for " + packageName + " in user " + userId);
2674 return -1;
2675 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002676 }
2677 return 0;
2678 }
2679 }
2680
2681 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002682 FileDescriptor err, String[] args, ShellCallback callback,
2683 ResultReceiver resultReceiver) {
2684 (new Shell(this, this)).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002685 }
2686
2687 static void dumpCommandHelp(PrintWriter pw) {
2688 pw.println("AppOps service (appops) commands:");
2689 pw.println(" help");
2690 pw.println(" Print this help text.");
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05002691 pw.println(" start [--user <USER_ID>] <PACKAGE | UID> <OP> ");
2692 pw.println(" Starts a given operation for a particular application.");
2693 pw.println(" stop [--user <USER_ID>] <PACKAGE | UID> <OP> ");
2694 pw.println(" Stops a given operation for a particular application.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002695 pw.println(" set [--user <USER_ID>] <PACKAGE | UID> <OP> <MODE>");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002696 pw.println(" Set the mode for a particular application and operation.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002697 pw.println(" get [--user <USER_ID>] <PACKAGE | UID> [<OP>]");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002698 pw.println(" Return the mode for a particular application and optional operation.");
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002699 pw.println(" query-op [--user <USER_ID>] <OP> [<MODE>]");
2700 pw.println(" Print all packages that currently have the given op in the given mode.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002701 pw.println(" reset [--user <USER_ID>] [<PACKAGE>]");
2702 pw.println(" Reset the given application or all applications to default modes.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002703 pw.println(" write-settings");
2704 pw.println(" Immediately write pending changes to storage.");
2705 pw.println(" read-settings");
2706 pw.println(" Read the last written settings, replacing current state in RAM.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002707 pw.println(" options:");
2708 pw.println(" <PACKAGE> an Android package name.");
2709 pw.println(" <OP> an AppOps operation.");
2710 pw.println(" <MODE> one of allow, ignore, deny, or default");
2711 pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
2712 pw.println(" specified, the current user is assumed.");
2713 }
2714
2715 static int onShellCommand(Shell shell, String cmd) {
2716 if (cmd == null) {
2717 return shell.handleDefaultCommands(cmd);
2718 }
2719 PrintWriter pw = shell.getOutPrintWriter();
2720 PrintWriter err = shell.getErrPrintWriter();
2721 try {
2722 switch (cmd) {
2723 case "set": {
2724 int res = shell.parseUserPackageOp(true, err);
2725 if (res < 0) {
2726 return res;
2727 }
2728 String modeStr = shell.getNextArg();
2729 if (modeStr == null) {
2730 err.println("Error: Mode not specified.");
2731 return -1;
2732 }
2733
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002734 final int mode = shell.strModeToMode(modeStr, err);
2735 if (mode < 0) {
2736 return -1;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002737 }
2738
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002739 if (shell.packageName != null) {
2740 shell.mInterface.setMode(shell.op, shell.packageUid, shell.packageName,
2741 mode);
2742 } else {
2743 shell.mInterface.setUidMode(shell.op, shell.nonpackageUid, mode);
2744 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002745 return 0;
2746 }
2747 case "get": {
2748 int res = shell.parseUserPackageOp(false, err);
2749 if (res < 0) {
2750 return res;
2751 }
2752
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002753 List<AppOpsManager.PackageOps> ops;
2754 if (shell.packageName != null) {
2755 ops = shell.mInterface.getOpsForPackage(
2756 shell.packageUid, shell.packageName,
2757 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
2758 } else {
2759 ops = shell.mInterface.getUidOps(
2760 shell.nonpackageUid,
2761 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
2762 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002763 if (ops == null || ops.size() <= 0) {
2764 pw.println("No operations.");
Svet Ganov82f09bc2018-01-12 22:08:40 -08002765 if (shell.op > AppOpsManager.OP_NONE && shell.op < AppOpsManager._NUM_OP) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002766 pw.println("Default mode: " + AppOpsManager.modeToName(
Svet Ganov82f09bc2018-01-12 22:08:40 -08002767 AppOpsManager.opToDefaultMode(shell.op)));
2768 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002769 return 0;
2770 }
2771 final long now = System.currentTimeMillis();
2772 for (int i=0; i<ops.size(); i++) {
2773 List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
2774 for (int j=0; j<entries.size(); j++) {
2775 AppOpsManager.OpEntry ent = entries.get(j);
2776 pw.print(AppOpsManager.opToName(ent.getOp()));
2777 pw.print(": ");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002778 pw.print(AppOpsManager.modeToName(ent.getMode()));
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002779 if (ent.getTime() != 0) {
2780 pw.print("; time=");
2781 TimeUtils.formatDuration(now - ent.getTime(), pw);
2782 pw.print(" ago");
2783 }
2784 if (ent.getRejectTime() != 0) {
2785 pw.print("; rejectTime=");
2786 TimeUtils.formatDuration(now - ent.getRejectTime(), pw);
2787 pw.print(" ago");
2788 }
2789 if (ent.getDuration() == -1) {
2790 pw.print(" (running)");
2791 } else if (ent.getDuration() != 0) {
2792 pw.print("; duration=");
2793 TimeUtils.formatDuration(ent.getDuration(), pw);
2794 }
2795 pw.println();
2796 }
2797 }
2798 return 0;
2799 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002800 case "query-op": {
2801 int res = shell.parseUserOpMode(AppOpsManager.MODE_IGNORED, err);
2802 if (res < 0) {
2803 return res;
2804 }
2805 List<AppOpsManager.PackageOps> ops = shell.mInterface.getPackagesForOps(
2806 new int[] {shell.op});
2807 if (ops == null || ops.size() <= 0) {
2808 pw.println("No operations.");
2809 return 0;
2810 }
2811 for (int i=0; i<ops.size(); i++) {
2812 final AppOpsManager.PackageOps pkg = ops.get(i);
2813 boolean hasMatch = false;
2814 final List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
2815 for (int j=0; j<entries.size(); j++) {
2816 AppOpsManager.OpEntry ent = entries.get(j);
2817 if (ent.getOp() == shell.op && ent.getMode() == shell.mode) {
2818 hasMatch = true;
2819 break;
2820 }
2821 }
2822 if (hasMatch) {
2823 pw.println(pkg.getPackageName());
2824 }
2825 }
2826 return 0;
2827 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002828 case "reset": {
2829 String packageName = null;
2830 int userId = UserHandle.USER_CURRENT;
2831 for (String argument; (argument = shell.getNextArg()) != null;) {
2832 if ("--user".equals(argument)) {
2833 String userStr = shell.getNextArgRequired();
2834 userId = UserHandle.parseUserArg(userStr);
2835 } else {
2836 if (packageName == null) {
2837 packageName = argument;
2838 } else {
2839 err.println("Error: Unsupported argument: " + argument);
2840 return -1;
2841 }
2842 }
2843 }
2844
2845 if (userId == UserHandle.USER_CURRENT) {
2846 userId = ActivityManager.getCurrentUser();
2847 }
2848
2849 shell.mInterface.resetAllModes(userId, packageName);
2850 pw.print("Reset all modes for: ");
2851 if (userId == UserHandle.USER_ALL) {
2852 pw.print("all users");
2853 } else {
2854 pw.print("user "); pw.print(userId);
2855 }
2856 pw.print(", ");
2857 if (packageName == null) {
2858 pw.println("all packages");
2859 } else {
2860 pw.print("package "); pw.println(packageName);
2861 }
2862 return 0;
2863 }
2864 case "write-settings": {
Dianne Hackbornd5254412018-05-11 18:02:58 -07002865 shell.mInternal.enforceManageAppOpsModes(Binder.getCallingPid(),
2866 Binder.getCallingUid(), -1);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002867 long token = Binder.clearCallingIdentity();
2868 try {
2869 synchronized (shell.mInternal) {
2870 shell.mInternal.mHandler.removeCallbacks(shell.mInternal.mWriteRunner);
2871 }
2872 shell.mInternal.writeState();
2873 pw.println("Current settings written.");
2874 } finally {
2875 Binder.restoreCallingIdentity(token);
2876 }
2877 return 0;
2878 }
2879 case "read-settings": {
Dianne Hackbornd5254412018-05-11 18:02:58 -07002880 shell.mInternal.enforceManageAppOpsModes(Binder.getCallingPid(),
2881 Binder.getCallingUid(), -1);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002882 long token = Binder.clearCallingIdentity();
2883 try {
2884 shell.mInternal.readState();
2885 pw.println("Last settings read.");
2886 } finally {
2887 Binder.restoreCallingIdentity(token);
2888 }
2889 return 0;
2890 }
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05002891 case "start": {
2892 int res = shell.parseUserPackageOp(true, err);
2893 if (res < 0) {
2894 return res;
2895 }
2896
2897 if (shell.packageName != null) {
2898 shell.mInterface.startOperation(shell.mToken,
2899 shell.op, shell.packageUid, shell.packageName, true);
2900 } else {
2901 return -1;
2902 }
2903 return 0;
2904 }
2905 case "stop": {
2906 int res = shell.parseUserPackageOp(true, err);
2907 if (res < 0) {
2908 return res;
2909 }
2910
2911 if (shell.packageName != null) {
2912 shell.mInterface.finishOperation(shell.mToken,
2913 shell.op, shell.packageUid, shell.packageName);
2914 } else {
2915 return -1;
2916 }
2917 return 0;
2918 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002919 default:
2920 return shell.handleDefaultCommands(cmd);
2921 }
2922 } catch (RemoteException e) {
2923 pw.println("Remote exception: " + e);
2924 }
2925 return -1;
2926 }
2927
2928 private void dumpHelp(PrintWriter pw) {
2929 pw.println("AppOps service (appops) dump options:");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002930 pw.println(" -h");
2931 pw.println(" Print this help text.");
2932 pw.println(" --op [OP]");
2933 pw.println(" Limit output to data associated with the given app op code.");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002934 pw.println(" --mode [MODE]");
2935 pw.println(" Limit output to data associated with the given app op mode.");
2936 pw.println(" --package [PACKAGE]");
2937 pw.println(" Limit output to data associated with the given package name.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002938 }
2939
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002940 private void dumpTimesLocked(PrintWriter pw, String firstPrefix, String prefix, long[] times,
2941 long now, SimpleDateFormat sdf, Date date) {
2942 boolean hasTime = false;
2943 for (int i = 0; i < _NUM_UID_STATE; i++) {
2944 if (times[i] != 0) {
2945 hasTime = true;
2946 break;
2947 }
2948 }
2949 if (!hasTime) {
2950 return;
2951 }
2952 boolean first = true;
2953 for (int i = 0; i < _NUM_UID_STATE; i++) {
2954 if (times[i] != 0) {
2955 pw.print(first ? firstPrefix : prefix);
2956 first = false;
2957 pw.print(UID_STATE_NAMES[i]);
2958 pw.print(" = ");
2959 date.setTime(times[i]);
2960 pw.print(sdf.format(date));
2961 pw.print(" (");
2962 TimeUtils.formatDuration(times[i]-now, pw);
2963 pw.println(")");
2964 }
2965 }
2966 }
2967
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002968 @Override
2969 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002970 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002971
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002972 int dumpOp = -1;
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002973 String dumpPackage = null;
2974 int dumpUid = -1;
2975 int dumpMode = -1;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002976
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002977 if (args != null) {
2978 for (int i=0; i<args.length; i++) {
2979 String arg = args[i];
2980 if ("-h".equals(arg)) {
2981 dumpHelp(pw);
2982 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07002983 } else if ("-a".equals(arg)) {
2984 // dump all data
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002985 } else if ("--op".equals(arg)) {
2986 i++;
2987 if (i >= args.length) {
2988 pw.println("No argument for --op option");
2989 return;
2990 }
2991 dumpOp = Shell.strOpToOp(args[i], pw);
2992 if (dumpOp < 0) {
2993 return;
2994 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002995 } else if ("--package".equals(arg)) {
2996 i++;
2997 if (i >= args.length) {
2998 pw.println("No argument for --package option");
2999 return;
3000 }
3001 dumpPackage = args[i];
3002 try {
3003 dumpUid = AppGlobals.getPackageManager().getPackageUid(dumpPackage,
3004 PackageManager.MATCH_KNOWN_PACKAGES | PackageManager.MATCH_INSTANT,
3005 0);
3006 } catch (RemoteException e) {
3007 }
3008 if (dumpUid < 0) {
3009 pw.println("Unknown package: " + dumpPackage);
3010 return;
3011 }
3012 dumpUid = UserHandle.getAppId(dumpUid);
3013 } else if ("--mode".equals(arg)) {
3014 i++;
3015 if (i >= args.length) {
3016 pw.println("No argument for --mode option");
3017 return;
3018 }
3019 dumpMode = Shell.strModeToMode(args[i], pw);
3020 if (dumpMode < 0) {
3021 return;
3022 }
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003023 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
3024 pw.println("Unknown option: " + arg);
3025 return;
3026 } else {
3027 pw.println("Unknown command: " + arg);
3028 return;
3029 }
3030 }
3031 }
3032
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003033 synchronized (this) {
3034 pw.println("Current AppOps Service state:");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003035 mConstants.dump(pw);
3036 pw.println();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003037 final long now = System.currentTimeMillis();
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003038 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003039 final long nowUptime = SystemClock.uptimeMillis();
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003040 final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
3041 final Date date = new Date();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003042 boolean needSep = false;
Dianne Hackbornd5254412018-05-11 18:02:58 -07003043 if (dumpOp < 0 && dumpMode < 0 && dumpPackage == null && mProfileOwners != null) {
3044 pw.println(" Profile owners:");
3045 for (int poi = 0; poi < mProfileOwners.size(); poi++) {
3046 pw.print(" User #");
3047 pw.print(mProfileOwners.keyAt(poi));
3048 pw.print(": ");
3049 UserHandle.formatUid(pw, mProfileOwners.valueAt(poi));
3050 pw.println();
3051 }
3052 pw.println();
3053 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003054 if (mOpModeWatchers.size() > 0) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003055 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003056 for (int i=0; i<mOpModeWatchers.size(); i++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003057 if (dumpOp >= 0 && dumpOp != mOpModeWatchers.keyAt(i)) {
3058 continue;
3059 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003060 boolean printedOpHeader = false;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003061 ArraySet<ModeCallback> callbacks = mOpModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003062 for (int j=0; j<callbacks.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003063 final ModeCallback cb = callbacks.valueAt(j);
3064 if (dumpPackage != null && cb.mWatchingUid >= 0
3065 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3066 continue;
3067 }
3068 needSep = true;
3069 if (!printedHeader) {
3070 pw.println(" Op mode watchers:");
3071 printedHeader = true;
3072 }
3073 if (!printedOpHeader) {
3074 pw.print(" Op ");
3075 pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
3076 pw.println(":");
3077 printedOpHeader = true;
3078 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003079 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003080 pw.println(cb);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003081 }
3082 }
3083 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003084 if (mPackageModeWatchers.size() > 0 && dumpOp < 0) {
3085 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003086 for (int i=0; i<mPackageModeWatchers.size(); i++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003087 if (dumpPackage != null && !dumpPackage.equals(mPackageModeWatchers.keyAt(i))) {
3088 continue;
3089 }
3090 needSep = true;
3091 if (!printedHeader) {
3092 pw.println(" Package mode watchers:");
3093 printedHeader = true;
3094 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003095 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
3096 pw.println(":");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003097 ArraySet<ModeCallback> callbacks = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003098 for (int j=0; j<callbacks.size(); j++) {
3099 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08003100 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003101 }
3102 }
3103 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003104 if (mModeWatchers.size() > 0 && dumpOp < 0) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003105 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003106 for (int i=0; i<mModeWatchers.size(); i++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003107 final ModeCallback cb = mModeWatchers.valueAt(i);
3108 if (dumpPackage != null && cb.mWatchingUid >= 0
3109 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3110 continue;
3111 }
3112 needSep = true;
3113 if (!printedHeader) {
3114 pw.println(" All op mode watchers:");
3115 printedHeader = true;
3116 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003117 pw.print(" ");
3118 pw.print(Integer.toHexString(System.identityHashCode(mModeWatchers.keyAt(i))));
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003119 pw.print(": "); pw.println(cb);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003120 }
3121 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003122 if (mActiveWatchers.size() > 0 && dumpMode < 0) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003123 needSep = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003124 boolean printedHeader = false;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003125 for (int i = 0; i < mActiveWatchers.size(); i++) {
3126 final SparseArray<ActiveCallback> activeWatchers = mActiveWatchers.valueAt(i);
3127 if (activeWatchers.size() <= 0) {
3128 continue;
3129 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003130 final ActiveCallback cb = activeWatchers.valueAt(0);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003131 if (dumpOp >= 0 && activeWatchers.indexOfKey(dumpOp) < 0) {
3132 continue;
3133 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003134 if (dumpPackage != null && cb.mWatchingUid >= 0
3135 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3136 continue;
3137 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003138 if (!printedHeader) {
3139 pw.println(" All op active watchers:");
3140 printedHeader = true;
3141 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003142 pw.print(" ");
3143 pw.print(Integer.toHexString(System.identityHashCode(
3144 mActiveWatchers.keyAt(i))));
3145 pw.println(" ->");
3146 pw.print(" [");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003147 final int opCount = activeWatchers.size();
3148 for (i = 0; i < opCount; i++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003149 if (i > 0) {
3150 pw.print(' ');
3151 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003152 pw.print(AppOpsManager.opToName(activeWatchers.keyAt(i)));
3153 if (i < opCount - 1) {
3154 pw.print(',');
3155 }
3156 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003157 pw.println("]");
3158 pw.print(" ");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003159 pw.println(cb);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003160 }
3161 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003162 if (mClients.size() > 0 && dumpMode < 0) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003163 needSep = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003164 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003165 for (int i=0; i<mClients.size(); i++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003166 boolean printedClient = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003167 ClientState cs = mClients.valueAt(i);
Svet Ganovf7b47252018-02-26 11:11:27 -08003168 if (cs.mStartedOps.size() > 0) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003169 boolean printedStarted = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003170 for (int j=0; j<cs.mStartedOps.size(); j++) {
3171 Op op = cs.mStartedOps.get(j);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003172 if (dumpOp >= 0 && op.op != dumpOp) {
3173 continue;
3174 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003175 if (dumpPackage != null && !dumpPackage.equals(op.packageName)) {
3176 continue;
3177 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003178 if (!printedHeader) {
3179 pw.println(" Clients:");
3180 printedHeader = true;
3181 }
3182 if (!printedClient) {
3183 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
3184 pw.print(" "); pw.println(cs);
3185 printedClient = true;
3186 }
3187 if (!printedStarted) {
3188 pw.println(" Started ops:");
3189 printedStarted = true;
3190 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003191 pw.print(" "); pw.print("uid="); pw.print(op.uid);
3192 pw.print(" pkg="); pw.print(op.packageName);
3193 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
3194 }
3195 }
3196 }
3197 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003198 if (mAudioRestrictions.size() > 0 && dumpOp < 0 && dumpPackage != null
3199 && dumpMode < 0) {
John Spurlock1af30c72014-03-10 08:33:35 -04003200 boolean printedHeader = false;
3201 for (int o=0; o<mAudioRestrictions.size(); o++) {
3202 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
3203 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
3204 for (int i=0; i<restrictions.size(); i++) {
3205 if (!printedHeader){
3206 pw.println(" Audio Restrictions:");
3207 printedHeader = true;
3208 needSep = true;
3209 }
John Spurlock7b414672014-07-18 13:02:39 -04003210 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04003211 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04003212 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04003213 Restriction r = restrictions.valueAt(i);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003214 pw.print(": mode="); pw.println(AppOpsManager.modeToName(r.mode));
John Spurlock1af30c72014-03-10 08:33:35 -04003215 if (!r.exceptionPackages.isEmpty()) {
3216 pw.println(" Exceptions:");
3217 for (int j=0; j<r.exceptionPackages.size(); j++) {
3218 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
3219 }
3220 }
3221 }
3222 }
3223 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003224 if (needSep) {
3225 pw.println();
3226 }
Svet Ganov2af57082015-07-30 08:44:20 -07003227 for (int i=0; i<mUidStates.size(); i++) {
3228 UidState uidState = mUidStates.valueAt(i);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003229 final SparseIntArray opModes = uidState.opModes;
3230 final ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
3231
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003232 if (dumpOp >= 0 || dumpPackage != null || dumpMode >= 0) {
3233 boolean hasOp = dumpOp < 0 || (uidState.opModes != null
3234 && uidState.opModes.indexOfKey(dumpOp) >= 0);
3235 boolean hasPackage = dumpPackage == null;
3236 boolean hasMode = dumpMode < 0;
3237 if (!hasMode && opModes != null) {
3238 for (int opi = 0; !hasMode && opi < opModes.size(); opi++) {
3239 if (opModes.valueAt(opi) == dumpMode) {
3240 hasMode = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003241 }
3242 }
3243 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003244 if (pkgOps != null) {
3245 for (int pkgi = 0;
3246 (!hasOp || !hasPackage || !hasMode) && pkgi < pkgOps.size();
3247 pkgi++) {
3248 Ops ops = pkgOps.valueAt(pkgi);
3249 if (!hasOp && ops != null && ops.indexOfKey(dumpOp) >= 0) {
3250 hasOp = true;
3251 }
3252 if (!hasMode) {
3253 for (int opi = 0; !hasMode && opi < ops.size(); opi++) {
3254 if (ops.valueAt(opi).mode == dumpMode) {
3255 hasMode = true;
3256 }
3257 }
3258 }
3259 if (!hasPackage && dumpPackage.equals(ops.packageName)) {
3260 hasPackage = true;
3261 }
3262 }
3263 }
3264 if (uidState.foregroundOps != null && !hasOp) {
3265 if (uidState.foregroundOps.indexOfKey(dumpOp) > 0) {
3266 hasOp = true;
3267 }
3268 }
3269 if (!hasOp || !hasPackage || !hasMode) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003270 continue;
3271 }
3272 }
Svet Ganov2af57082015-07-30 08:44:20 -07003273
3274 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003275 pw.print(" state=");
3276 pw.println(UID_STATE_NAMES[uidState.state]);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003277 if (uidState.state != uidState.pendingState) {
3278 pw.print(" pendingState=");
3279 pw.println(UID_STATE_NAMES[uidState.pendingState]);
3280 }
3281 if (uidState.pendingStateCommitTime != 0) {
3282 pw.print(" pendingStateCommitTime=");
3283 TimeUtils.formatDuration(uidState.pendingStateCommitTime, nowUptime, pw);
3284 pw.println();
3285 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003286 if (uidState.startNesting != 0) {
3287 pw.print(" startNesting=");
3288 pw.println(uidState.startNesting);
3289 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003290 if (uidState.foregroundOps != null && (dumpMode < 0
3291 || dumpMode == AppOpsManager.MODE_FOREGROUND)) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003292 pw.println(" foregroundOps:");
3293 for (int j = 0; j < uidState.foregroundOps.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003294 if (dumpOp >= 0 && dumpOp != uidState.foregroundOps.keyAt(j)) {
3295 continue;
3296 }
3297 pw.print(" ");
3298 pw.print(AppOpsManager.opToName(uidState.foregroundOps.keyAt(j)));
3299 pw.print(": ");
3300 pw.println(uidState.foregroundOps.valueAt(j) ? "WATCHER" : "SILENT");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003301 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003302 pw.print(" hasForegroundWatchers=");
3303 pw.println(uidState.hasForegroundWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003304 }
Svet Ganovee438d42017-01-19 18:04:38 -08003305 needSep = true;
Svet Ganov2af57082015-07-30 08:44:20 -07003306
Svet Ganov2af57082015-07-30 08:44:20 -07003307 if (opModes != null) {
3308 final int opModeCount = opModes.size();
3309 for (int j = 0; j < opModeCount; j++) {
3310 final int code = opModes.keyAt(j);
3311 final int mode = opModes.valueAt(j);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003312 if (dumpOp >= 0 && dumpOp != code) {
3313 continue;
3314 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003315 if (dumpMode >= 0 && dumpMode != mode) {
3316 continue;
3317 }
Svet Ganov2af57082015-07-30 08:44:20 -07003318 pw.print(" "); pw.print(AppOpsManager.opToName(code));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003319 pw.print(": mode="); pw.println(AppOpsManager.modeToName(mode));
Svet Ganov2af57082015-07-30 08:44:20 -07003320 }
3321 }
3322
Svet Ganov2af57082015-07-30 08:44:20 -07003323 if (pkgOps == null) {
3324 continue;
3325 }
3326
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003327 for (int pkgi = 0; pkgi < pkgOps.size(); pkgi++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003328 final Ops ops = pkgOps.valueAt(pkgi);
3329 if (dumpPackage != null && !dumpPackage.equals(ops.packageName)) {
3330 continue;
3331 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003332 boolean printedPackage = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003333 for (int j=0; j<ops.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003334 final Op op = ops.valueAt(j);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003335 if (dumpOp >= 0 && dumpOp != op.op) {
3336 continue;
3337 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003338 if (dumpMode >= 0 && dumpMode != op.mode) {
3339 continue;
3340 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003341 if (!printedPackage) {
3342 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
3343 printedPackage = true;
3344 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003345 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003346 pw.print(" ("); pw.print(AppOpsManager.modeToName(op.mode));
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003347 final int switchOp = AppOpsManager.opToSwitch(op.op);
3348 if (switchOp != op.op) {
3349 pw.print(" / switch ");
3350 pw.print(AppOpsManager.opToName(switchOp));
3351 final Op switchObj = ops.get(switchOp);
3352 int mode = switchObj != null
3353 ? switchObj.mode : AppOpsManager.opToDefaultMode(switchOp);
3354 pw.print("="); pw.print(AppOpsManager.modeToName(mode));
3355 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003356 pw.println("): ");
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003357 dumpTimesLocked(pw,
3358 " Access: ",
3359 " ", op.time, now, sdf, date);
3360 dumpTimesLocked(pw,
3361 " Reject: ",
3362 " ", op.rejectTime, now, sdf, date);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003363 if (op.duration == -1) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003364 pw.print(" Running start at: ");
3365 TimeUtils.formatDuration(nowElapsed-op.startRealtime, pw);
3366 pw.println();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08003367 } else if (op.duration != 0) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003368 pw.print(" duration=");
3369 TimeUtils.formatDuration(op.duration, pw);
3370 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003371 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003372 if (op.startNesting != 0) {
3373 pw.print(" startNesting=");
3374 pw.println(op.startNesting);
3375 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003376 }
3377 }
3378 }
Svet Ganovee438d42017-01-19 18:04:38 -08003379 if (needSep) {
3380 pw.println();
3381 }
3382
3383 final int userRestrictionCount = mOpUserRestrictions.size();
3384 for (int i = 0; i < userRestrictionCount; i++) {
3385 IBinder token = mOpUserRestrictions.keyAt(i);
3386 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
3387 pw.println(" User restrictions for token " + token + ":");
3388
3389 final int restrictionCount = restrictionState.perUserRestrictions != null
3390 ? restrictionState.perUserRestrictions.size() : 0;
3391 if (restrictionCount > 0) {
3392 pw.println(" Restricted ops:");
3393 for (int j = 0; j < restrictionCount; j++) {
3394 int userId = restrictionState.perUserRestrictions.keyAt(j);
3395 boolean[] restrictedOps = restrictionState.perUserRestrictions.valueAt(j);
3396 if (restrictedOps == null) {
3397 continue;
3398 }
3399 StringBuilder restrictedOpsValue = new StringBuilder();
3400 restrictedOpsValue.append("[");
3401 final int restrictedOpCount = restrictedOps.length;
3402 for (int k = 0; k < restrictedOpCount; k++) {
3403 if (restrictedOps[k]) {
3404 if (restrictedOpsValue.length() > 1) {
3405 restrictedOpsValue.append(", ");
3406 }
3407 restrictedOpsValue.append(AppOpsManager.opToName(k));
3408 }
3409 }
3410 restrictedOpsValue.append("]");
3411 pw.print(" "); pw.print("user: "); pw.print(userId);
3412 pw.print(" restricted ops: "); pw.println(restrictedOpsValue);
3413 }
3414 }
3415
3416 final int excludedPackageCount = restrictionState.perUserExcludedPackages != null
3417 ? restrictionState.perUserExcludedPackages.size() : 0;
3418 if (excludedPackageCount > 0) {
3419 pw.println(" Excluded packages:");
3420 for (int j = 0; j < excludedPackageCount; j++) {
3421 int userId = restrictionState.perUserExcludedPackages.keyAt(j);
3422 String[] packageNames = restrictionState.perUserExcludedPackages.valueAt(j);
3423 pw.print(" "); pw.print("user: "); pw.print(userId);
3424 pw.print(" packages: "); pw.println(Arrays.toString(packageNames));
3425 }
3426 }
3427 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003428 }
3429 }
John Spurlock1af30c72014-03-10 08:33:35 -04003430
3431 private static final class Restriction {
3432 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
3433 int mode;
3434 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
3435 }
Jason Monk62062992014-05-06 09:55:28 -04003436
3437 @Override
Svet Ganov9cea80cd2016-02-16 11:47:00 -08003438 public void setUserRestrictions(Bundle restrictions, IBinder token, int userHandle) {
Jason Monk62062992014-05-06 09:55:28 -04003439 checkSystemUid("setUserRestrictions");
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00003440 Preconditions.checkNotNull(restrictions);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08003441 Preconditions.checkNotNull(token);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07003442 for (int i = 0; i < AppOpsManager._NUM_OP; i++) {
Jason Monk62062992014-05-06 09:55:28 -04003443 String restriction = AppOpsManager.opToRestriction(i);
Suprabh Shukla64e0dcb2016-05-24 16:23:11 -07003444 if (restriction != null) {
3445 setUserRestrictionNoCheck(i, restrictions.getBoolean(restriction, false), token,
3446 userHandle, null);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07003447 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08003448 }
3449 }
3450
3451 @Override
Ruben Brunk29931bc2016-03-11 00:24:26 -08003452 public void setUserRestriction(int code, boolean restricted, IBinder token, int userHandle,
3453 String[] exceptionPackages) {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08003454 if (Binder.getCallingPid() != Process.myPid()) {
3455 mContext.enforcePermission(Manifest.permission.MANAGE_APP_OPS_RESTRICTIONS,
3456 Binder.getCallingPid(), Binder.getCallingUid(), null);
3457 }
3458 if (userHandle != UserHandle.getCallingUserId()) {
3459 if (mContext.checkCallingOrSelfPermission(Manifest.permission
3460 .INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
3461 && mContext.checkCallingOrSelfPermission(Manifest.permission
3462 .INTERACT_ACROSS_USERS) != PackageManager.PERMISSION_GRANTED) {
3463 throw new SecurityException("Need INTERACT_ACROSS_USERS_FULL or"
3464 + " INTERACT_ACROSS_USERS to interact cross user ");
Jason Monk62062992014-05-06 09:55:28 -04003465 }
3466 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08003467 verifyIncomingOp(code);
3468 Preconditions.checkNotNull(token);
Ruben Brunk29931bc2016-03-11 00:24:26 -08003469 setUserRestrictionNoCheck(code, restricted, token, userHandle, exceptionPackages);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08003470 }
3471
3472 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
Ruben Brunk29931bc2016-03-11 00:24:26 -08003473 int userHandle, String[] exceptionPackages) {
Svet Ganov442ed572016-08-17 17:29:43 -07003474 synchronized (AppOpsService.this) {
3475 ClientRestrictionState restrictionState = mOpUserRestrictions.get(token);
3476
3477 if (restrictionState == null) {
3478 try {
3479 restrictionState = new ClientRestrictionState(token);
3480 } catch (RemoteException e) {
3481 return;
3482 }
3483 mOpUserRestrictions.put(token, restrictionState);
Ruben Brunk29931bc2016-03-11 00:24:26 -08003484 }
Svet Ganov442ed572016-08-17 17:29:43 -07003485
3486 if (restrictionState.setRestriction(code, restricted, exceptionPackages, userHandle)) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003487 mHandler.sendMessage(PooledLambda.obtainMessage(
Svet Ganov3a95f832018-03-23 17:44:30 -07003488 AppOpsService::notifyWatchersOfChange, this, code, UID_ANY));
Svet Ganov442ed572016-08-17 17:29:43 -07003489 }
3490
3491 if (restrictionState.isDefault()) {
3492 mOpUserRestrictions.remove(token);
3493 restrictionState.destroy();
3494 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08003495 }
Julia Reynoldsbb21c252016-04-05 16:01:49 -04003496 }
3497
Svet Ganov3a95f832018-03-23 17:44:30 -07003498 private void notifyWatchersOfChange(int code, int uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003499 final ArraySet<ModeCallback> clonedCallbacks;
Svet Ganov9cea80cd2016-02-16 11:47:00 -08003500 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003501 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08003502 if (callbacks == null) {
3503 return;
3504 }
Dianne Hackborn68d76552017-02-27 15:32:03 -08003505 clonedCallbacks = new ArraySet<>(callbacks);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08003506 }
3507
Svet Ganov3a95f832018-03-23 17:44:30 -07003508 notifyOpChanged(clonedCallbacks, code, uid, null);
Jason Monk62062992014-05-06 09:55:28 -04003509 }
3510
3511 @Override
3512 public void removeUser(int userHandle) throws RemoteException {
3513 checkSystemUid("removeUser");
Svet Ganov442ed572016-08-17 17:29:43 -07003514 synchronized (AppOpsService.this) {
3515 final int tokenCount = mOpUserRestrictions.size();
3516 for (int i = tokenCount - 1; i >= 0; i--) {
3517 ClientRestrictionState opRestrictions = mOpUserRestrictions.valueAt(i);
3518 opRestrictions.removeUser(userHandle);
3519 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07003520 removeUidsForUserLocked(userHandle);
3521 }
3522 }
3523
Jeff Sharkey35e46d22017-06-09 10:01:20 -06003524 @Override
3525 public boolean isOperationActive(int code, int uid, String packageName) {
Svet Ganovf7b47252018-02-26 11:11:27 -08003526 if (Binder.getCallingUid() != uid) {
3527 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
3528 != PackageManager.PERMISSION_GRANTED) {
3529 return false;
3530 }
3531 }
Jeff Sharkey35e46d22017-06-09 10:01:20 -06003532 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003533 final String resolvedPackageName = resolvePackageName(uid, packageName);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06003534 if (resolvedPackageName == null) {
3535 return false;
3536 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003537 synchronized (AppOpsService.this) {
Jeff Sharkey35e46d22017-06-09 10:01:20 -06003538 for (int i = mClients.size() - 1; i >= 0; i--) {
3539 final ClientState client = mClients.valueAt(i);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06003540 for (int j = client.mStartedOps.size() - 1; j >= 0; j--) {
3541 final Op op = client.mStartedOps.get(j);
3542 if (op.op == code && op.uid == uid) return true;
3543 }
3544 }
3545 }
3546 return false;
3547 }
3548
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07003549 private void removeUidsForUserLocked(int userHandle) {
3550 for (int i = mUidStates.size() - 1; i >= 0; --i) {
3551 final int uid = mUidStates.keyAt(i);
3552 if (UserHandle.getUserId(uid) == userHandle) {
3553 mUidStates.removeAt(i);
3554 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08003555 }
3556 }
3557
Jason Monk62062992014-05-06 09:55:28 -04003558 private void checkSystemUid(String function) {
3559 int uid = Binder.getCallingUid();
3560 if (uid != Process.SYSTEM_UID) {
3561 throw new SecurityException(function + " must by called by the system");
3562 }
3563 }
3564
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00003565 private static String resolvePackageName(int uid, String packageName) {
Svet Ganov82f09bc2018-01-12 22:08:40 -08003566 if (uid == Process.ROOT_UID) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00003567 return "root";
3568 } else if (uid == Process.SHELL_UID) {
3569 return "com.android.shell";
Svet Ganov82f09bc2018-01-12 22:08:40 -08003570 } else if (uid == Process.MEDIA_UID) {
3571 return "media";
3572 } else if (uid == Process.AUDIOSERVER_UID) {
3573 return "audioserver";
3574 } else if (uid == Process.CAMERASERVER_UID) {
3575 return "cameraserver";
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00003576 } else if (uid == Process.SYSTEM_UID && packageName == null) {
3577 return "android";
3578 }
3579 return packageName;
3580 }
3581
Svet Ganov82f09bc2018-01-12 22:08:40 -08003582 private static int resolveUid(String packageName) {
3583 if (packageName == null) {
3584 return -1;
3585 }
3586 switch (packageName) {
3587 case "root":
3588 return Process.ROOT_UID;
3589 case "shell":
3590 return Process.SHELL_UID;
3591 case "media":
3592 return Process.MEDIA_UID;
3593 case "audioserver":
3594 return Process.AUDIOSERVER_UID;
3595 case "cameraserver":
3596 return Process.CAMERASERVER_UID;
3597 }
3598 return -1;
3599 }
3600
Svet Ganov2af57082015-07-30 08:44:20 -07003601 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07003602 String[] packageNames = null;
Svet Ganov2af57082015-07-30 08:44:20 -07003603 try {
riddle_hsu40b300f2015-11-23 13:22:03 +08003604 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -07003605 } catch (RemoteException e) {
3606 /* ignore - local call */
3607 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07003608 if (packageNames == null) {
3609 return EmptyArray.STRING;
3610 }
3611 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07003612 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07003613
3614 private final class ClientRestrictionState implements DeathRecipient {
3615 private final IBinder token;
3616 SparseArray<boolean[]> perUserRestrictions;
3617 SparseArray<String[]> perUserExcludedPackages;
3618
3619 public ClientRestrictionState(IBinder token)
3620 throws RemoteException {
3621 token.linkToDeath(this, 0);
3622 this.token = token;
3623 }
3624
3625 public boolean setRestriction(int code, boolean restricted,
3626 String[] excludedPackages, int userId) {
3627 boolean changed = false;
3628
3629 if (perUserRestrictions == null && restricted) {
3630 perUserRestrictions = new SparseArray<>();
3631 }
3632
Philip P. Moltmanne683f192017-06-23 14:05:04 -07003633 int[] users;
3634 if (userId == UserHandle.USER_ALL) {
3635 List<UserInfo> liveUsers = UserManager.get(mContext).getUsers(false);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07003636
Philip P. Moltmanne683f192017-06-23 14:05:04 -07003637 users = new int[liveUsers.size()];
3638 for (int i = 0; i < liveUsers.size(); i++) {
3639 users[i] = liveUsers.get(i).id;
3640 }
3641 } else {
3642 users = new int[]{userId};
3643 }
3644
3645 if (perUserRestrictions != null) {
3646 int numUsers = users.length;
3647
3648 for (int i = 0; i < numUsers; i++) {
3649 int thisUserId = users[i];
3650
3651 boolean[] userRestrictions = perUserRestrictions.get(thisUserId);
3652 if (userRestrictions == null && restricted) {
3653 userRestrictions = new boolean[AppOpsManager._NUM_OP];
3654 perUserRestrictions.put(thisUserId, userRestrictions);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07003655 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07003656 if (userRestrictions != null && userRestrictions[code] != restricted) {
3657 userRestrictions[code] = restricted;
3658 if (!restricted && isDefault(userRestrictions)) {
3659 perUserRestrictions.remove(thisUserId);
3660 userRestrictions = null;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07003661 }
3662 changed = true;
3663 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07003664
3665 if (userRestrictions != null) {
3666 final boolean noExcludedPackages = ArrayUtils.isEmpty(excludedPackages);
3667 if (perUserExcludedPackages == null && !noExcludedPackages) {
3668 perUserExcludedPackages = new SparseArray<>();
3669 }
3670 if (perUserExcludedPackages != null && !Arrays.equals(excludedPackages,
3671 perUserExcludedPackages.get(thisUserId))) {
3672 if (noExcludedPackages) {
3673 perUserExcludedPackages.remove(thisUserId);
3674 if (perUserExcludedPackages.size() <= 0) {
3675 perUserExcludedPackages = null;
3676 }
3677 } else {
3678 perUserExcludedPackages.put(thisUserId, excludedPackages);
3679 }
3680 changed = true;
3681 }
3682 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07003683 }
3684 }
3685
3686 return changed;
3687 }
3688
3689 public boolean hasRestriction(int restriction, String packageName, int userId) {
3690 if (perUserRestrictions == null) {
3691 return false;
3692 }
3693 boolean[] restrictions = perUserRestrictions.get(userId);
3694 if (restrictions == null) {
3695 return false;
3696 }
3697 if (!restrictions[restriction]) {
3698 return false;
3699 }
3700 if (perUserExcludedPackages == null) {
3701 return true;
3702 }
3703 String[] perUserExclusions = perUserExcludedPackages.get(userId);
3704 if (perUserExclusions == null) {
3705 return true;
3706 }
3707 return !ArrayUtils.contains(perUserExclusions, packageName);
3708 }
3709
3710 public void removeUser(int userId) {
3711 if (perUserExcludedPackages != null) {
3712 perUserExcludedPackages.remove(userId);
3713 if (perUserExcludedPackages.size() <= 0) {
3714 perUserExcludedPackages = null;
3715 }
3716 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07003717 if (perUserRestrictions != null) {
3718 perUserRestrictions.remove(userId);
3719 if (perUserRestrictions.size() <= 0) {
3720 perUserRestrictions = null;
3721 }
3722 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07003723 }
3724
3725 public boolean isDefault() {
3726 return perUserRestrictions == null || perUserRestrictions.size() <= 0;
3727 }
3728
3729 @Override
3730 public void binderDied() {
3731 synchronized (AppOpsService.this) {
3732 mOpUserRestrictions.remove(token);
3733 if (perUserRestrictions == null) {
3734 return;
3735 }
3736 final int userCount = perUserRestrictions.size();
3737 for (int i = 0; i < userCount; i++) {
3738 final boolean[] restrictions = perUserRestrictions.valueAt(i);
3739 final int restrictionCount = restrictions.length;
3740 for (int j = 0; j < restrictionCount; j++) {
3741 if (restrictions[j]) {
3742 final int changedCode = j;
Svet Ganov3a95f832018-03-23 17:44:30 -07003743 mHandler.post(() -> notifyWatchersOfChange(changedCode, UID_ANY));
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07003744 }
3745 }
3746 }
3747 destroy();
3748 }
3749 }
3750
3751 public void destroy() {
3752 token.unlinkToDeath(this, 0);
3753 }
3754
3755 private boolean isDefault(boolean[] array) {
3756 if (ArrayUtils.isEmpty(array)) {
3757 return true;
3758 }
3759 for (boolean value : array) {
3760 if (value) {
3761 return false;
3762 }
3763 }
3764 return true;
3765 }
3766 }
Dianne Hackbornd5254412018-05-11 18:02:58 -07003767
3768 private final class AppOpsManagerInternalImpl extends AppOpsManagerInternal {
3769 @Override public void setDeviceAndProfileOwners(SparseIntArray owners) {
3770 synchronized (AppOpsService.this) {
3771 mProfileOwners = owners;
3772 }
3773 }
3774 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003775}