blob: 10b67c1047cf3bc0142a86ad05f2b94e3ef5ba30 [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
Svet Ganov8455ba22019-01-02 13:05:56 -080017package com.android.server.appop;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080018
Svet Ganovaf189e32019-02-15 18:45:29 -080019import static android.app.AppOpsManager.MAX_PRIORITY_UID_STATE;
20import static android.app.AppOpsManager.MIN_PRIORITY_UID_STATE;
21import static android.app.AppOpsManager.OP_FLAGS_ALL;
Svet Ganov8455ba22019-01-02 13:05:56 -080022import static android.app.AppOpsManager.OP_NONE;
Philip P. Moltmanndde07852019-01-25 16:42:36 -080023import static android.app.AppOpsManager.OP_PLAY_AUDIO;
Hai Zhang2b98fb32018-09-21 15:18:46 -070024import static android.app.AppOpsManager.UID_STATE_BACKGROUND;
25import static android.app.AppOpsManager.UID_STATE_CACHED;
26import static android.app.AppOpsManager.UID_STATE_FOREGROUND;
27import static android.app.AppOpsManager.UID_STATE_FOREGROUND_SERVICE;
Amith Yamasania0a30a12019-01-22 11:38:06 -080028import static android.app.AppOpsManager.UID_STATE_FOREGROUND_SERVICE_LOCATION;
Svet Ganovaf189e32019-02-15 18:45:29 -080029import static android.app.AppOpsManager.UID_STATE_MAX_LAST_NON_RESTRICTED;
Hai Zhang2b98fb32018-09-21 15:18:46 -070030import static android.app.AppOpsManager.UID_STATE_PERSISTENT;
31import static android.app.AppOpsManager.UID_STATE_TOP;
Eugene Suslae4ee2c22018-11-05 12:23:30 -080032import static android.app.AppOpsManager.modeToName;
33import static android.app.AppOpsManager.opToName;
Svet Ganovaf189e32019-02-15 18:45:29 -080034import static android.app.AppOpsManager.resolveFirstUnrestrictedUidState;
Hai Zhang2b98fb32018-09-21 15:18:46 -070035
Philip P. Moltmanne683f192017-06-23 14:05:04 -070036import android.Manifest;
Svet Ganovad0a49b2018-10-29 10:07:08 -070037import android.annotation.NonNull;
38import android.annotation.Nullable;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070039import android.app.ActivityManager;
40import android.app.ActivityThread;
41import android.app.AppGlobals;
42import android.app.AppOpsManager;
Svet Ganov8455ba22019-01-02 13:05:56 -080043import android.app.AppOpsManager.HistoricalOps;
Svet Ganov23c88db2019-01-22 20:38:11 -080044import android.app.AppOpsManager.HistoricalOpsRequest;
Svet Ganovaf189e32019-02-15 18:45:29 -080045import android.app.AppOpsManager.Mode;
46import android.app.AppOpsManager.OpEntry;
47import android.app.AppOpsManager.OpFlags;
Dianne Hackbornd5254412018-05-11 18:02:58 -070048import android.app.AppOpsManagerInternal;
Svet Ganovd873ae62018-06-25 16:39:23 -070049import android.app.AppOpsManagerInternal.CheckOpsDelegate;
Suprabh Shukla3017fe42018-11-08 19:00:01 -080050import android.content.BroadcastReceiver;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070051import android.content.ContentResolver;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070052import android.content.Context;
Suprabh Shukla3017fe42018-11-08 19:00:01 -080053import android.content.Intent;
54import android.content.IntentFilter;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070055import android.content.pm.ApplicationInfo;
56import android.content.pm.IPackageManager;
57import android.content.pm.PackageManager;
58import android.content.pm.PackageManagerInternal;
59import android.content.pm.UserInfo;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070060import android.database.ContentObserver;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070061import android.media.AudioAttributes;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070062import android.net.Uri;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070063import android.os.AsyncTask;
64import android.os.Binder;
65import android.os.Bundle;
66import android.os.Handler;
67import android.os.IBinder;
68import android.os.Process;
Svet Ganov8455ba22019-01-02 13:05:56 -080069import android.os.RemoteCallback;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070070import android.os.RemoteException;
71import android.os.ResultReceiver;
72import android.os.ServiceManager;
73import android.os.ShellCallback;
74import android.os.ShellCommand;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -070075import android.os.SystemClock;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070076import android.os.UserHandle;
77import android.os.UserManager;
Sudheer Shanka98cb3f02018-08-17 16:10:29 -070078import android.os.storage.StorageManager;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070079import android.os.storage.StorageManagerInternal;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070080import android.provider.Settings;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070081import android.util.ArrayMap;
82import android.util.ArraySet;
83import android.util.AtomicFile;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070084import android.util.KeyValueListParser;
Svet Ganovaf189e32019-02-15 18:45:29 -080085import android.util.LongSparseArray;
86import android.util.LongSparseLongArray;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070087import android.util.Slog;
88import android.util.SparseArray;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -070089import android.util.SparseBooleanArray;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070090import android.util.SparseIntArray;
91import android.util.TimeUtils;
92import android.util.Xml;
93
Todd Kennedy556efba2018-11-15 07:43:55 -080094import com.android.internal.annotations.GuardedBy;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070095import com.android.internal.annotations.VisibleForTesting;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -080096import com.android.internal.app.IAppOpsActiveCallback;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070097import com.android.internal.app.IAppOpsCallback;
Svet Ganovb3d2ae22018-12-17 22:06:15 -080098import com.android.internal.app.IAppOpsNotedCallback;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070099import com.android.internal.app.IAppOpsService;
100import com.android.internal.os.Zygote;
101import com.android.internal.util.ArrayUtils;
102import com.android.internal.util.DumpUtils;
103import com.android.internal.util.FastXmlSerializer;
104import com.android.internal.util.Preconditions;
105import com.android.internal.util.XmlUtils;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800106import com.android.internal.util.function.pooled.PooledLambda;
Svet Ganov8455ba22019-01-02 13:05:56 -0800107import com.android.server.LocalServices;
108import com.android.server.LockGuard;
Philip P. Moltmanndde07852019-01-25 16:42:36 -0800109
Philip P. Moltmanne683f192017-06-23 14:05:04 -0700110import libcore.util.EmptyArray;
111
112import org.xmlpull.v1.XmlPullParser;
113import org.xmlpull.v1.XmlPullParserException;
114import org.xmlpull.v1.XmlSerializer;
115
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800116import java.io.File;
117import java.io.FileDescriptor;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800118import java.io.FileInputStream;
119import java.io.FileNotFoundException;
120import java.io.FileOutputStream;
121import java.io.IOException;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800122import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100123import java.nio.charset.StandardCharsets;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700124import java.text.SimpleDateFormat;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800125import java.util.ArrayList;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -0700126import java.util.Arrays;
Svetoslav215b44a2015-08-04 19:03:40 -0700127import java.util.Collections;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700128import java.util.Date;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800129import java.util.HashMap;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800130import java.util.Iterator;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800131import java.util.List;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700132import java.util.Map;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800133
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800134public class AppOpsService extends IAppOpsService.Stub {
135 static final String TAG = "AppOps";
Dianne Hackborn35654b62013-01-14 17:38:02 -0800136 static final boolean DEBUG = false;
137
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700138 private static final int NO_VERSION = -1;
139 /** Increment by one every time and add the corresponding upgrade logic in
140 * {@link #upgradeLocked(int)} below. The first version was 1 */
141 private static final int CURRENT_VERSION = 1;
142
Dianne Hackborn35654b62013-01-14 17:38:02 -0800143 // Write at most every 30 minutes.
144 static final long WRITE_DELAY = DEBUG ? 1000 : 30*60*1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800145
Svet Ganov3a95f832018-03-23 17:44:30 -0700146 // Constant meaning that any UID should be matched when dispatching callbacks
147 private static final int UID_ANY = -2;
148
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700149 // Map from process states to the uid states we track.
150 private static final int[] PROCESS_STATE_TO_UID_STATE = new int[] {
151 UID_STATE_PERSISTENT, // ActivityManager.PROCESS_STATE_PERSISTENT
152 UID_STATE_PERSISTENT, // ActivityManager.PROCESS_STATE_PERSISTENT_UI
153 UID_STATE_TOP, // ActivityManager.PROCESS_STATE_TOP
Amith Yamasania0a30a12019-01-22 11:38:06 -0800154 UID_STATE_FOREGROUND_SERVICE_LOCATION,
155 // ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE_LOCATION
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700156 UID_STATE_FOREGROUND_SERVICE, // ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
157 UID_STATE_FOREGROUND, // ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
158 UID_STATE_FOREGROUND, // ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND
159 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND
160 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_TRANSIENT_BACKGROUND
161 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_BACKUP
162 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_SERVICE
163 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_RECEIVER
164 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_TOP_SLEEPING
165 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_HEAVY_WEIGHT
166 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_HOME
167 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_LAST_ACTIVITY
168 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY
169 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT
170 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_RECENT
171 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_EMPTY
172 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_NONEXISTENT
173 };
174
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800175 Context mContext;
176 final AtomicFile mFile;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800177 final Handler mHandler;
178
Dianne Hackbornd5254412018-05-11 18:02:58 -0700179 private final AppOpsManagerInternalImpl mAppOpsManagerInternal
180 = new AppOpsManagerInternalImpl();
181
Dianne Hackborn35654b62013-01-14 17:38:02 -0800182 boolean mWriteScheduled;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800183 boolean mFastWriteScheduled;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800184 final Runnable mWriteRunner = new Runnable() {
185 public void run() {
186 synchronized (AppOpsService.this) {
187 mWriteScheduled = false;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800188 mFastWriteScheduled = false;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800189 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
190 @Override protected Void doInBackground(Void... params) {
191 writeState();
192 return null;
193 }
194 };
195 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
196 }
197 }
198 };
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800199
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700200 @VisibleForTesting
201 final SparseArray<UidState> mUidStates = new SparseArray<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800202
Svet Ganov8455ba22019-01-02 13:05:56 -0800203 private final HistoricalRegistry mHistoricalRegistry = new HistoricalRegistry(this);
204
Dianne Hackborn9fb93502018-06-18 12:29:44 -0700205 long mLastRealtime;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700206
Ruben Brunk29931bc2016-03-11 00:24:26 -0800207 /*
208 * These are app op restrictions imposed per user from various parties.
Ruben Brunk29931bc2016-03-11 00:24:26 -0800209 */
Svetoslav Ganova8bbd762016-05-13 17:08:16 -0700210 private final ArrayMap<IBinder, ClientRestrictionState> mOpUserRestrictions = new ArrayMap<>();
Jason Monk62062992014-05-06 09:55:28 -0400211
Dianne Hackbornd5254412018-05-11 18:02:58 -0700212 SparseIntArray mProfileOwners;
213
Todd Kennedy556efba2018-11-15 07:43:55 -0800214 @GuardedBy("this")
Svet Ganovd873ae62018-06-25 16:39:23 -0700215 private CheckOpsDelegate mCheckOpsDelegate;
216
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700217 /**
218 * All times are in milliseconds. These constants are kept synchronized with the system
219 * global Settings. Any access to this class or its fields should be done while
220 * holding the AppOpsService lock.
221 */
222 private final class Constants extends ContentObserver {
223 // Key names stored in the settings value.
Dianne Hackborne93ab412018-05-14 17:52:30 -0700224 private static final String KEY_TOP_STATE_SETTLE_TIME = "top_state_settle_time";
225 private static final String KEY_FG_SERVICE_STATE_SETTLE_TIME
226 = "fg_service_state_settle_time";
227 private static final String KEY_BG_STATE_SETTLE_TIME = "bg_state_settle_time";
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700228
229 /**
Dianne Hackborne93ab412018-05-14 17:52:30 -0700230 * How long we want for a drop in uid state from top to settle before applying it.
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700231 * @see Settings.Global#APP_OPS_CONSTANTS
Dianne Hackborne93ab412018-05-14 17:52:30 -0700232 * @see #KEY_TOP_STATE_SETTLE_TIME
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700233 */
Dianne Hackborne93ab412018-05-14 17:52:30 -0700234 public long TOP_STATE_SETTLE_TIME;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700235
Dianne Hackborne93ab412018-05-14 17:52:30 -0700236 /**
237 * How long we want for a drop in uid state from foreground to settle before applying it.
238 * @see Settings.Global#APP_OPS_CONSTANTS
239 * @see #KEY_FG_SERVICE_STATE_SETTLE_TIME
240 */
241 public long FG_SERVICE_STATE_SETTLE_TIME;
242
243 /**
244 * How long we want for a drop in uid state from background to settle before applying it.
245 * @see Settings.Global#APP_OPS_CONSTANTS
246 * @see #KEY_BG_STATE_SETTLE_TIME
247 */
248 public long BG_STATE_SETTLE_TIME;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700249
250 private final KeyValueListParser mParser = new KeyValueListParser(',');
251 private ContentResolver mResolver;
252
253 public Constants(Handler handler) {
254 super(handler);
255 updateConstants();
256 }
257
258 public void startMonitoring(ContentResolver resolver) {
259 mResolver = resolver;
260 mResolver.registerContentObserver(
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700261 Settings.Global.getUriFor(Settings.Global.APP_OPS_CONSTANTS),
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700262 false, this);
263 updateConstants();
264 }
265
266 @Override
267 public void onChange(boolean selfChange, Uri uri) {
268 updateConstants();
269 }
270
271 private void updateConstants() {
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700272 String value = mResolver != null ? Settings.Global.getString(mResolver,
273 Settings.Global.APP_OPS_CONSTANTS) : "";
274
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700275 synchronized (AppOpsService.this) {
276 try {
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700277 mParser.setString(value);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700278 } catch (IllegalArgumentException e) {
279 // Failed to parse the settings string, log this and move on
280 // with defaults.
281 Slog.e(TAG, "Bad app ops settings", e);
282 }
Dianne Hackborne93ab412018-05-14 17:52:30 -0700283 TOP_STATE_SETTLE_TIME = mParser.getDurationMillis(
284 KEY_TOP_STATE_SETTLE_TIME, 30 * 1000L);
285 FG_SERVICE_STATE_SETTLE_TIME = mParser.getDurationMillis(
286 KEY_FG_SERVICE_STATE_SETTLE_TIME, 10 * 1000L);
287 BG_STATE_SETTLE_TIME = mParser.getDurationMillis(
288 KEY_BG_STATE_SETTLE_TIME, 1 * 1000L);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700289 }
290 }
291
292 void dump(PrintWriter pw) {
293 pw.println(" Settings:");
294
Dianne Hackborne93ab412018-05-14 17:52:30 -0700295 pw.print(" "); pw.print(KEY_TOP_STATE_SETTLE_TIME); pw.print("=");
296 TimeUtils.formatDuration(TOP_STATE_SETTLE_TIME, pw);
Dianne Hackbornb94d82f2018-05-16 17:03:01 -0700297 pw.println();
Dianne Hackborne93ab412018-05-14 17:52:30 -0700298 pw.print(" "); pw.print(KEY_FG_SERVICE_STATE_SETTLE_TIME); pw.print("=");
299 TimeUtils.formatDuration(FG_SERVICE_STATE_SETTLE_TIME, pw);
Dianne Hackbornb94d82f2018-05-16 17:03:01 -0700300 pw.println();
Dianne Hackborne93ab412018-05-14 17:52:30 -0700301 pw.print(" "); pw.print(KEY_BG_STATE_SETTLE_TIME); pw.print("=");
302 TimeUtils.formatDuration(BG_STATE_SETTLE_TIME, pw);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700303 pw.println();
304 }
305 }
306
307 private final Constants mConstants;
308
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700309 @VisibleForTesting
310 static final class UidState {
Svet Ganov2af57082015-07-30 08:44:20 -0700311 public final int uid;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700312
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700313 public int state = UID_STATE_CACHED;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700314 public int pendingState = UID_STATE_CACHED;
315 public long pendingStateCommitTime;
316
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700317 public int startNesting;
Svet Ganov2af57082015-07-30 08:44:20 -0700318 public ArrayMap<String, Ops> pkgOps;
319 public SparseIntArray opModes;
320
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700321 // true indicates there is an interested observer, false there isn't but it has such an op
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700322 public SparseBooleanArray foregroundOps;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700323 public boolean hasForegroundWatchers;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700324
Svet Ganov2af57082015-07-30 08:44:20 -0700325 public UidState(int uid) {
326 this.uid = uid;
327 }
328
329 public void clear() {
330 pkgOps = null;
331 opModes = null;
332 }
333
334 public boolean isDefault() {
335 return (pkgOps == null || pkgOps.isEmpty())
Svet Ganovaf189e32019-02-15 18:45:29 -0800336 && (opModes == null || opModes.size() <= 0)
337 && (state == UID_STATE_CACHED
338 && (pendingState == UID_STATE_CACHED));
Svet Ganov2af57082015-07-30 08:44:20 -0700339 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700340
Svet Ganovaf189e32019-02-15 18:45:29 -0800341 int evalMode(int op, int mode) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700342 if (mode == AppOpsManager.MODE_FOREGROUND) {
Svet Ganovaf189e32019-02-15 18:45:29 -0800343 return state <= AppOpsManager.resolveLastRestrictedUidState(op)
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700344 ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED;
345 }
346 return mode;
347 }
348
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700349 private void evalForegroundWatchers(int op, SparseArray<ArraySet<ModeCallback>> watchers,
350 SparseBooleanArray which) {
351 boolean curValue = which.get(op, false);
352 ArraySet<ModeCallback> callbacks = watchers.get(op);
353 if (callbacks != null) {
354 for (int cbi = callbacks.size() - 1; !curValue && cbi >= 0; cbi--) {
355 if ((callbacks.valueAt(cbi).mFlags
356 & AppOpsManager.WATCH_FOREGROUND_CHANGES) != 0) {
357 hasForegroundWatchers = true;
358 curValue = true;
359 }
360 }
361 }
362 which.put(op, curValue);
363 }
364
365 public void evalForegroundOps(SparseArray<ArraySet<ModeCallback>> watchers) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700366 SparseBooleanArray which = null;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700367 hasForegroundWatchers = false;
368 if (opModes != null) {
369 for (int i = opModes.size() - 1; i >= 0; i--) {
370 if (opModes.valueAt(i) == AppOpsManager.MODE_FOREGROUND) {
371 if (which == null) {
372 which = new SparseBooleanArray();
373 }
374 evalForegroundWatchers(opModes.keyAt(i), watchers, which);
375 }
376 }
377 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700378 if (pkgOps != null) {
379 for (int i = pkgOps.size() - 1; i >= 0; i--) {
380 Ops ops = pkgOps.valueAt(i);
381 for (int j = ops.size() - 1; j >= 0; j--) {
382 if (ops.valueAt(j).mode == AppOpsManager.MODE_FOREGROUND) {
383 if (which == null) {
384 which = new SparseBooleanArray();
385 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700386 evalForegroundWatchers(ops.keyAt(j), watchers, which);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700387 }
388 }
389 }
390 }
391 foregroundOps = which;
392 }
Svet Ganov2af57082015-07-30 08:44:20 -0700393 }
394
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700395 final static class Ops extends SparseArray<Op> {
396 final String packageName;
397 final UidState uidState;
398 final boolean isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800399
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700400 Ops(String _packageName, UidState _uidState, boolean _isPrivileged) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800401 packageName = _packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700402 uidState = _uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400403 isPrivileged = _isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800404 }
405 }
406
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700407 final static class Op {
Svet Ganovaf189e32019-02-15 18:45:29 -0800408 int op;
409 boolean running;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700410 final UidState uidState;
Svet Ganovaf189e32019-02-15 18:45:29 -0800411 final @NonNull String packageName;
412
413 private @Mode int mode;
414 private @Nullable LongSparseLongArray mAccessTimes;
415 private @Nullable LongSparseLongArray mRejectTimes;
416 private @Nullable LongSparseLongArray mDurations;
417 private @Nullable LongSparseLongArray mProxyUids;
418 private @Nullable LongSparseArray<String> mProxyPackageNames;
419
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700420 int startNesting;
421 long startRealtime;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800422
Svet Ganovaf189e32019-02-15 18:45:29 -0800423 Op(UidState uidState, String packageName, int op) {
424 this.op = op;
425 this.uidState = uidState;
426 this.packageName = packageName;
427 this.mode = AppOpsManager.opToDefaultMode(op);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700428 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700429
430 int getMode() {
Svet Ganovaf189e32019-02-15 18:45:29 -0800431 return mode;
432 }
433
434 int evalMode() {
435 return uidState.evalMode(op, mode);
436 }
437
438 /** @hide */
439 public void accessed(long time, int proxyUid, @Nullable String proxyPackageName,
440 @AppOpsManager.UidState int uidState, @OpFlags int flags) {
441 final long key = AppOpsManager.makeKey(uidState, flags);
442 if (mAccessTimes == null) {
443 mAccessTimes = new LongSparseLongArray();
444 }
445 mAccessTimes.put(key, time);
446 updateProxyState(key, proxyUid, proxyPackageName);
447 if (mDurations != null) {
448 mDurations.delete(key);
449 }
450 }
451
452 /** @hide */
453 public void rejected(long time, int proxyUid, @Nullable String proxyPackageName,
454 @AppOpsManager.UidState int uidState, @OpFlags int flags) {
455 final long key = AppOpsManager.makeKey(uidState, flags);
456 if (mRejectTimes == null) {
457 mRejectTimes = new LongSparseLongArray();
458 }
459 mRejectTimes.put(key, time);
460 updateProxyState(key, proxyUid, proxyPackageName);
461 if (mDurations != null) {
462 mDurations.delete(key);
463 }
464 }
465
466 /** @hide */
467 public void started(long time, @AppOpsManager.UidState int uidState, @OpFlags int flags) {
468 updateAccessTimeAndDuration(time, -1 /*duration*/, uidState, flags);
469 running = true;
470 }
471
472 /** @hide */
473 public void finished(long time, long duration, @AppOpsManager.UidState int uidState,
474 @OpFlags int flags) {
475 updateAccessTimeAndDuration(time, duration, uidState, flags);
476 running = false;
477 }
478
479 /** @hide */
480 public void running(long time, long duration, @AppOpsManager.UidState int uidState,
481 @OpFlags int flags) {
482 updateAccessTimeAndDuration(time, duration, uidState, flags);
483 }
484
485 /** @hide */
486 public void continuing(long duration, @AppOpsManager.UidState int uidState,
487 @OpFlags int flags) {
488 final long key = AppOpsManager.makeKey(uidState, flags);
489 if (mDurations == null) {
490 mDurations = new LongSparseLongArray();
491 }
492 mDurations.put(key, duration);
493 }
494
495 private void updateAccessTimeAndDuration(long time, long duration,
496 @AppOpsManager.UidState int uidState, @OpFlags int flags) {
497 final long key = AppOpsManager.makeKey(uidState, flags);
498 if (mAccessTimes == null) {
499 mAccessTimes = new LongSparseLongArray();
500 }
501 mAccessTimes.put(key, time);
502 if (mDurations == null) {
503 mDurations = new LongSparseLongArray();
504 }
505 mDurations.put(key, duration);
506 }
507
508 private void updateProxyState(long key, int proxyUid,
509 @Nullable String proxyPackageName) {
510 if (mProxyUids == null) {
511 mProxyUids = new LongSparseLongArray();
512 }
513 mProxyUids.put(key, proxyUid);
514 if (mProxyPackageNames == null) {
515 mProxyPackageNames = new LongSparseArray<>();
516 }
517 mProxyPackageNames.put(key, proxyPackageName);
518 }
519
520 boolean hasAnyTime() {
521 return (mAccessTimes != null && mAccessTimes.size() > 0)
522 || (mRejectTimes != null && mRejectTimes.size() > 0);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700523 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800524 }
525
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800526 final SparseArray<ArraySet<ModeCallback>> mOpModeWatchers = new SparseArray<>();
527 final ArrayMap<String, ArraySet<ModeCallback>> mPackageModeWatchers = new ArrayMap<>();
528 final ArrayMap<IBinder, ModeCallback> mModeWatchers = new ArrayMap<>();
529 final ArrayMap<IBinder, SparseArray<ActiveCallback>> mActiveWatchers = new ArrayMap<>();
Svet Ganovb3d2ae22018-12-17 22:06:15 -0800530 final ArrayMap<IBinder, SparseArray<NotedCallback>> mNotedWatchers = new ArrayMap<>();
Dianne Hackborn68d76552017-02-27 15:32:03 -0800531 final SparseArray<SparseArray<Restriction>> mAudioRestrictions = new SparseArray<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800532
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700533 final class ModeCallback implements DeathRecipient {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800534 final IAppOpsCallback mCallback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700535 final int mWatchingUid;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700536 final int mFlags;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700537 final int mCallingUid;
538 final int mCallingPid;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800539
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700540 ModeCallback(IAppOpsCallback callback, int watchingUid, int flags, int callingUid,
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700541 int callingPid) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800542 mCallback = callback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700543 mWatchingUid = watchingUid;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700544 mFlags = flags;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700545 mCallingUid = callingUid;
546 mCallingPid = callingPid;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800547 try {
548 mCallback.asBinder().linkToDeath(this, 0);
549 } catch (RemoteException e) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -0800550 /*ignored*/
Dianne Hackbornc2293022013-02-06 23:14:49 -0800551 }
552 }
553
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700554 public boolean isWatchingUid(int uid) {
555 return uid == UID_ANY || mWatchingUid < 0 || mWatchingUid == uid;
556 }
557
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700558 @Override
559 public String toString() {
560 StringBuilder sb = new StringBuilder(128);
561 sb.append("ModeCallback{");
562 sb.append(Integer.toHexString(System.identityHashCode(this)));
563 sb.append(" watchinguid=");
564 UserHandle.formatUid(sb, mWatchingUid);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700565 sb.append(" flags=0x");
566 sb.append(Integer.toHexString(mFlags));
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700567 sb.append(" from uid=");
568 UserHandle.formatUid(sb, mCallingUid);
569 sb.append(" pid=");
570 sb.append(mCallingPid);
571 sb.append('}');
572 return sb.toString();
573 }
574
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700575 void unlinkToDeath() {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800576 mCallback.asBinder().unlinkToDeath(this, 0);
577 }
578
579 @Override
580 public void binderDied() {
581 stopWatchingMode(mCallback);
582 }
583 }
584
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700585 final class ActiveCallback implements DeathRecipient {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800586 final IAppOpsActiveCallback mCallback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700587 final int mWatchingUid;
588 final int mCallingUid;
589 final int mCallingPid;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800590
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700591 ActiveCallback(IAppOpsActiveCallback callback, int watchingUid, int callingUid,
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700592 int callingPid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800593 mCallback = callback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700594 mWatchingUid = watchingUid;
595 mCallingUid = callingUid;
596 mCallingPid = callingPid;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800597 try {
598 mCallback.asBinder().linkToDeath(this, 0);
599 } catch (RemoteException e) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -0800600 /*ignored*/
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800601 }
602 }
603
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700604 @Override
605 public String toString() {
606 StringBuilder sb = new StringBuilder(128);
607 sb.append("ActiveCallback{");
608 sb.append(Integer.toHexString(System.identityHashCode(this)));
609 sb.append(" watchinguid=");
610 UserHandle.formatUid(sb, mWatchingUid);
611 sb.append(" from uid=");
612 UserHandle.formatUid(sb, mCallingUid);
613 sb.append(" pid=");
614 sb.append(mCallingPid);
615 sb.append('}');
616 return sb.toString();
617 }
618
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700619 void destroy() {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800620 mCallback.asBinder().unlinkToDeath(this, 0);
621 }
622
623 @Override
624 public void binderDied() {
625 stopWatchingActive(mCallback);
626 }
627 }
628
Svet Ganovb3d2ae22018-12-17 22:06:15 -0800629 final class NotedCallback implements DeathRecipient {
630 final IAppOpsNotedCallback mCallback;
631 final int mWatchingUid;
632 final int mCallingUid;
633 final int mCallingPid;
634
635 NotedCallback(IAppOpsNotedCallback callback, int watchingUid, int callingUid,
636 int callingPid) {
637 mCallback = callback;
638 mWatchingUid = watchingUid;
639 mCallingUid = callingUid;
640 mCallingPid = callingPid;
641 try {
642 mCallback.asBinder().linkToDeath(this, 0);
643 } catch (RemoteException e) {
644 /*ignored*/
645 }
646 }
647
648 @Override
649 public String toString() {
650 StringBuilder sb = new StringBuilder(128);
651 sb.append("NotedCallback{");
652 sb.append(Integer.toHexString(System.identityHashCode(this)));
653 sb.append(" watchinguid=");
654 UserHandle.formatUid(sb, mWatchingUid);
655 sb.append(" from uid=");
656 UserHandle.formatUid(sb, mCallingUid);
657 sb.append(" pid=");
658 sb.append(mCallingPid);
659 sb.append('}');
660 return sb.toString();
661 }
662
663 void destroy() {
664 mCallback.asBinder().unlinkToDeath(this, 0);
665 }
666
667 @Override
668 public void binderDied() {
669 stopWatchingNoted(mCallback);
670 }
671 }
672
Svet Ganova7a0db62018-02-27 20:08:01 -0800673 final ArrayMap<IBinder, ClientState> mClients = new ArrayMap<>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700674
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700675 final class ClientState extends Binder implements DeathRecipient {
Svet Ganovf7b47252018-02-26 11:11:27 -0800676 final ArrayList<Op> mStartedOps = new ArrayList<>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700677 final IBinder mAppToken;
678 final int mPid;
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700679
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700680 ClientState(IBinder appToken) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700681 mAppToken = appToken;
682 mPid = Binder.getCallingPid();
Svet Ganovf7b47252018-02-26 11:11:27 -0800683 // Watch only for remote processes dying
684 if (!(appToken instanceof Binder)) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700685 try {
686 mAppToken.linkToDeath(this, 0);
687 } catch (RemoteException e) {
Svet Ganovf7b47252018-02-26 11:11:27 -0800688 /* do nothing */
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700689 }
690 }
691 }
692
693 @Override
694 public String toString() {
695 return "ClientState{" +
696 "mAppToken=" + mAppToken +
Svet Ganovf7b47252018-02-26 11:11:27 -0800697 ", " + "pid=" + mPid +
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700698 '}';
699 }
700
701 @Override
702 public void binderDied() {
703 synchronized (AppOpsService.this) {
704 for (int i=mStartedOps.size()-1; i>=0; i--) {
Svet Ganova7a0db62018-02-27 20:08:01 -0800705 finishOperationLocked(mStartedOps.get(i), /*finishNested*/ true);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700706 }
707 mClients.remove(mAppToken);
708 }
709 }
710 }
711
Jeff Brown6f357d32014-01-15 20:40:55 -0800712 public AppOpsService(File storagePath, Handler handler) {
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600713 LockGuard.installLock(this, LockGuard.INDEX_APP_OPS);
Dianne Hackborne17b4452018-01-10 13:15:40 -0800714 mFile = new AtomicFile(storagePath, "appops");
Jeff Brown6f357d32014-01-15 20:40:55 -0800715 mHandler = handler;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700716 mConstants = new Constants(mHandler);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800717 readState();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800718 }
David Braunf5d83192013-09-16 13:43:51 -0700719
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800720 public void publish(Context context) {
721 mContext = context;
722 ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
Dianne Hackbornd5254412018-05-11 18:02:58 -0700723 LocalServices.addService(AppOpsManagerInternal.class, mAppOpsManagerInternal);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800724 }
725
Dianne Hackborn514074f2013-02-11 10:52:46 -0800726 public void systemReady() {
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700727 mConstants.startMonitoring(mContext.getContentResolver());
Svet Ganov8455ba22019-01-02 13:05:56 -0800728 mHistoricalRegistry.systemReady(mContext.getContentResolver());
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700729
Dianne Hackborn514074f2013-02-11 10:52:46 -0800730 synchronized (this) {
731 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700732 for (int i = mUidStates.size() - 1; i >= 0; i--) {
733 UidState uidState = mUidStates.valueAt(i);
734
735 String[] packageNames = getPackagesForUid(uidState.uid);
736 if (ArrayUtils.isEmpty(packageNames)) {
737 uidState.clear();
738 mUidStates.removeAt(i);
739 changed = true;
740 continue;
741 }
742
743 ArrayMap<String, Ops> pkgs = uidState.pkgOps;
744 if (pkgs == null) {
745 continue;
746 }
747
Dianne Hackborn514074f2013-02-11 10:52:46 -0800748 Iterator<Ops> it = pkgs.values().iterator();
749 while (it.hasNext()) {
750 Ops ops = it.next();
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700751 int curUid = -1;
Dianne Hackborn514074f2013-02-11 10:52:46 -0800752 try {
Jeff Sharkeycd654482016-01-08 17:42:11 -0700753 curUid = AppGlobals.getPackageManager().getPackageUid(ops.packageName,
754 PackageManager.MATCH_UNINSTALLED_PACKAGES,
Svet Ganov2af57082015-07-30 08:44:20 -0700755 UserHandle.getUserId(ops.uidState.uid));
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700756 } catch (RemoteException ignored) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800757 }
Svet Ganov2af57082015-07-30 08:44:20 -0700758 if (curUid != ops.uidState.uid) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800759 Slog.i(TAG, "Pruning old package " + ops.packageName
Svet Ganov2af57082015-07-30 08:44:20 -0700760 + "/" + ops.uidState + ": new uid=" + curUid);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800761 it.remove();
762 changed = true;
763 }
764 }
Svet Ganov2af57082015-07-30 08:44:20 -0700765
766 if (uidState.isDefault()) {
767 mUidStates.removeAt(i);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800768 }
769 }
770 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800771 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800772 }
773 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700774
Suprabh Shukla3017fe42018-11-08 19:00:01 -0800775 final IntentFilter packageSuspendFilter = new IntentFilter();
776 packageSuspendFilter.addAction(Intent.ACTION_PACKAGES_UNSUSPENDED);
777 packageSuspendFilter.addAction(Intent.ACTION_PACKAGES_SUSPENDED);
778 mContext.registerReceiver(new BroadcastReceiver() {
779 @Override
780 public void onReceive(Context context, Intent intent) {
781 final int[] changedUids = intent.getIntArrayExtra(Intent.EXTRA_CHANGED_UID_LIST);
782 final String[] changedPkgs = intent.getStringArrayExtra(
783 Intent.EXTRA_CHANGED_PACKAGE_LIST);
784 final ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(OP_PLAY_AUDIO);
785 for (int i = 0; i < changedUids.length; i++) {
786 final int changedUid = changedUids[i];
787 final String changedPkg = changedPkgs[i];
788 // We trust packagemanager to insert matching uid and packageNames in the extras
789 mHandler.sendMessage(PooledLambda.obtainMessage(AppOpsService::notifyOpChanged,
790 AppOpsService.this, callbacks, OP_PLAY_AUDIO, changedUid, changedPkg));
791 }
792 }
793 }, packageSuspendFilter);
794
Suprabh Shuklaaef25132017-01-23 18:09:03 -0800795 PackageManagerInternal packageManagerInternal = LocalServices.getService(
796 PackageManagerInternal.class);
797 packageManagerInternal.setExternalSourcesPolicy(
798 new PackageManagerInternal.ExternalSourcesPolicy() {
799 @Override
800 public int getPackageTrustedToInstallApps(String packageName, int uid) {
801 int appOpMode = checkOperation(AppOpsManager.OP_REQUEST_INSTALL_PACKAGES,
802 uid, packageName);
803 switch (appOpMode) {
804 case AppOpsManager.MODE_ALLOWED:
805 return PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
806 case AppOpsManager.MODE_ERRORED:
807 return PackageManagerInternal.ExternalSourcesPolicy.USER_BLOCKED;
808 default:
809 return PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT;
810 }
811 }
812 });
813
Jeff Sharkey10ec9d82018-11-28 14:52:45 -0700814 if (!StorageManager.hasIsolatedStorage()) {
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700815 StorageManagerInternal storageManagerInternal = LocalServices.getService(
816 StorageManagerInternal.class);
817 storageManagerInternal.addExternalStoragePolicy(
818 new StorageManagerInternal.ExternalStorageMountPolicy() {
819 @Override
820 public int getMountMode(int uid, String packageName) {
821 if (Process.isIsolated(uid)) {
822 return Zygote.MOUNT_EXTERNAL_NONE;
823 }
824 if (noteOperation(AppOpsManager.OP_READ_EXTERNAL_STORAGE, uid,
825 packageName) != AppOpsManager.MODE_ALLOWED) {
826 return Zygote.MOUNT_EXTERNAL_NONE;
827 }
828 if (noteOperation(AppOpsManager.OP_WRITE_EXTERNAL_STORAGE, uid,
829 packageName) != AppOpsManager.MODE_ALLOWED) {
830 return Zygote.MOUNT_EXTERNAL_READ;
831 }
832 return Zygote.MOUNT_EXTERNAL_WRITE;
Svet Ganov6ee871e2015-07-10 14:29:33 -0700833 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700834
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700835 @Override
836 public boolean hasExternalStorage(int uid, String packageName) {
837 final int mountMode = getMountMode(uid, packageName);
838 return mountMode == Zygote.MOUNT_EXTERNAL_READ
839 || mountMode == Zygote.MOUNT_EXTERNAL_WRITE;
840 }
841 });
842 }
Dianne Hackborn514074f2013-02-11 10:52:46 -0800843 }
844
845 public void packageRemoved(int uid, String packageName) {
846 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700847 UidState uidState = mUidStates.get(uid);
848 if (uidState == null) {
849 return;
850 }
851
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800852 Ops ops = null;
Svet Ganov2af57082015-07-30 08:44:20 -0700853
854 // Remove any package state if such.
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800855 if (uidState.pkgOps != null) {
856 ops = uidState.pkgOps.remove(packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700857 }
858
859 // If we just nuked the last package state check if the UID is valid.
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800860 if (ops != null && uidState.pkgOps.isEmpty()
Svet Ganov2af57082015-07-30 08:44:20 -0700861 && getPackagesForUid(uid).length <= 0) {
862 mUidStates.remove(uid);
863 }
864
Svet Ganova7a0db62018-02-27 20:08:01 -0800865 // Finish ops other packages started on behalf of the package.
866 final int clientCount = mClients.size();
867 for (int i = 0; i < clientCount; i++) {
868 final ClientState client = mClients.valueAt(i);
869 if (client.mStartedOps == null) {
870 continue;
871 }
872 final int opCount = client.mStartedOps.size();
873 for (int j = opCount - 1; j >= 0; j--) {
874 final Op op = client.mStartedOps.get(j);
Svet Ganovaf189e32019-02-15 18:45:29 -0800875 if (uid == op.uidState.uid && packageName.equals(op.packageName)) {
Svet Ganova7a0db62018-02-27 20:08:01 -0800876 finishOperationLocked(op, /*finishNested*/ true);
877 client.mStartedOps.remove(j);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700878 if (op.startNesting <= 0) {
Svet Ganova7a0db62018-02-27 20:08:01 -0800879 scheduleOpActiveChangedIfNeededLocked(op.op,
880 uid, packageName, false);
881 }
882 }
883 }
884 }
885
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800886 if (ops != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700887 scheduleFastWriteLocked();
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800888
889 final int opCount = ops.size();
890 for (int i = 0; i < opCount; i++) {
891 final Op op = ops.valueAt(i);
Svet Ganovaf189e32019-02-15 18:45:29 -0800892 if (op.running) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800893 scheduleOpActiveChangedIfNeededLocked(
Svet Ganovaf189e32019-02-15 18:45:29 -0800894 op.op, op.uidState.uid, op.packageName, false);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800895 }
896 }
Dianne Hackborn514074f2013-02-11 10:52:46 -0800897 }
898 }
899 }
900
901 public void uidRemoved(int uid) {
902 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700903 if (mUidStates.indexOfKey(uid) >= 0) {
904 mUidStates.remove(uid);
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800905 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800906 }
907 }
908 }
909
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700910 public void updateUidProcState(int uid, int procState) {
911 synchronized (this) {
912 final UidState uidState = getUidStateLocked(uid, true);
Amith Yamasania0a30a12019-01-22 11:38:06 -0800913 int newState = PROCESS_STATE_TO_UID_STATE[procState];
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700914 if (uidState != null && uidState.pendingState != newState) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700915 final int oldPendingState = uidState.pendingState;
916 uidState.pendingState = newState;
Svet Ganovaf189e32019-02-15 18:45:29 -0800917 if (newState < uidState.state || newState <= UID_STATE_MAX_LAST_NON_RESTRICTED) {
Dianne Hackborne93ab412018-05-14 17:52:30 -0700918 // We are moving to a more important state, or the new state is in the
919 // foreground, then always do it immediately.
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700920 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700921 } else if (uidState.pendingStateCommitTime == 0) {
922 // We are moving to a less important state for the first time,
923 // delay the application for a bit.
Dianne Hackborne93ab412018-05-14 17:52:30 -0700924 final long settleTime;
925 if (uidState.state <= UID_STATE_TOP) {
926 settleTime = mConstants.TOP_STATE_SETTLE_TIME;
927 } else if (uidState.state <= UID_STATE_FOREGROUND_SERVICE) {
928 settleTime = mConstants.FG_SERVICE_STATE_SETTLE_TIME;
929 } else {
930 settleTime = mConstants.BG_STATE_SETTLE_TIME;
931 }
Dianne Hackborn9fb93502018-06-18 12:29:44 -0700932 uidState.pendingStateCommitTime = SystemClock.elapsedRealtime() + settleTime;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700933 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700934 if (uidState.startNesting != 0) {
935 // There is some actively running operation... need to find it
936 // and appropriately update its state.
937 final long now = System.currentTimeMillis();
938 for (int i = uidState.pkgOps.size() - 1; i >= 0; i--) {
939 final Ops ops = uidState.pkgOps.valueAt(i);
940 for (int j = ops.size() - 1; j >= 0; j--) {
941 final Op op = ops.valueAt(j);
942 if (op.startNesting > 0) {
Svet Ganovaf189e32019-02-15 18:45:29 -0800943 final long duration = SystemClock.elapsedRealtime()
944 - op.startRealtime;
945 // We don't support proxy long running ops (start/stop)
946 mHistoricalRegistry.increaseOpAccessDuration(op.op,
947 op.uidState.uid, op.packageName, oldPendingState,
948 AppOpsManager.OP_FLAG_SELF, duration);
949 // Finish the op in the old state
950 op.finished(now, duration, oldPendingState,
951 AppOpsManager.OP_FLAG_SELF);
952 // Start the op in the new state
953 op.startRealtime = now;
954 op.started(now, newState, AppOpsManager.OP_FLAG_SELF);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700955 }
956 }
957 }
958 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700959 }
960 }
961 }
962
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800963 public void shutdown() {
964 Slog.w(TAG, "Writing app ops before shutdown...");
Dianne Hackborn35654b62013-01-14 17:38:02 -0800965 boolean doWrite = false;
966 synchronized (this) {
967 if (mWriteScheduled) {
968 mWriteScheduled = false;
969 doWrite = true;
970 }
971 }
972 if (doWrite) {
973 writeState();
974 }
975 }
976
Dianne Hackborn72e39832013-01-18 18:36:09 -0800977 private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
978 ArrayList<AppOpsManager.OpEntry> resOps = null;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700979 final long elapsedNow = SystemClock.elapsedRealtime();
Dianne Hackborn72e39832013-01-18 18:36:09 -0800980 if (ops == null) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700981 resOps = new ArrayList<>();
Dianne Hackborn72e39832013-01-18 18:36:09 -0800982 for (int j=0; j<pkgOps.size(); j++) {
983 Op curOp = pkgOps.valueAt(j);
Svet Ganovaf189e32019-02-15 18:45:29 -0800984 resOps.add(getOpEntryForResult(curOp, elapsedNow));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800985 }
986 } else {
987 for (int j=0; j<ops.length; j++) {
988 Op curOp = pkgOps.get(ops[j]);
989 if (curOp != null) {
990 if (resOps == null) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700991 resOps = new ArrayList<>();
Dianne Hackborn72e39832013-01-18 18:36:09 -0800992 }
Svet Ganovaf189e32019-02-15 18:45:29 -0800993 resOps.add(getOpEntryForResult(curOp, elapsedNow));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800994 }
995 }
996 }
997 return resOps;
998 }
999
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001000 private ArrayList<AppOpsManager.OpEntry> collectOps(SparseIntArray uidOps, int[] ops) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08001001 if (uidOps == null) {
1002 return null;
1003 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001004 ArrayList<AppOpsManager.OpEntry> resOps = null;
1005 if (ops == null) {
1006 resOps = new ArrayList<>();
1007 for (int j=0; j<uidOps.size(); j++) {
Svet Ganovaf189e32019-02-15 18:45:29 -08001008 resOps.add(new OpEntry(uidOps.keyAt(j), uidOps.valueAt(j)));
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001009 }
1010 } else {
1011 for (int j=0; j<ops.length; j++) {
1012 int index = uidOps.indexOfKey(ops[j]);
1013 if (index >= 0) {
1014 if (resOps == null) {
1015 resOps = new ArrayList<>();
1016 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001017 resOps.add(new OpEntry(uidOps.keyAt(j), uidOps.valueAt(j)));
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001018 }
1019 }
1020 }
1021 return resOps;
1022 }
1023
Svet Ganovaf189e32019-02-15 18:45:29 -08001024 private static @NonNull OpEntry getOpEntryForResult(@NonNull Op op, long elapsedNow) {
1025 if (op.running) {
1026 op.continuing(elapsedNow - op.startRealtime,
1027 op.uidState.state, AppOpsManager.OP_FLAG_SELF);
1028 }
1029 final OpEntry entry = new OpEntry(op.op, op.running, op.mode,
1030 op.mAccessTimes != null ? op.mAccessTimes.clone() : null,
1031 op.mRejectTimes != null ? op.mRejectTimes.clone() : null,
1032 op.mDurations != null ? op.mDurations.clone() : null,
1033 op.mProxyUids != null ? op.mProxyUids.clone() : null,
1034 op.mProxyPackageNames != null ? op.mProxyPackageNames.clone() : null);
1035 return entry;
1036 }
1037
Dianne Hackborn35654b62013-01-14 17:38:02 -08001038 @Override
1039 public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
1040 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
1041 Binder.getCallingPid(), Binder.getCallingUid(), null);
1042 ArrayList<AppOpsManager.PackageOps> res = null;
1043 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -07001044 final int uidStateCount = mUidStates.size();
1045 for (int i = 0; i < uidStateCount; i++) {
1046 UidState uidState = mUidStates.valueAt(i);
1047 if (uidState.pkgOps == null || uidState.pkgOps.isEmpty()) {
1048 continue;
1049 }
1050 ArrayMap<String, Ops> packages = uidState.pkgOps;
1051 final int packageCount = packages.size();
1052 for (int j = 0; j < packageCount; j++) {
1053 Ops pkgOps = packages.valueAt(j);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001054 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001055 if (resOps != null) {
1056 if (res == null) {
1057 res = new ArrayList<AppOpsManager.PackageOps>();
1058 }
1059 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -07001060 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001061 res.add(resPackage);
1062 }
1063 }
1064 }
1065 }
1066 return res;
1067 }
1068
1069 @Override
Dianne Hackborn72e39832013-01-18 18:36:09 -08001070 public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
1071 int[] ops) {
1072 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
1073 Binder.getCallingPid(), Binder.getCallingUid(), null);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001074 String resolvedPackageName = resolvePackageName(uid, packageName);
1075 if (resolvedPackageName == null) {
1076 return Collections.emptyList();
1077 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08001078 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001079 Ops pkgOps = getOpsRawLocked(uid, resolvedPackageName, false /* edit */,
1080 false /* uidMismatchExpected */);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001081 if (pkgOps == null) {
1082 return null;
1083 }
1084 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
1085 if (resOps == null) {
1086 return null;
1087 }
1088 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
1089 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -07001090 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001091 res.add(resPackage);
1092 return res;
1093 }
1094 }
1095
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001096 @Override
Svet Ganov8455ba22019-01-02 13:05:56 -08001097 public void getHistoricalOps(int uid, @NonNull String packageName,
Svet Ganov23c88db2019-01-22 20:38:11 -08001098 @Nullable List<String> opNames, long beginTimeMillis, long endTimeMillis,
Svet Ganovaf189e32019-02-15 18:45:29 -08001099 @OpFlags int flags, @NonNull RemoteCallback callback) {
Svet Ganov23c88db2019-01-22 20:38:11 -08001100 // Use the builder to validate arguments.
Svet Ganovaf189e32019-02-15 18:45:29 -08001101 new HistoricalOpsRequest.Builder(
Svet Ganov23c88db2019-01-22 20:38:11 -08001102 beginTimeMillis, endTimeMillis)
1103 .setUid(uid)
1104 .setPackageName(packageName)
1105 .setOpNames(opNames)
Svet Ganovaf189e32019-02-15 18:45:29 -08001106 .setFlags(flags)
Svet Ganov23c88db2019-01-22 20:38:11 -08001107 .build();
Svet Ganov8455ba22019-01-02 13:05:56 -08001108 Preconditions.checkNotNull(callback, "callback cannot be null");
Svet Ganovad0a49b2018-10-29 10:07:08 -07001109
1110 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
Svet Ganov8455ba22019-01-02 13:05:56 -08001111 Binder.getCallingPid(), Binder.getCallingUid(), "getHistoricalOps");
Svet Ganovad0a49b2018-10-29 10:07:08 -07001112
Svet Ganov23c88db2019-01-22 20:38:11 -08001113 final String[] opNamesArray = (opNames != null)
1114 ? opNames.toArray(new String[opNames.size()]) : null;
Svet Ganovad0a49b2018-10-29 10:07:08 -07001115
Svet Ganovaf189e32019-02-15 18:45:29 -08001116 // Must not hold the appops lock
1117 mHistoricalRegistry.getHistoricalOps(uid, packageName, opNamesArray,
1118 beginTimeMillis, endTimeMillis, flags, callback);
Svet Ganovad0a49b2018-10-29 10:07:08 -07001119 }
1120
1121 @Override
Svet Ganov8455ba22019-01-02 13:05:56 -08001122 public void getHistoricalOpsFromDiskRaw(int uid, @NonNull String packageName,
Svet Ganov23c88db2019-01-22 20:38:11 -08001123 @Nullable List<String> opNames, long beginTimeMillis, long endTimeMillis,
Svet Ganovaf189e32019-02-15 18:45:29 -08001124 @OpFlags int flags, @NonNull RemoteCallback callback) {
Svet Ganov23c88db2019-01-22 20:38:11 -08001125 // Use the builder to validate arguments.
Svet Ganovaf189e32019-02-15 18:45:29 -08001126 new HistoricalOpsRequest.Builder(
Svet Ganov23c88db2019-01-22 20:38:11 -08001127 beginTimeMillis, endTimeMillis)
1128 .setUid(uid)
1129 .setPackageName(packageName)
1130 .setOpNames(opNames)
Svet Ganovaf189e32019-02-15 18:45:29 -08001131 .setFlags(flags)
Svet Ganov23c88db2019-01-22 20:38:11 -08001132 .build();
Svet Ganov8455ba22019-01-02 13:05:56 -08001133 Preconditions.checkNotNull(callback, "callback cannot be null");
Svet Ganovad0a49b2018-10-29 10:07:08 -07001134
Svet Ganov8e5bf962019-03-19 23:59:03 -07001135 mContext.enforcePermission(Manifest.permission.MANAGE_APPOPS,
Svet Ganov8455ba22019-01-02 13:05:56 -08001136 Binder.getCallingPid(), Binder.getCallingUid(), "getHistoricalOps");
Svet Ganovad0a49b2018-10-29 10:07:08 -07001137
Svet Ganov23c88db2019-01-22 20:38:11 -08001138 final String[] opNamesArray = (opNames != null)
1139 ? opNames.toArray(new String[opNames.size()]) : null;
1140
Svet Ganov8455ba22019-01-02 13:05:56 -08001141 // Must not hold the appops lock
Svet Ganov23c88db2019-01-22 20:38:11 -08001142 mHistoricalRegistry.getHistoricalOpsFromDiskRaw(uid, packageName, opNamesArray,
Svet Ganovaf189e32019-02-15 18:45:29 -08001143 beginTimeMillis, endTimeMillis, flags, callback);
Svet Ganovad0a49b2018-10-29 10:07:08 -07001144 }
1145
1146 @Override
Svet Ganov8e5bf962019-03-19 23:59:03 -07001147 public void reloadNonHistoricalState() {
1148 mContext.enforcePermission(Manifest.permission.MANAGE_APPOPS,
1149 Binder.getCallingPid(), Binder.getCallingUid(), "reloadNonHistoricalState");
1150 writeState();
1151 readState();
1152 }
1153
1154 @Override
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001155 public List<AppOpsManager.PackageOps> getUidOps(int uid, int[] ops) {
1156 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
1157 Binder.getCallingPid(), Binder.getCallingUid(), null);
1158 synchronized (this) {
1159 UidState uidState = getUidStateLocked(uid, false);
1160 if (uidState == null) {
1161 return null;
1162 }
1163 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(uidState.opModes, ops);
1164 if (resOps == null) {
1165 return null;
1166 }
1167 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
1168 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
1169 null, uidState.uid, resOps);
1170 res.add(resPackage);
1171 return res;
1172 }
1173 }
1174
Dianne Hackborn607b4142013-08-02 18:10:10 -07001175 private void pruneOp(Op op, int uid, String packageName) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001176 if (!op.hasAnyTime()) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001177 Ops ops = getOpsRawLocked(uid, packageName, false /* edit */,
1178 false /* uidMismatchExpected */);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001179 if (ops != null) {
1180 ops.remove(op.op);
1181 if (ops.size() <= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -07001182 UidState uidState = ops.uidState;
1183 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
Dianne Hackborn607b4142013-08-02 18:10:10 -07001184 if (pkgOps != null) {
1185 pkgOps.remove(ops.packageName);
Svet Ganov2af57082015-07-30 08:44:20 -07001186 if (pkgOps.isEmpty()) {
1187 uidState.pkgOps = null;
1188 }
1189 if (uidState.isDefault()) {
1190 mUidStates.remove(uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001191 }
1192 }
1193 }
1194 }
1195 }
1196 }
1197
Svet Ganovaf189e32019-02-15 18:45:29 -08001198 private void enforceManageAppOpsModes(int callingPid, int callingUid, int targetUid) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07001199 if (callingPid == Process.myPid()) {
1200 return;
1201 }
1202 final int callingUser = UserHandle.getUserId(callingUid);
1203 synchronized (this) {
1204 if (mProfileOwners != null && mProfileOwners.get(callingUser, -1) == callingUid) {
1205 if (targetUid >= 0 && callingUser == UserHandle.getUserId(targetUid)) {
1206 // Profile owners are allowed to change modes but only for apps
1207 // within their user.
1208 return;
1209 }
1210 }
1211 }
1212 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
1213 Binder.getCallingPid(), Binder.getCallingUid(), null);
1214 }
1215
Dianne Hackborn72e39832013-01-18 18:36:09 -08001216 @Override
Svet Ganov2af57082015-07-30 08:44:20 -07001217 public void setUidMode(int code, int uid, int mode) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08001218 if (DEBUG) {
1219 Slog.i(TAG, "uid " + uid + " OP_" + opToName(code) + " := " + modeToName(mode)
1220 + " by uid " + Binder.getCallingUid());
1221 }
1222
Dianne Hackbornd5254412018-05-11 18:02:58 -07001223 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
Svet Ganov2af57082015-07-30 08:44:20 -07001224 verifyIncomingOp(code);
1225 code = AppOpsManager.opToSwitch(code);
1226
1227 synchronized (this) {
1228 final int defaultMode = AppOpsManager.opToDefaultMode(code);
1229
1230 UidState uidState = getUidStateLocked(uid, false);
1231 if (uidState == null) {
1232 if (mode == defaultMode) {
1233 return;
1234 }
1235 uidState = new UidState(uid);
1236 uidState.opModes = new SparseIntArray();
1237 uidState.opModes.put(code, mode);
1238 mUidStates.put(uid, uidState);
1239 scheduleWriteLocked();
1240 } else if (uidState.opModes == null) {
1241 if (mode != defaultMode) {
1242 uidState.opModes = new SparseIntArray();
1243 uidState.opModes.put(code, mode);
1244 scheduleWriteLocked();
1245 }
1246 } else {
Hai Zhang2b98fb32018-09-21 15:18:46 -07001247 if (uidState.opModes.indexOfKey(code) >= 0 && uidState.opModes.get(code) == mode) {
Svet Ganov2af57082015-07-30 08:44:20 -07001248 return;
1249 }
1250 if (mode == defaultMode) {
1251 uidState.opModes.delete(code);
1252 if (uidState.opModes.size() <= 0) {
1253 uidState.opModes = null;
1254 }
1255 } else {
1256 uidState.opModes.put(code, mode);
1257 }
1258 scheduleWriteLocked();
1259 }
1260 }
1261
Svetoslav215b44a2015-08-04 19:03:40 -07001262 String[] uidPackageNames = getPackagesForUid(uid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001263 ArrayMap<ModeCallback, ArraySet<String>> callbackSpecs = null;
Svet Ganov2af57082015-07-30 08:44:20 -07001264
riddle_hsu40b300f2015-11-23 13:22:03 +08001265 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001266 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001267 if (callbacks != null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001268 final int callbackCount = callbacks.size();
1269 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001270 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +08001271 ArraySet<String> changedPackages = new ArraySet<>();
1272 Collections.addAll(changedPackages, uidPackageNames);
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001273 if (callbackSpecs == null) {
1274 callbackSpecs = new ArrayMap<>();
1275 }
riddle_hsu40b300f2015-11-23 13:22:03 +08001276 callbackSpecs.put(callback, changedPackages);
1277 }
1278 }
1279
1280 for (String uidPackageName : uidPackageNames) {
1281 callbacks = mPackageModeWatchers.get(uidPackageName);
1282 if (callbacks != null) {
1283 if (callbackSpecs == null) {
1284 callbackSpecs = new ArrayMap<>();
Svet Ganov2af57082015-07-30 08:44:20 -07001285 }
riddle_hsu40b300f2015-11-23 13:22:03 +08001286 final int callbackCount = callbacks.size();
1287 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001288 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +08001289 ArraySet<String> changedPackages = callbackSpecs.get(callback);
1290 if (changedPackages == null) {
1291 changedPackages = new ArraySet<>();
1292 callbackSpecs.put(callback, changedPackages);
1293 }
1294 changedPackages.add(uidPackageName);
1295 }
Svet Ganov2af57082015-07-30 08:44:20 -07001296 }
1297 }
1298 }
1299
1300 if (callbackSpecs == null) {
1301 return;
1302 }
1303
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001304 for (int i = 0; i < callbackSpecs.size(); i++) {
1305 final ModeCallback callback = callbackSpecs.keyAt(i);
1306 final ArraySet<String> reportedPackageNames = callbackSpecs.valueAt(i);
1307 if (reportedPackageNames == null) {
1308 mHandler.sendMessage(PooledLambda.obtainMessage(
1309 AppOpsService::notifyOpChanged,
1310 this, callback, code, uid, (String) null));
1311
1312 } else {
1313 final int reportedPackageCount = reportedPackageNames.size();
1314 for (int j = 0; j < reportedPackageCount; j++) {
1315 final String reportedPackageName = reportedPackageNames.valueAt(j);
1316 mHandler.sendMessage(PooledLambda.obtainMessage(
1317 AppOpsService::notifyOpChanged,
1318 this, callback, code, uid, reportedPackageName));
Svet Ganov2af57082015-07-30 08:44:20 -07001319 }
1320 }
Svet Ganov2af57082015-07-30 08:44:20 -07001321 }
1322 }
1323
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001324 /**
1325 * Set all {@link #setMode (package) modes} for this uid to the default value.
1326 *
1327 * @param code The app-op
1328 * @param uid The uid
1329 */
1330 private void setAllPkgModesToDefault(int code, int uid) {
1331 synchronized (this) {
1332 UidState uidState = getUidStateLocked(uid, false);
1333 if (uidState == null) {
1334 return;
1335 }
1336
1337 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
1338 if (pkgOps == null) {
1339 return;
1340 }
1341
Svet Ganovaf189e32019-02-15 18:45:29 -08001342 boolean scheduleWrite = false;
1343
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001344 int numPkgs = pkgOps.size();
1345 for (int pkgNum = 0; pkgNum < numPkgs; pkgNum++) {
1346 Ops ops = pkgOps.valueAt(pkgNum);
1347
1348 Op op = ops.get(code);
1349 if (op == null) {
1350 continue;
1351 }
1352
1353 int defaultMode = AppOpsManager.opToDefaultMode(code);
1354 if (op.mode != defaultMode) {
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001355 op.mode = defaultMode;
Svet Ganovaf189e32019-02-15 18:45:29 -08001356 scheduleWrite = true;
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001357 }
1358 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001359
1360 if (scheduleWrite) {
1361 scheduleWriteLocked();
1362 }
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001363 }
1364 }
1365
Svet Ganov2af57082015-07-30 08:44:20 -07001366 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001367 public void setMode(int code, int uid, String packageName, int mode) {
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07001368 setMode(code, uid, packageName, mode, true, false);
1369 }
1370
1371 /**
1372 * Sets the mode for a certain op and uid.
1373 *
1374 * @param code The op code to set
1375 * @param uid The UID for which to set
1376 * @param packageName The package for which to set
1377 * @param mode The new mode to set
1378 * @param verifyUid Iff {@code true}, check that the package name belongs to the uid
1379 * @param isPrivileged Whether the package is privileged. (Only used if {@code verifyUid ==
1380 * false})
1381 */
1382 private void setMode(int code, int uid, @NonNull String packageName, int mode,
1383 boolean verifyUid, boolean isPrivileged) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07001384 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001385 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001386 ArraySet<ModeCallback> repCbs = null;
Dianne Hackbornc2293022013-02-06 23:14:49 -08001387 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001388 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -07001389 UidState uidState = getUidStateLocked(uid, false);
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07001390 Op op = getOpLocked(code, uid, packageName, true, verifyUid, isPrivileged);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001391 if (op != null) {
1392 if (op.mode != mode) {
1393 op.mode = mode;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001394 if (uidState != null) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001395 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001396 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001397 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001398 if (cbs != null) {
1399 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001400 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001401 }
1402 repCbs.addAll(cbs);
1403 }
1404 cbs = mPackageModeWatchers.get(packageName);
1405 if (cbs != null) {
1406 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001407 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001408 }
1409 repCbs.addAll(cbs);
1410 }
David Braunf5d83192013-09-16 13:43:51 -07001411 if (mode == AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001412 // If going into the default mode, prune this op
1413 // if there is nothing else interesting in it.
Dianne Hackborn607b4142013-08-02 18:10:10 -07001414 pruneOp(op, uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001415 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001416 scheduleFastWriteLocked();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001417 }
1418 }
1419 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001420 if (repCbs != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001421 mHandler.sendMessage(PooledLambda.obtainMessage(
1422 AppOpsService::notifyOpChanged,
1423 this, repCbs, code, uid, packageName));
Dianne Hackbornc2293022013-02-06 23:14:49 -08001424 }
1425 }
1426
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001427 private void notifyOpChanged(ArraySet<ModeCallback> callbacks, int code,
1428 int uid, String packageName) {
1429 for (int i = 0; i < callbacks.size(); i++) {
1430 final ModeCallback callback = callbacks.valueAt(i);
1431 notifyOpChanged(callback, code, uid, packageName);
1432 }
1433 }
1434
1435 private void notifyOpChanged(ModeCallback callback, int code,
1436 int uid, String packageName) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001437 if (uid != UID_ANY && callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001438 return;
1439 }
1440 // There are components watching for mode changes such as window manager
1441 // and location manager which are in our process. The callbacks in these
1442 // components may require permissions our remote caller does not have.
1443 final long identity = Binder.clearCallingIdentity();
1444 try {
1445 callback.mCallback.opChanged(code, uid, packageName);
1446 } catch (RemoteException e) {
1447 /* ignore */
1448 } finally {
1449 Binder.restoreCallingIdentity(identity);
1450 }
1451 }
1452
1453 private static HashMap<ModeCallback, ArrayList<ChangeRec>> addCallbacks(
1454 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks,
1455 int op, int uid, String packageName, ArraySet<ModeCallback> cbs) {
Dianne Hackborn607b4142013-08-02 18:10:10 -07001456 if (cbs == null) {
1457 return callbacks;
1458 }
1459 if (callbacks == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001460 callbacks = new HashMap<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001461 }
Svet Ganov2af57082015-07-30 08:44:20 -07001462 boolean duplicate = false;
Dianne Hackborn68d76552017-02-27 15:32:03 -08001463 final int N = cbs.size();
1464 for (int i=0; i<N; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001465 ModeCallback cb = cbs.valueAt(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001466 ArrayList<ChangeRec> reports = callbacks.get(cb);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001467 if (reports == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001468 reports = new ArrayList<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001469 callbacks.put(cb, reports);
Svet Ganov2af57082015-07-30 08:44:20 -07001470 } else {
1471 final int reportCount = reports.size();
1472 for (int j = 0; j < reportCount; j++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001473 ChangeRec report = reports.get(j);
1474 if (report.op == op && report.pkg.equals(packageName)) {
Svet Ganov2af57082015-07-30 08:44:20 -07001475 duplicate = true;
1476 break;
1477 }
1478 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001479 }
Svet Ganov2af57082015-07-30 08:44:20 -07001480 if (!duplicate) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001481 reports.add(new ChangeRec(op, uid, packageName));
Svet Ganov2af57082015-07-30 08:44:20 -07001482 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001483 }
1484 return callbacks;
1485 }
1486
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001487 static final class ChangeRec {
1488 final int op;
1489 final int uid;
1490 final String pkg;
1491
1492 ChangeRec(int _op, int _uid, String _pkg) {
1493 op = _op;
1494 uid = _uid;
1495 pkg = _pkg;
1496 }
1497 }
1498
Dianne Hackborn607b4142013-08-02 18:10:10 -07001499 @Override
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001500 public void resetAllModes(int reqUserId, String reqPackageName) {
1501 final int callingPid = Binder.getCallingPid();
1502 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001503 reqUserId = ActivityManager.handleIncomingUser(callingPid, callingUid, reqUserId,
1504 true, true, "resetAllModes", null);
Svet Ganov2af57082015-07-30 08:44:20 -07001505
1506 int reqUid = -1;
1507 if (reqPackageName != null) {
1508 try {
1509 reqUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -07001510 reqPackageName, PackageManager.MATCH_UNINSTALLED_PACKAGES, reqUserId);
Svet Ganov2af57082015-07-30 08:44:20 -07001511 } catch (RemoteException e) {
1512 /* ignore - local call */
1513 }
1514 }
1515
Dianne Hackbornd5254412018-05-11 18:02:58 -07001516 enforceManageAppOpsModes(callingPid, callingUid, reqUid);
1517
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001518 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks = null;
Dianne Hackborn607b4142013-08-02 18:10:10 -07001519 synchronized (this) {
1520 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -07001521 for (int i = mUidStates.size() - 1; i >= 0; i--) {
1522 UidState uidState = mUidStates.valueAt(i);
1523
1524 SparseIntArray opModes = uidState.opModes;
1525 if (opModes != null && (uidState.uid == reqUid || reqUid == -1)) {
1526 final int uidOpCount = opModes.size();
1527 for (int j = uidOpCount - 1; j >= 0; j--) {
1528 final int code = opModes.keyAt(j);
1529 if (AppOpsManager.opAllowsReset(code)) {
1530 opModes.removeAt(j);
1531 if (opModes.size() <= 0) {
1532 uidState.opModes = null;
1533 }
1534 for (String packageName : getPackagesForUid(uidState.uid)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001535 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -07001536 mOpModeWatchers.get(code));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001537 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -07001538 mPackageModeWatchers.get(packageName));
1539 }
1540 }
1541 }
1542 }
1543
1544 if (uidState.pkgOps == null) {
1545 continue;
1546 }
1547
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001548 if (reqUserId != UserHandle.USER_ALL
Svet Ganov2af57082015-07-30 08:44:20 -07001549 && reqUserId != UserHandle.getUserId(uidState.uid)) {
Alexandra Gherghinad6a98972014-08-04 17:05:34 +01001550 // Skip any ops for a different user
1551 continue;
1552 }
Svet Ganov2af57082015-07-30 08:44:20 -07001553
1554 Map<String, Ops> packages = uidState.pkgOps;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001555 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001556 boolean uidChanged = false;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001557 while (it.hasNext()) {
1558 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001559 String packageName = ent.getKey();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001560 if (reqPackageName != null && !reqPackageName.equals(packageName)) {
1561 // Skip any ops for a different package
1562 continue;
1563 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001564 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001565 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -07001566 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -07001567 if (AppOpsManager.opAllowsReset(curOp.op)
1568 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -07001569 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001570 changed = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001571 uidChanged = true;
Svet Ganovaf189e32019-02-15 18:45:29 -08001572 final int uid = curOp.uidState.uid;
1573 callbacks = addCallbacks(callbacks, curOp.op, uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -07001574 mOpModeWatchers.get(curOp.op));
Svet Ganovaf189e32019-02-15 18:45:29 -08001575 callbacks = addCallbacks(callbacks, curOp.op, uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -07001576 mPackageModeWatchers.get(packageName));
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001577 if (!curOp.hasAnyTime()) {
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001578 pkgOps.removeAt(j);
1579 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001580 }
1581 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001582 if (pkgOps.size() == 0) {
1583 it.remove();
1584 }
1585 }
Svet Ganov2af57082015-07-30 08:44:20 -07001586 if (uidState.isDefault()) {
1587 mUidStates.remove(uidState.uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001588 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001589 if (uidChanged) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001590 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001591 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001592 }
Svet Ganov2af57082015-07-30 08:44:20 -07001593
Dianne Hackborn607b4142013-08-02 18:10:10 -07001594 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001595 scheduleFastWriteLocked();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001596 }
1597 }
1598 if (callbacks != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001599 for (Map.Entry<ModeCallback, ArrayList<ChangeRec>> ent : callbacks.entrySet()) {
1600 ModeCallback cb = ent.getKey();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001601 ArrayList<ChangeRec> reports = ent.getValue();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001602 for (int i=0; i<reports.size(); i++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001603 ChangeRec rep = reports.get(i);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001604 mHandler.sendMessage(PooledLambda.obtainMessage(
1605 AppOpsService::notifyOpChanged,
1606 this, cb, rep.op, rep.uid, rep.pkg));
Dianne Hackborn607b4142013-08-02 18:10:10 -07001607 }
1608 }
1609 }
1610 }
1611
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001612 private void evalAllForegroundOpsLocked() {
1613 for (int uidi = mUidStates.size() - 1; uidi >= 0; uidi--) {
1614 final UidState uidState = mUidStates.valueAt(uidi);
1615 if (uidState.foregroundOps != null) {
1616 uidState.evalForegroundOps(mOpModeWatchers);
1617 }
1618 }
1619 }
1620
Dianne Hackbornc2293022013-02-06 23:14:49 -08001621 @Override
1622 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001623 startWatchingModeWithFlags(op, packageName, 0, callback);
1624 }
1625
1626 @Override
1627 public void startWatchingModeWithFlags(int op, String packageName, int flags,
1628 IAppOpsCallback callback) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001629 int watchedUid = -1;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001630 final int callingUid = Binder.getCallingUid();
1631 final int callingPid = Binder.getCallingPid();
Dianne Hackborn5376edd2018-06-05 13:21:16 -07001632 // TODO: should have a privileged permission to protect this.
1633 // Also, if the caller has requested WATCH_FOREGROUND_CHANGES, should we require
1634 // the USAGE_STATS permission since this can provide information about when an
1635 // app is in the foreground?
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001636 Preconditions.checkArgumentInRange(op, AppOpsManager.OP_NONE,
1637 AppOpsManager._NUM_OP - 1, "Invalid op code: " + op);
Svetoslav Ganov8de59712015-12-09 18:25:13 -08001638 if (callback == null) {
1639 return;
1640 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001641 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -07001642 op = (op != AppOpsManager.OP_NONE) ? AppOpsManager.opToSwitch(op) : op;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001643 ModeCallback cb = mModeWatchers.get(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -08001644 if (cb == null) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001645 cb = new ModeCallback(callback, watchedUid, flags, callingUid, callingPid);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001646 mModeWatchers.put(callback.asBinder(), cb);
1647 }
1648 if (op != AppOpsManager.OP_NONE) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001649 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(op);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001650 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08001651 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001652 mOpModeWatchers.put(op, cbs);
1653 }
1654 cbs.add(cb);
1655 }
1656 if (packageName != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001657 ArraySet<ModeCallback> cbs = mPackageModeWatchers.get(packageName);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001658 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08001659 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001660 mPackageModeWatchers.put(packageName, cbs);
1661 }
1662 cbs.add(cb);
1663 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001664 evalAllForegroundOpsLocked();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001665 }
1666 }
1667
1668 @Override
1669 public void stopWatchingMode(IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -08001670 if (callback == null) {
1671 return;
1672 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001673 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001674 ModeCallback cb = mModeWatchers.remove(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -08001675 if (cb != null) {
1676 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001677 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001678 ArraySet<ModeCallback> cbs = mOpModeWatchers.valueAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001679 cbs.remove(cb);
1680 if (cbs.size() <= 0) {
1681 mOpModeWatchers.removeAt(i);
1682 }
1683 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001684 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001685 ArraySet<ModeCallback> cbs = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001686 cbs.remove(cb);
1687 if (cbs.size() <= 0) {
1688 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001689 }
1690 }
1691 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001692 evalAllForegroundOpsLocked();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001693 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001694 }
1695
1696 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001697 public IBinder getToken(IBinder clientToken) {
1698 synchronized (this) {
1699 ClientState cs = mClients.get(clientToken);
1700 if (cs == null) {
1701 cs = new ClientState(clientToken);
1702 mClients.put(clientToken, cs);
1703 }
1704 return cs;
1705 }
1706 }
1707
Svet Ganovd873ae62018-06-25 16:39:23 -07001708 public CheckOpsDelegate getAppOpsServiceDelegate() {
1709 synchronized (this) {
1710 return mCheckOpsDelegate;
1711 }
1712 }
1713
1714 public void setAppOpsServiceDelegate(CheckOpsDelegate delegate) {
1715 synchronized (this) {
1716 mCheckOpsDelegate = delegate;
1717 }
1718 }
1719
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001720 @Override
Svet Ganov9d528a12018-12-19 17:23:11 -08001721 public int checkOperationRaw(int code, int uid, String packageName) {
1722 return checkOperationInternal(code, uid, packageName, true /*raw*/);
1723 }
1724
1725 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -08001726 public int checkOperation(int code, int uid, String packageName) {
Svet Ganov9d528a12018-12-19 17:23:11 -08001727 return checkOperationInternal(code, uid, packageName, false /*raw*/);
1728 }
1729
1730 private int checkOperationInternal(int code, int uid, String packageName, boolean raw) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001731 final CheckOpsDelegate delegate;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001732 synchronized (this) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001733 delegate = mCheckOpsDelegate;
1734 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001735 if (delegate == null) {
Svet Ganov9d528a12018-12-19 17:23:11 -08001736 return checkOperationImpl(code, uid, packageName, raw);
Todd Kennedy556efba2018-11-15 07:43:55 -08001737 }
Svet Ganov9d528a12018-12-19 17:23:11 -08001738 return delegate.checkOperation(code, uid, packageName, raw,
Svet Ganovd873ae62018-06-25 16:39:23 -07001739 AppOpsService.this::checkOperationImpl);
1740 }
1741
Svet Ganov9d528a12018-12-19 17:23:11 -08001742 private int checkOperationImpl(int code, int uid, String packageName,
1743 boolean raw) {
Todd Kennedy556efba2018-11-15 07:43:55 -08001744 verifyIncomingUid(uid);
1745 verifyIncomingOp(code);
1746 String resolvedPackageName = resolvePackageName(uid, packageName);
1747 if (resolvedPackageName == null) {
1748 return AppOpsManager.MODE_IGNORED;
1749 }
Svet Ganov9d528a12018-12-19 17:23:11 -08001750 return checkOperationUnchecked(code, uid, resolvedPackageName, raw);
Todd Kennedy556efba2018-11-15 07:43:55 -08001751 }
1752
Philip P. Moltmann724150d2019-03-11 17:01:05 -07001753 /**
1754 * @see #checkOperationUnchecked(int, int, String, boolean, boolean)
1755 */
1756 private @Mode int checkOperationUnchecked(int code, int uid, @NonNull String packageName,
1757 boolean raw) {
1758 return checkOperationUnchecked(code, uid, packageName, raw, true);
1759 }
1760
1761 /**
1762 * Get the mode of an app-op.
1763 *
1764 * @param code The code of the op
1765 * @param uid The uid of the package the op belongs to
1766 * @param packageName The package the op belongs to
1767 * @param raw If the raw state of eval-ed state should be checked.
1768 * @param verify If the code should check the package belongs to the uid
1769 *
1770 * @return The mode of the op
1771 */
1772 private @Mode int checkOperationUnchecked(int code, int uid, @NonNull String packageName,
1773 boolean raw, boolean verify) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001774 synchronized (this) {
Philip P. Moltmann724150d2019-03-11 17:01:05 -07001775 if (verify) {
1776 checkPackage(uid, packageName);
1777 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001778 if (isOpRestrictedLocked(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001779 return AppOpsManager.MODE_IGNORED;
1780 }
Svet Ganov2af57082015-07-30 08:44:20 -07001781 code = AppOpsManager.opToSwitch(code);
1782 UidState uidState = getUidStateLocked(uid, false);
Svet Ganovee438d42017-01-19 18:04:38 -08001783 if (uidState != null && uidState.opModes != null
1784 && uidState.opModes.indexOfKey(code) >= 0) {
Svet Ganov9d528a12018-12-19 17:23:11 -08001785 final int rawMode = uidState.opModes.get(code);
Svet Ganovaf189e32019-02-15 18:45:29 -08001786 return raw ? rawMode : uidState.evalMode(code, rawMode);
Svet Ganov2af57082015-07-30 08:44:20 -07001787 }
Philip P. Moltmann724150d2019-03-11 17:01:05 -07001788 Op op = getOpLocked(code, uid, packageName, false, verify, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001789 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -07001790 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001791 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001792 return raw ? op.mode : op.evalMode();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001793 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001794 }
1795
1796 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001797 public int checkAudioOperation(int code, int usage, int uid, String packageName) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001798 final CheckOpsDelegate delegate;
John Spurlock1af30c72014-03-10 08:33:35 -04001799 synchronized (this) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001800 delegate = mCheckOpsDelegate;
1801 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001802 if (delegate == null) {
1803 return checkAudioOperationImpl(code, usage, uid, packageName);
1804 }
Svet Ganovd873ae62018-06-25 16:39:23 -07001805 return delegate.checkAudioOperation(code, usage, uid, packageName,
1806 AppOpsService.this::checkAudioOperationImpl);
1807 }
1808
1809 private int checkAudioOperationImpl(int code, int usage, int uid, String packageName) {
Todd Kennedy556efba2018-11-15 07:43:55 -08001810 boolean suspended;
1811 try {
1812 suspended = isPackageSuspendedForUser(packageName, uid);
1813 } catch (IllegalArgumentException ex) {
1814 // Package not found.
1815 suspended = false;
1816 }
1817
1818 if (suspended) {
1819 Slog.i(TAG, "Audio disabled for suspended package=" + packageName
1820 + " for uid=" + uid);
1821 return AppOpsManager.MODE_IGNORED;
1822 }
1823
Svet Ganovd873ae62018-06-25 16:39:23 -07001824 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001825 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -04001826 if (mode != AppOpsManager.MODE_ALLOWED) {
1827 return mode;
1828 }
1829 }
1830 return checkOperation(code, uid, packageName);
1831 }
1832
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001833 private boolean isPackageSuspendedForUser(String pkg, int uid) {
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001834 try {
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001835 return AppGlobals.getPackageManager().isPackageSuspendedForUser(
1836 pkg, UserHandle.getUserId(uid));
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001837 } catch (RemoteException re) {
1838 throw new SecurityException("Could not talk to package manager service");
1839 }
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001840 }
1841
John Spurlock7b414672014-07-18 13:02:39 -04001842 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
1843 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1844 if (usageRestrictions != null) {
1845 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001846 if (r != null && !r.exceptionPackages.contains(packageName)) {
1847 return r.mode;
1848 }
1849 }
1850 return AppOpsManager.MODE_ALLOWED;
1851 }
1852
1853 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001854 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -04001855 String[] exceptionPackages) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07001856 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
John Spurlock1af30c72014-03-10 08:33:35 -04001857 verifyIncomingUid(uid);
1858 verifyIncomingOp(code);
1859 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001860 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1861 if (usageRestrictions == null) {
1862 usageRestrictions = new SparseArray<Restriction>();
1863 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -04001864 }
John Spurlock7b414672014-07-18 13:02:39 -04001865 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001866 if (mode != AppOpsManager.MODE_ALLOWED) {
1867 final Restriction r = new Restriction();
1868 r.mode = mode;
1869 if (exceptionPackages != null) {
1870 final int N = exceptionPackages.length;
1871 r.exceptionPackages = new ArraySet<String>(N);
1872 for (int i = 0; i < N; i++) {
1873 final String pkg = exceptionPackages[i];
1874 if (pkg != null) {
1875 r.exceptionPackages.add(pkg.trim());
1876 }
1877 }
1878 }
John Spurlock7b414672014-07-18 13:02:39 -04001879 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -04001880 }
1881 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001882
1883 mHandler.sendMessage(PooledLambda.obtainMessage(
Svet Ganov3a95f832018-03-23 17:44:30 -07001884 AppOpsService::notifyWatchersOfChange, this, code, UID_ANY));
John Spurlock1af30c72014-03-10 08:33:35 -04001885 }
1886
1887 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001888 public int checkPackage(int uid, String packageName) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001889 Preconditions.checkNotNull(packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001890 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001891 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1892 true /* uidMismatchExpected */);
1893 if (ops != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001894 return AppOpsManager.MODE_ALLOWED;
1895 } else {
1896 return AppOpsManager.MODE_ERRORED;
1897 }
1898 }
1899 }
1900
1901 @Override
Svet Ganovd873ae62018-06-25 16:39:23 -07001902 public int noteProxyOperation(int code, int proxyUid,
1903 String proxyPackageName, int proxiedUid, String proxiedPackageName) {
1904 verifyIncomingUid(proxyUid);
Svet Ganov99b60432015-06-27 13:15:22 -07001905 verifyIncomingOp(code);
Svet Ganovaf189e32019-02-15 18:45:29 -08001906
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001907 String resolveProxyPackageName = resolvePackageName(proxyUid, proxyPackageName);
1908 if (resolveProxyPackageName == null) {
1909 return AppOpsManager.MODE_IGNORED;
1910 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001911
1912 final boolean isProxyTrusted = mContext.checkPermission(
1913 Manifest.permission.UPDATE_APP_OPS_STATS, -1, proxyUid)
1914 == PackageManager.PERMISSION_GRANTED;
1915
1916 final int proxyFlags = isProxyTrusted ? AppOpsManager.OP_FLAG_TRUSTED_PROXY
1917 : AppOpsManager.OP_FLAG_UNTRUSTED_PROXY;
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001918 final int proxyMode = noteOperationUnchecked(code, proxyUid,
Svet Ganovaf189e32019-02-15 18:45:29 -08001919 resolveProxyPackageName, Process.INVALID_UID, null, proxyFlags);
Svet Ganov99b60432015-06-27 13:15:22 -07001920 if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
1921 return proxyMode;
1922 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001923
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001924 String resolveProxiedPackageName = resolvePackageName(proxiedUid, proxiedPackageName);
1925 if (resolveProxiedPackageName == null) {
1926 return AppOpsManager.MODE_IGNORED;
1927 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001928 final int proxiedFlags = isProxyTrusted ? AppOpsManager.OP_FLAG_TRUSTED_PROXIED
1929 : AppOpsManager.OP_FLAG_UNTRUSTED_PROXIED;
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001930 return noteOperationUnchecked(code, proxiedUid, resolveProxiedPackageName,
Svet Ganovaf189e32019-02-15 18:45:29 -08001931 proxyUid, resolveProxyPackageName, proxiedFlags);
Svet Ganov99b60432015-06-27 13:15:22 -07001932 }
1933
1934 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001935 public int noteOperation(int code, int uid, String packageName) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001936 final CheckOpsDelegate delegate;
1937 synchronized (this) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001938 delegate = mCheckOpsDelegate;
1939 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001940 if (delegate == null) {
1941 return noteOperationImpl(code, uid, packageName);
1942 }
Svet Ganovd873ae62018-06-25 16:39:23 -07001943 return delegate.noteOperation(code, uid, packageName,
1944 AppOpsService.this::noteOperationImpl);
1945 }
1946
1947 private int noteOperationImpl(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001948 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001949 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001950 String resolvedPackageName = resolvePackageName(uid, packageName);
1951 if (resolvedPackageName == null) {
1952 return AppOpsManager.MODE_IGNORED;
1953 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001954 return noteOperationUnchecked(code, uid, resolvedPackageName, Process.INVALID_UID, null,
1955 AppOpsManager.OP_FLAG_SELF);
Svet Ganov99b60432015-06-27 13:15:22 -07001956 }
1957
1958 private int noteOperationUnchecked(int code, int uid, String packageName,
Svet Ganovaf189e32019-02-15 18:45:29 -08001959 int proxyUid, String proxyPackageName, @OpFlags int flags) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001960 synchronized (this) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001961 final Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
Yohei Yukawaa965d652017-10-12 15:02:26 -07001962 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001963 if (ops == null) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -08001964 scheduleOpNotedIfNeededLocked(code, uid, packageName,
1965 AppOpsManager.MODE_IGNORED);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001966 if (DEBUG) Slog.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001967 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001968 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001969 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001970 final Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07001971 if (isOpRestrictedLocked(uid, code, packageName)) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -08001972 scheduleOpNotedIfNeededLocked(code, uid, packageName,
1973 AppOpsManager.MODE_IGNORED);
Jason Monk62062992014-05-06 09:55:28 -04001974 return AppOpsManager.MODE_IGNORED;
1975 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001976 final UidState uidState = ops.uidState;
Svet Ganovaf189e32019-02-15 18:45:29 -08001977 if (op.running) {
1978 final OpEntry entry = new OpEntry(op.op, op.running, op.mode, op.mAccessTimes,
1979 op.mRejectTimes, op.mDurations, op.mProxyUids, op.mProxyPackageNames);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001980 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
Svet Ganovaf189e32019-02-15 18:45:29 -08001981 + " code " + code + " time=" + entry.getLastAccessTime(uidState.state,
1982 uidState.state, flags) + " duration=" + entry.getLastDuration(
1983 uidState.state, uidState.state, flags));
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001984 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001985
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001986 final int switchCode = AppOpsManager.opToSwitch(code);
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001987 // If there is a non-default per UID policy (we set UID op mode only if
1988 // non-default) it takes over, otherwise use the per package policy.
1989 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Svet Ganovaf189e32019-02-15 18:45:29 -08001990 final int uidMode = uidState.evalMode(code, uidState.opModes.get(switchCode));
Svet Ganov2af57082015-07-30 08:44:20 -07001991 if (uidMode != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001992 if (DEBUG) Slog.d(TAG, "noteOperation: uid reject #" + uidMode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07001993 + switchCode + " (" + code + ") uid " + uid + " package "
1994 + packageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08001995 op.rejected(System.currentTimeMillis(), proxyUid, proxyPackageName,
1996 uidState.state, flags);
1997 mHistoricalRegistry.incrementOpRejected(code, uid, packageName,
1998 uidState.state, flags);
Svet Ganovb3d2ae22018-12-17 22:06:15 -08001999 scheduleOpNotedIfNeededLocked(code, uid, packageName, uidMode);
Svet Ganov2af57082015-07-30 08:44:20 -07002000 return uidMode;
2001 }
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07002002 } else {
2003 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
Svet Ganovaf189e32019-02-15 18:45:29 -08002004 final int mode = switchOp.evalMode();
2005 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002006 if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + mode + " for code "
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07002007 + switchCode + " (" + code + ") uid " + uid + " package "
2008 + packageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08002009 op.rejected(System.currentTimeMillis(), proxyUid, proxyPackageName,
2010 uidState.state, flags);
2011 mHistoricalRegistry.incrementOpRejected(code, uid, packageName,
2012 uidState.state, flags);
2013 scheduleOpNotedIfNeededLocked(code, uid, packageName, mode);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002014 return mode;
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07002015 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002016 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002017 if (DEBUG) Slog.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002018 + " package " + packageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08002019 op.accessed(System.currentTimeMillis(), proxyUid, proxyPackageName,
2020 uidState.state, flags);
Svet Ganov8455ba22019-01-02 13:05:56 -08002021 mHistoricalRegistry.incrementOpAccessedCount(op.op, uid, packageName,
Svet Ganovaf189e32019-02-15 18:45:29 -08002022 uidState.state, flags);
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002023 scheduleOpNotedIfNeededLocked(code, uid, packageName,
2024 AppOpsManager.MODE_ALLOWED);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002025 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002026 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002027 }
2028
2029 @Override
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002030 public void startWatchingActive(int[] ops, IAppOpsActiveCallback callback) {
Svet Ganovf7b47252018-02-26 11:11:27 -08002031 int watchedUid = -1;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002032 final int callingUid = Binder.getCallingUid();
2033 final int callingPid = Binder.getCallingPid();
Svet Ganovf7b47252018-02-26 11:11:27 -08002034 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
2035 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002036 watchedUid = callingUid;
Svet Ganovf7b47252018-02-26 11:11:27 -08002037 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002038 if (ops != null) {
2039 Preconditions.checkArrayElementsInRange(ops, 0,
2040 AppOpsManager._NUM_OP - 1, "Invalid op code in: " + Arrays.toString(ops));
2041 }
2042 if (callback == null) {
2043 return;
2044 }
2045 synchronized (this) {
2046 SparseArray<ActiveCallback> callbacks = mActiveWatchers.get(callback.asBinder());
2047 if (callbacks == null) {
2048 callbacks = new SparseArray<>();
2049 mActiveWatchers.put(callback.asBinder(), callbacks);
2050 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002051 final ActiveCallback activeCallback = new ActiveCallback(callback, watchedUid,
2052 callingUid, callingPid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002053 for (int op : ops) {
2054 callbacks.put(op, activeCallback);
2055 }
2056 }
2057 }
2058
2059 @Override
2060 public void stopWatchingActive(IAppOpsActiveCallback callback) {
2061 if (callback == null) {
2062 return;
2063 }
2064 synchronized (this) {
2065 final SparseArray<ActiveCallback> activeCallbacks =
2066 mActiveWatchers.remove(callback.asBinder());
2067 if (activeCallbacks == null) {
2068 return;
2069 }
2070 final int callbackCount = activeCallbacks.size();
2071 for (int i = 0; i < callbackCount; i++) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002072 activeCallbacks.valueAt(i).destroy();
2073 }
2074 }
2075 }
2076
2077 @Override
2078 public void startWatchingNoted(@NonNull int[] ops, @NonNull IAppOpsNotedCallback callback) {
2079 int watchedUid = Process.INVALID_UID;
2080 final int callingUid = Binder.getCallingUid();
2081 final int callingPid = Binder.getCallingPid();
2082 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
2083 != PackageManager.PERMISSION_GRANTED) {
2084 watchedUid = callingUid;
2085 }
2086 Preconditions.checkArgument(!ArrayUtils.isEmpty(ops), "Ops cannot be null or empty");
2087 Preconditions.checkArrayElementsInRange(ops, 0, AppOpsManager._NUM_OP - 1,
2088 "Invalid op code in: " + Arrays.toString(ops));
2089 Preconditions.checkNotNull(callback, "Callback cannot be null");
2090 synchronized (this) {
2091 SparseArray<NotedCallback> callbacks = mNotedWatchers.get(callback.asBinder());
2092 if (callbacks == null) {
2093 callbacks = new SparseArray<>();
2094 mNotedWatchers.put(callback.asBinder(), callbacks);
2095 }
2096 final NotedCallback notedCallback = new NotedCallback(callback, watchedUid,
2097 callingUid, callingPid);
2098 for (int op : ops) {
2099 callbacks.put(op, notedCallback);
2100 }
2101 }
2102 }
2103
2104 @Override
2105 public void stopWatchingNoted(IAppOpsNotedCallback callback) {
2106 Preconditions.checkNotNull(callback, "Callback cannot be null");
2107 synchronized (this) {
2108 final SparseArray<NotedCallback> notedCallbacks =
2109 mNotedWatchers.remove(callback.asBinder());
2110 if (notedCallbacks == null) {
2111 return;
2112 }
2113 final int callbackCount = notedCallbacks.size();
2114 for (int i = 0; i < callbackCount; i++) {
2115 notedCallbacks.valueAt(i).destroy();
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002116 }
2117 }
2118 }
2119
2120 @Override
Svet Ganovf7b47252018-02-26 11:11:27 -08002121 public int startOperation(IBinder token, int code, int uid, String packageName,
2122 boolean startIfModeDefault) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002123 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08002124 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002125 String resolvedPackageName = resolvePackageName(uid, packageName);
2126 if (resolvedPackageName == null) {
2127 return AppOpsManager.MODE_IGNORED;
2128 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002129 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002130 synchronized (this) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002131 final Ops ops = getOpsRawLocked(uid, resolvedPackageName, true /* edit */,
Yohei Yukawaa965d652017-10-12 15:02:26 -07002132 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002133 if (ops == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002134 if (DEBUG) Slog.d(TAG, "startOperation: no op for code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002135 + " package " + resolvedPackageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07002136 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002137 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002138 final Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07002139 if (isOpRestrictedLocked(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -04002140 return AppOpsManager.MODE_IGNORED;
2141 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002142 final int switchCode = AppOpsManager.opToSwitch(code);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002143 final UidState uidState = ops.uidState;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002144 // If there is a non-default per UID policy (we set UID op mode only if
2145 // non-default) it takes over, otherwise use the per package policy.
Svet Ganovaf189e32019-02-15 18:45:29 -08002146 final int opCode = op.op;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002147 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002148 final int uidMode = uidState.evalMode(code, uidState.opModes.get(switchCode));
Svet Ganovf7b47252018-02-26 11:11:27 -08002149 if (uidMode != AppOpsManager.MODE_ALLOWED
2150 && (!startIfModeDefault || uidMode != AppOpsManager.MODE_DEFAULT)) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002151 if (DEBUG) Slog.d(TAG, "noteOperation: uid reject #" + uidMode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07002152 + switchCode + " (" + code + ") uid " + uid + " package "
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002153 + resolvedPackageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08002154 // We don't support proxy long running ops (start/stop)
2155 op.rejected(System.currentTimeMillis(), -1 /*proxyUid*/,
2156 null /*proxyPackage*/, uidState.state, AppOpsManager.OP_FLAG_SELF);
2157 mHistoricalRegistry.incrementOpRejected(opCode, uid, packageName,
2158 uidState.state, AppOpsManager.OP_FLAG_SELF);
Svet Ganov2af57082015-07-30 08:44:20 -07002159 return uidMode;
2160 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002161 } else {
2162 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
Svet Ganovaf189e32019-02-15 18:45:29 -08002163 final int mode = switchOp.evalMode();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002164 if (mode != AppOpsManager.MODE_ALLOWED
2165 && (!startIfModeDefault || mode != AppOpsManager.MODE_DEFAULT)) {
2166 if (DEBUG) Slog.d(TAG, "startOperation: reject #" + mode + " for code "
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002167 + switchCode + " (" + code + ") uid " + uid + " package "
2168 + resolvedPackageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08002169 // We don't support proxy long running ops (start/stop)
2170 op.rejected(System.currentTimeMillis(), -1 /*proxyUid*/,
2171 null /*proxyPackage*/, uidState.state, AppOpsManager.OP_FLAG_SELF);
2172 mHistoricalRegistry.incrementOpRejected(opCode, uid, packageName,
2173 uidState.state, AppOpsManager.OP_FLAG_SELF);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002174 return mode;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002175 }
Svet Ganov2af57082015-07-30 08:44:20 -07002176 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002177 if (DEBUG) Slog.d(TAG, "startOperation: allowing code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002178 + " package " + resolvedPackageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002179 if (op.startNesting == 0) {
2180 op.startRealtime = SystemClock.elapsedRealtime();
Svet Ganovaf189e32019-02-15 18:45:29 -08002181 // We don't support proxy long running ops (start/stop)
2182 op.started(System.currentTimeMillis(), uidState.state,
2183 AppOpsManager.OP_FLAG_SELF);
2184 mHistoricalRegistry.incrementOpAccessedCount(opCode, uid, packageName,
2185 uidState.state, AppOpsManager.OP_FLAG_SELF);
2186
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002187 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002188 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002189 op.startNesting++;
2190 uidState.startNesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002191 if (client.mStartedOps != null) {
2192 client.mStartedOps.add(op);
2193 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002194 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002195
2196 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002197 }
2198
2199 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002200 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002201 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08002202 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002203 String resolvedPackageName = resolvePackageName(uid, packageName);
2204 if (resolvedPackageName == null) {
2205 return;
2206 }
2207 if (!(token instanceof ClientState)) {
2208 return;
2209 }
2210 ClientState client = (ClientState) token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002211 synchronized (this) {
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07002212 Op op = getOpLocked(code, uid, resolvedPackageName, true, true, false);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002213 if (op == null) {
2214 return;
2215 }
Svet Ganovf7b47252018-02-26 11:11:27 -08002216 if (!client.mStartedOps.remove(op)) {
Svet Ganovf5d5af12018-03-18 11:51:17 -07002217 // We finish ops when packages get removed to guarantee no dangling
2218 // started ops. However, some part of the system may asynchronously
2219 // finish ops for an already gone package. Hence, finishing an op
2220 // for a non existing package is fine and we don't log as a wtf.
2221 final long identity = Binder.clearCallingIdentity();
2222 try {
2223 if (LocalServices.getService(PackageManagerInternal.class).getPackageUid(
2224 resolvedPackageName, 0, UserHandle.getUserId(uid)) < 0) {
2225 Slog.i(TAG, "Finishing op=" + AppOpsManager.opToName(code)
2226 + " for non-existing package=" + resolvedPackageName
2227 + " in uid=" + uid);
2228 return;
2229 }
2230 } finally {
2231 Binder.restoreCallingIdentity(identity);
2232 }
Svet Ganovaf189e32019-02-15 18:45:29 -08002233 Slog.wtf(TAG, "Operation not started: uid=" + op.uidState.uid + " pkg="
Svet Ganovf5d5af12018-03-18 11:51:17 -07002234 + op.packageName + " op=" + AppOpsManager.opToName(op.op));
Svet Ganov31d83ae2018-03-15 10:45:56 -07002235 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002236 }
Svet Ganova7a0db62018-02-27 20:08:01 -08002237 finishOperationLocked(op, /*finishNested*/ false);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002238 if (op.startNesting <= 0) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002239 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, false);
2240 }
2241 }
2242 }
2243
2244 private void scheduleOpActiveChangedIfNeededLocked(int code, int uid, String packageName,
2245 boolean active) {
2246 ArraySet<ActiveCallback> dispatchedCallbacks = null;
2247 final int callbackListCount = mActiveWatchers.size();
2248 for (int i = 0; i < callbackListCount; i++) {
2249 final SparseArray<ActiveCallback> callbacks = mActiveWatchers.valueAt(i);
2250 ActiveCallback callback = callbacks.get(code);
2251 if (callback != null) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002252 if (callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
Svet Ganovf7b47252018-02-26 11:11:27 -08002253 continue;
2254 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002255 if (dispatchedCallbacks == null) {
2256 dispatchedCallbacks = new ArraySet<>();
2257 }
2258 dispatchedCallbacks.add(callback);
2259 }
2260 }
2261 if (dispatchedCallbacks == null) {
2262 return;
2263 }
2264 mHandler.sendMessage(PooledLambda.obtainMessage(
2265 AppOpsService::notifyOpActiveChanged,
2266 this, dispatchedCallbacks, code, uid, packageName, active));
2267 }
2268
2269 private void notifyOpActiveChanged(ArraySet<ActiveCallback> callbacks,
2270 int code, int uid, String packageName, boolean active) {
2271 // There are components watching for mode changes such as window manager
2272 // and location manager which are in our process. The callbacks in these
2273 // components may require permissions our remote caller does not have.
2274 final long identity = Binder.clearCallingIdentity();
2275 try {
2276 final int callbackCount = callbacks.size();
2277 for (int i = 0; i < callbackCount; i++) {
2278 final ActiveCallback callback = callbacks.valueAt(i);
2279 try {
2280 callback.mCallback.opActiveChanged(code, uid, packageName, active);
2281 } catch (RemoteException e) {
2282 /* do nothing */
2283 }
2284 }
2285 } finally {
2286 Binder.restoreCallingIdentity(identity);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002287 }
2288 }
2289
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002290 private void scheduleOpNotedIfNeededLocked(int code, int uid, String packageName,
2291 int result) {
2292 ArraySet<NotedCallback> dispatchedCallbacks = null;
2293 final int callbackListCount = mNotedWatchers.size();
2294 for (int i = 0; i < callbackListCount; i++) {
2295 final SparseArray<NotedCallback> callbacks = mNotedWatchers.valueAt(i);
2296 final NotedCallback callback = callbacks.get(code);
2297 if (callback != null) {
2298 if (callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
2299 continue;
2300 }
2301 if (dispatchedCallbacks == null) {
2302 dispatchedCallbacks = new ArraySet<>();
2303 }
2304 dispatchedCallbacks.add(callback);
2305 }
2306 }
2307 if (dispatchedCallbacks == null) {
2308 return;
2309 }
2310 mHandler.sendMessage(PooledLambda.obtainMessage(
2311 AppOpsService::notifyOpChecked,
2312 this, dispatchedCallbacks, code, uid, packageName, result));
2313 }
2314
2315 private void notifyOpChecked(ArraySet<NotedCallback> callbacks,
2316 int code, int uid, String packageName, int result) {
2317 // There are components watching for checks in our process. The callbacks in
2318 // these components may require permissions our remote caller does not have.
2319 final long identity = Binder.clearCallingIdentity();
2320 try {
2321 final int callbackCount = callbacks.size();
2322 for (int i = 0; i < callbackCount; i++) {
2323 final NotedCallback callback = callbacks.valueAt(i);
2324 try {
2325 callback.mCallback.opNoted(code, uid, packageName, result);
2326 } catch (RemoteException e) {
2327 /* do nothing */
2328 }
2329 }
2330 } finally {
2331 Binder.restoreCallingIdentity(identity);
2332 }
2333 }
2334
Svet Ganovb9d71a62015-04-30 10:38:13 -07002335 @Override
2336 public int permissionToOpCode(String permission) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002337 if (permission == null) {
2338 return AppOpsManager.OP_NONE;
2339 }
Svet Ganovb9d71a62015-04-30 10:38:13 -07002340 return AppOpsManager.permissionToOpCode(permission);
2341 }
2342
Svet Ganova7a0db62018-02-27 20:08:01 -08002343 void finishOperationLocked(Op op, boolean finishNested) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002344 final int opCode = op.op;
2345 final int uid = op.uidState.uid;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002346 if (op.startNesting <= 1 || finishNested) {
2347 if (op.startNesting == 1 || finishNested) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002348 // We don't support proxy long running ops (start/stop)
2349 final long duration = SystemClock.elapsedRealtime() - op.startRealtime;
2350 op.finished(System.currentTimeMillis(), duration, op.uidState.state,
2351 AppOpsManager.OP_FLAG_SELF);
2352 mHistoricalRegistry.increaseOpAccessDuration(opCode, uid, op.packageName,
2353 op.uidState.state, AppOpsManager.OP_FLAG_SELF, duration);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002354 } else {
Svet Ganovaf189e32019-02-15 18:45:29 -08002355 final OpEntry entry = new OpEntry(op.op, op.running, op.mode, op.mAccessTimes,
2356 op.mRejectTimes, op.mDurations, op.mProxyUids, op.mProxyPackageNames);
2357 Slog.w(TAG, "Finishing op nesting under-run: uid " + uid + " pkg "
2358 + op.packageName + " code " + opCode + " time="
2359 + entry.getLastAccessTime(OP_FLAGS_ALL)
2360 + " duration=" + entry.getLastDuration(MAX_PRIORITY_UID_STATE,
2361 MIN_PRIORITY_UID_STATE, OP_FLAGS_ALL) + " nesting=" + op.startNesting);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002362 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002363 if (op.startNesting >= 1) {
2364 op.uidState.startNesting -= op.startNesting;
2365 }
2366 op.startNesting = 0;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002367 } else {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002368 op.startNesting--;
2369 op.uidState.startNesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002370 }
2371 }
2372
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002373 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002374 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002375 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002376 }
2377 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002378 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002379 }
2380 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
2381 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002382 }
2383
Dianne Hackborn961321f2013-02-05 17:22:41 -08002384 private void verifyIncomingOp(int op) {
2385 if (op >= 0 && op < AppOpsManager._NUM_OP) {
2386 return;
2387 }
2388 throw new IllegalArgumentException("Bad operation #" + op);
2389 }
2390
Philip P. Moltmann724150d2019-03-11 17:01:05 -07002391 private @Nullable UidState getUidStateLocked(int uid, boolean edit) {
Svet Ganov2af57082015-07-30 08:44:20 -07002392 UidState uidState = mUidStates.get(uid);
2393 if (uidState == null) {
2394 if (!edit) {
2395 return null;
2396 }
2397 uidState = new UidState(uid);
2398 mUidStates.put(uid, uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002399 } else {
2400 if (uidState.pendingStateCommitTime != 0) {
Dianne Hackborn9fb93502018-06-18 12:29:44 -07002401 if (uidState.pendingStateCommitTime < mLastRealtime) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002402 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002403 } else {
Dianne Hackborn9fb93502018-06-18 12:29:44 -07002404 mLastRealtime = SystemClock.elapsedRealtime();
2405 if (uidState.pendingStateCommitTime < mLastRealtime) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002406 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002407 }
2408 }
2409 }
Svet Ganov2af57082015-07-30 08:44:20 -07002410 }
2411 return uidState;
2412 }
2413
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002414 private void commitUidPendingStateLocked(UidState uidState) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002415 final boolean lastForeground = uidState.state <= UID_STATE_MAX_LAST_NON_RESTRICTED;
2416 final boolean nowForeground = uidState.pendingState <= UID_STATE_MAX_LAST_NON_RESTRICTED;
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002417 uidState.state = uidState.pendingState;
2418 uidState.pendingStateCommitTime = 0;
Dianne Hackborne93ab412018-05-14 17:52:30 -07002419 if (uidState.hasForegroundWatchers && lastForeground != nowForeground) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002420 for (int fgi = uidState.foregroundOps.size() - 1; fgi >= 0; fgi--) {
2421 if (!uidState.foregroundOps.valueAt(fgi)) {
2422 continue;
2423 }
2424 final int code = uidState.foregroundOps.keyAt(fgi);
Svet Ganovaf189e32019-02-15 18:45:29 -08002425 // For location ops we consider fg state only if the fg service
2426 // is of location type, for all other ops any fg service will do.
2427 final long resolvedLastRestrictedUidState = resolveFirstUnrestrictedUidState(code);
2428 final boolean resolvedLastFg = uidState.state <= resolvedLastRestrictedUidState;
2429 final boolean resolvedNowBg = uidState.pendingState
2430 <= resolvedLastRestrictedUidState;
2431 if (resolvedLastFg == resolvedNowBg) {
2432 continue;
2433 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002434 final ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
2435 if (callbacks != null) {
2436 for (int cbi = callbacks.size() - 1; cbi >= 0; cbi--) {
2437 final ModeCallback callback = callbacks.valueAt(cbi);
2438 if ((callback.mFlags & AppOpsManager.WATCH_FOREGROUND_CHANGES) == 0
2439 || !callback.isWatchingUid(uidState.uid)) {
2440 continue;
2441 }
2442 boolean doAllPackages = uidState.opModes != null
Hai Zhang2b98fb32018-09-21 15:18:46 -07002443 && uidState.opModes.indexOfKey(code) >= 0
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002444 && uidState.opModes.get(code) == AppOpsManager.MODE_FOREGROUND;
2445 if (uidState.pkgOps != null) {
2446 for (int pkgi = uidState.pkgOps.size() - 1; pkgi >= 0; pkgi--) {
2447 final Op op = uidState.pkgOps.valueAt(pkgi).get(code);
Svet Ganovaf189e32019-02-15 18:45:29 -08002448 if (op == null) {
2449 continue;
2450 }
2451 if (doAllPackages || op.mode == AppOpsManager.MODE_FOREGROUND) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002452 mHandler.sendMessage(PooledLambda.obtainMessage(
2453 AppOpsService::notifyOpChanged,
2454 this, callback, code, uidState.uid,
2455 uidState.pkgOps.keyAt(pkgi)));
2456 }
2457 }
2458 }
2459 }
2460 }
2461 }
2462 }
2463 }
2464
Yohei Yukawaa965d652017-10-12 15:02:26 -07002465 private Ops getOpsRawLocked(int uid, String packageName, boolean edit,
2466 boolean uidMismatchExpected) {
Svet Ganov2af57082015-07-30 08:44:20 -07002467 UidState uidState = getUidStateLocked(uid, edit);
2468 if (uidState == null) {
2469 return null;
2470 }
2471
2472 if (uidState.pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002473 if (!edit) {
2474 return null;
2475 }
Svet Ganov2af57082015-07-30 08:44:20 -07002476 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002477 }
Svet Ganov2af57082015-07-30 08:44:20 -07002478
2479 Ops ops = uidState.pkgOps.get(packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002480 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002481 if (!edit) {
2482 return null;
2483 }
Jason Monk1c7c3192014-06-26 12:52:18 -04002484 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002485 // This is the first time we have seen this package name under this uid,
2486 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -08002487 if (uid != 0) {
2488 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002489 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -08002490 int pkgUid = -1;
2491 try {
Jason Monk1c7c3192014-06-26 12:52:18 -04002492 ApplicationInfo appInfo = ActivityThread.getPackageManager()
Jeff Sharkeycd654482016-01-08 17:42:11 -07002493 .getApplicationInfo(packageName,
Svet Ganovad0a49b2018-10-29 10:07:08 -07002494 PackageManager.MATCH_DIRECT_BOOT_AWARE
Svet Ganov8455ba22019-01-02 13:05:56 -08002495 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkeycd654482016-01-08 17:42:11 -07002496 UserHandle.getUserId(uid));
Jason Monk1c7c3192014-06-26 12:52:18 -04002497 if (appInfo != null) {
2498 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002499 isPrivileged = (appInfo.privateFlags
2500 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04002501 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08002502 pkgUid = resolveUid(packageName);
2503 if (pkgUid >= 0) {
Chien-Yu Chen75cade02016-01-11 10:56:21 -08002504 isPrivileged = false;
Jason Monk1c7c3192014-06-26 12:52:18 -04002505 }
Dianne Hackborn713df152013-05-17 11:27:57 -07002506 }
Jason Monk1c7c3192014-06-26 12:52:18 -04002507 } catch (RemoteException e) {
2508 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08002509 }
2510 if (pkgUid != uid) {
2511 // Oops! The package name is not valid for the uid they are calling
2512 // under. Abort.
Yohei Yukawaa965d652017-10-12 15:02:26 -07002513 if (!uidMismatchExpected) {
2514 RuntimeException ex = new RuntimeException("here");
2515 ex.fillInStackTrace();
2516 Slog.w(TAG, "Bad call: specified package " + packageName
2517 + " under uid " + uid + " but it is really " + pkgUid, ex);
2518 }
Dianne Hackborn514074f2013-02-11 10:52:46 -08002519 return null;
2520 }
2521 } finally {
2522 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002523 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002524 }
Svet Ganov2af57082015-07-30 08:44:20 -07002525 ops = new Ops(packageName, uidState, isPrivileged);
2526 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002527 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08002528 return ops;
2529 }
2530
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07002531 /**
2532 * Get the state of all ops for a package, <b>don't verify that package belongs to uid</b>.
2533 *
2534 * <p>Usually callers should use {@link #getOpLocked} and not call this directly.
2535 *
2536 * @param uid The uid the of the package
2537 * @param packageName The package name for which to get the state for
2538 * @param edit Iff {@code true} create the {@link Ops} object if not yet created
2539 * @param isPrivileged Whether the package is privileged or not
2540 *
2541 * @return The {@link Ops state} of all ops for the package
2542 */
2543 private @Nullable Ops getOpsRawNoVerifyLocked(int uid, @NonNull String packageName,
2544 boolean edit, boolean isPrivileged) {
2545 UidState uidState = getUidStateLocked(uid, edit);
2546 if (uidState == null) {
2547 return null;
2548 }
2549
2550 if (uidState.pkgOps == null) {
2551 if (!edit) {
2552 return null;
2553 }
2554 uidState.pkgOps = new ArrayMap<>();
2555 }
2556
2557 Ops ops = uidState.pkgOps.get(packageName);
2558 if (ops == null) {
2559 if (!edit) {
2560 return null;
2561 }
2562 ops = new Ops(packageName, uidState, isPrivileged);
2563 uidState.pkgOps.put(packageName, ops);
2564 }
2565 return ops;
2566 }
2567
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002568 private void scheduleWriteLocked() {
2569 if (!mWriteScheduled) {
2570 mWriteScheduled = true;
2571 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
2572 }
2573 }
2574
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002575 private void scheduleFastWriteLocked() {
2576 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002577 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002578 mFastWriteScheduled = true;
2579 mHandler.removeCallbacks(mWriteRunner);
2580 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002581 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002582 }
2583
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07002584 /**
2585 * Get the state of an op for a uid.
2586 *
2587 * @param code The code of the op
2588 * @param uid The uid the of the package
2589 * @param packageName The package name for which to get the state for
2590 * @param edit Iff {@code true} create the {@link Op} object if not yet created
2591 * @param verifyUid Iff {@code true} check that the package belongs to the uid
2592 * @param isPrivileged Whether the package is privileged or not (only used if {@code verifyUid
2593 * == false})
2594 *
2595 * @return The {@link Op state} of the op
2596 */
2597 private @Nullable Op getOpLocked(int code, int uid, @NonNull String packageName, boolean edit,
2598 boolean verifyUid, boolean isPrivileged) {
2599 Ops ops;
2600
2601 if (verifyUid) {
2602 ops = getOpsRawLocked(uid, packageName, edit, false /* uidMismatchExpected */);
2603 } else {
2604 ops = getOpsRawNoVerifyLocked(uid, packageName, edit, isPrivileged);
2605 }
2606
Dianne Hackborn72e39832013-01-18 18:36:09 -08002607 if (ops == null) {
2608 return null;
2609 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002610 return getOpLocked(ops, code, edit);
2611 }
2612
2613 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002614 Op op = ops.get(code);
2615 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002616 if (!edit) {
2617 return null;
2618 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002619 op = new Op(ops.uidState, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002620 ops.put(code, op);
2621 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002622 if (edit) {
2623 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002624 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002625 return op;
2626 }
2627
Svet Ganov442ed572016-08-17 17:29:43 -07002628 private boolean isOpRestrictedLocked(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04002629 int userHandle = UserHandle.getUserId(uid);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002630 final int restrictionSetCount = mOpUserRestrictions.size();
Ruben Brunk29931bc2016-03-11 00:24:26 -08002631
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002632 for (int i = 0; i < restrictionSetCount; i++) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002633 // For each client, check that the given op is not restricted, or that the given
2634 // package is exempt from the restriction.
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002635 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07002636 if (restrictionState.hasRestriction(code, packageName, userHandle)) {
2637 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
2638 // If we are the system, bypass user restrictions for certain codes
2639 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07002640 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
2641 false /* uidMismatchExpected */);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07002642 if ((ops != null) && ops.isPrivileged) {
2643 return false;
2644 }
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002645 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002646 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002647 return true;
Jason Monk1c7c3192014-06-26 12:52:18 -04002648 }
Jason Monk62062992014-05-06 09:55:28 -04002649 }
2650 return false;
2651 }
2652
Dianne Hackborn35654b62013-01-14 17:38:02 -08002653 void readState() {
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002654 int oldVersion = NO_VERSION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08002655 synchronized (mFile) {
2656 synchronized (this) {
2657 FileInputStream stream;
2658 try {
2659 stream = mFile.openRead();
2660 } catch (FileNotFoundException e) {
2661 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
2662 return;
2663 }
2664 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002665 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002666 try {
2667 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002668 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08002669 int type;
2670 while ((type = parser.next()) != XmlPullParser.START_TAG
2671 && type != XmlPullParser.END_DOCUMENT) {
2672 ;
2673 }
2674
2675 if (type != XmlPullParser.START_TAG) {
2676 throw new IllegalStateException("no start tag found");
2677 }
2678
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002679 final String versionString = parser.getAttributeValue(null, "v");
2680 if (versionString != null) {
2681 oldVersion = Integer.parseInt(versionString);
2682 }
2683
Dianne Hackborn35654b62013-01-14 17:38:02 -08002684 int outerDepth = parser.getDepth();
2685 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2686 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2687 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2688 continue;
2689 }
2690
2691 String tagName = parser.getName();
2692 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00002693 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07002694 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07002695 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002696 } else {
2697 Slog.w(TAG, "Unknown element under <app-ops>: "
2698 + parser.getName());
2699 XmlUtils.skipCurrentTag(parser);
2700 }
2701 }
2702 success = true;
2703 } catch (IllegalStateException e) {
2704 Slog.w(TAG, "Failed parsing " + e);
2705 } catch (NullPointerException e) {
2706 Slog.w(TAG, "Failed parsing " + e);
2707 } catch (NumberFormatException e) {
2708 Slog.w(TAG, "Failed parsing " + e);
2709 } catch (XmlPullParserException e) {
2710 Slog.w(TAG, "Failed parsing " + e);
2711 } catch (IOException e) {
2712 Slog.w(TAG, "Failed parsing " + e);
2713 } catch (IndexOutOfBoundsException e) {
2714 Slog.w(TAG, "Failed parsing " + e);
2715 } finally {
2716 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07002717 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002718 }
2719 try {
2720 stream.close();
2721 } catch (IOException e) {
2722 }
2723 }
2724 }
2725 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002726 synchronized (this) {
2727 upgradeLocked(oldVersion);
2728 }
2729 }
2730
2731 private void upgradeRunAnyInBackgroundLocked() {
2732 for (int i = 0; i < mUidStates.size(); i++) {
2733 final UidState uidState = mUidStates.valueAt(i);
2734 if (uidState == null) {
2735 continue;
2736 }
2737 if (uidState.opModes != null) {
2738 final int idx = uidState.opModes.indexOfKey(AppOpsManager.OP_RUN_IN_BACKGROUND);
2739 if (idx >= 0) {
2740 uidState.opModes.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND,
Svet Ganovaf189e32019-02-15 18:45:29 -08002741 uidState.opModes.valueAt(idx));
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002742 }
2743 }
2744 if (uidState.pkgOps == null) {
2745 continue;
2746 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002747 boolean changed = false;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002748 for (int j = 0; j < uidState.pkgOps.size(); j++) {
2749 Ops ops = uidState.pkgOps.valueAt(j);
2750 if (ops != null) {
2751 final Op op = ops.get(AppOpsManager.OP_RUN_IN_BACKGROUND);
2752 if (op != null && op.mode != AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002753 final Op copy = new Op(op.uidState, op.packageName,
Svet Ganovaf189e32019-02-15 18:45:29 -08002754 AppOpsManager.OP_RUN_ANY_IN_BACKGROUND);
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002755 copy.mode = op.mode;
2756 ops.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, copy);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002757 changed = true;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002758 }
2759 }
2760 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002761 if (changed) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002762 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002763 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002764 }
2765 }
2766
2767 private void upgradeLocked(int oldVersion) {
2768 if (oldVersion >= CURRENT_VERSION) {
2769 return;
2770 }
2771 Slog.d(TAG, "Upgrading app-ops xml from version " + oldVersion + " to " + CURRENT_VERSION);
2772 switch (oldVersion) {
2773 case NO_VERSION:
2774 upgradeRunAnyInBackgroundLocked();
2775 // fall through
2776 case 1:
2777 // for future upgrades
2778 }
2779 scheduleFastWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002780 }
2781
Svet Ganovaf189e32019-02-15 18:45:29 -08002782 private void readUidOps(XmlPullParser parser) throws NumberFormatException,
Svet Ganov2af57082015-07-30 08:44:20 -07002783 XmlPullParserException, IOException {
2784 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
2785 int outerDepth = parser.getDepth();
2786 int type;
2787 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2788 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2789 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2790 continue;
2791 }
2792
2793 String tagName = parser.getName();
2794 if (tagName.equals("op")) {
2795 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
2796 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
2797 UidState uidState = getUidStateLocked(uid, true);
2798 if (uidState.opModes == null) {
2799 uidState.opModes = new SparseIntArray();
2800 }
2801 uidState.opModes.put(code, mode);
2802 } else {
2803 Slog.w(TAG, "Unknown element under <uid-ops>: "
2804 + parser.getName());
2805 XmlUtils.skipCurrentTag(parser);
2806 }
2807 }
2808 }
2809
Svet Ganovaf189e32019-02-15 18:45:29 -08002810 private void readPackage(XmlPullParser parser)
2811 throws NumberFormatException, XmlPullParserException, IOException {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002812 String pkgName = parser.getAttributeValue(null, "n");
2813 int outerDepth = parser.getDepth();
2814 int type;
2815 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2816 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2817 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2818 continue;
2819 }
2820
2821 String tagName = parser.getName();
2822 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00002823 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002824 } else {
2825 Slog.w(TAG, "Unknown element under <pkg>: "
2826 + parser.getName());
2827 XmlUtils.skipCurrentTag(parser);
2828 }
2829 }
2830 }
2831
Svet Ganovaf189e32019-02-15 18:45:29 -08002832 private void readUid(XmlPullParser parser, String pkgName)
2833 throws NumberFormatException, XmlPullParserException, IOException {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002834 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Svet Ganovaf189e32019-02-15 18:45:29 -08002835 final UidState uidState = getUidStateLocked(uid, true);
Jason Monk1c7c3192014-06-26 12:52:18 -04002836 String isPrivilegedString = parser.getAttributeValue(null, "p");
2837 boolean isPrivileged = false;
2838 if (isPrivilegedString == null) {
2839 try {
2840 IPackageManager packageManager = ActivityThread.getPackageManager();
2841 if (packageManager != null) {
2842 ApplicationInfo appInfo = ActivityThread.getPackageManager()
2843 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
2844 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002845 isPrivileged = (appInfo.privateFlags
2846 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04002847 }
2848 } else {
2849 // Could not load data, don't add to cache so it will be loaded later.
2850 return;
2851 }
2852 } catch (RemoteException e) {
2853 Slog.w(TAG, "Could not contact PackageManager", e);
2854 }
2855 } else {
2856 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
2857 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002858 int outerDepth = parser.getDepth();
2859 int type;
2860 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2861 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2862 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2863 continue;
2864 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002865 String tagName = parser.getName();
2866 if (tagName.equals("op")) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002867 readOp(parser, uidState, pkgName, isPrivileged);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002868 } else {
2869 Slog.w(TAG, "Unknown element under <pkg>: "
2870 + parser.getName());
2871 XmlUtils.skipCurrentTag(parser);
2872 }
2873 }
Svet Ganovaf189e32019-02-15 18:45:29 -08002874 uidState.evalForegroundOps(mOpModeWatchers);
2875 }
2876
2877 private void readOp(XmlPullParser parser, @NonNull UidState uidState,
2878 @NonNull String pkgName, boolean isPrivileged) throws NumberFormatException,
2879 XmlPullParserException, IOException {
2880 Op op = new Op(uidState, pkgName,
2881 Integer.parseInt(parser.getAttributeValue(null, "n")));
2882
2883 final int mode = XmlUtils.readIntAttribute(parser, "m",
2884 AppOpsManager.opToDefaultMode(op.op));
2885 op.mode = mode;
2886
2887 int outerDepth = parser.getDepth();
2888 int type;
2889 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2890 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2891 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2892 continue;
2893 }
2894 String tagName = parser.getName();
2895 if (tagName.equals("st")) {
2896 final long key = XmlUtils.readLongAttribute(parser, "n");
2897
2898 final int flags = AppOpsManager.extractFlagsFromKey(key);
2899 final int state = AppOpsManager.extractUidStateFromKey(key);
2900
2901 final long accessTime = XmlUtils.readLongAttribute(parser, "t", 0);
2902 final long rejectTime = XmlUtils.readLongAttribute(parser, "r", 0);
2903 final long accessDuration = XmlUtils.readLongAttribute(parser, "d", 0);
2904 final String proxyPkg = XmlUtils.readStringAttribute(parser, "pp");
2905 final int proxyUid = XmlUtils.readIntAttribute(parser, "pu", 0);
2906
2907 if (accessTime > 0) {
2908 op.accessed(accessTime, proxyUid, proxyPkg, state, flags);
2909 }
2910 if (rejectTime > 0) {
2911 op.rejected(rejectTime, proxyUid, proxyPkg, state, flags);
2912 }
2913 if (accessDuration > 0) {
2914 op.running(accessTime, accessDuration, state, flags);
2915 }
2916 } else {
2917 Slog.w(TAG, "Unknown element under <op>: "
2918 + parser.getName());
2919 XmlUtils.skipCurrentTag(parser);
2920 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002921 }
Svet Ganovaf189e32019-02-15 18:45:29 -08002922
2923 if (uidState.pkgOps == null) {
2924 uidState.pkgOps = new ArrayMap<>();
2925 }
2926 Ops ops = uidState.pkgOps.get(pkgName);
2927 if (ops == null) {
2928 ops = new Ops(pkgName, uidState, isPrivileged);
2929 uidState.pkgOps.put(pkgName, ops);
2930 }
2931 ops.put(op.op, op);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002932 }
2933
2934 void writeState() {
2935 synchronized (mFile) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002936 FileOutputStream stream;
2937 try {
2938 stream = mFile.startWrite();
2939 } catch (IOException e) {
2940 Slog.w(TAG, "Failed to write state: " + e);
2941 return;
2942 }
2943
Dianne Hackborne17b4452018-01-10 13:15:40 -08002944 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
2945
Dianne Hackborn35654b62013-01-14 17:38:02 -08002946 try {
2947 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002948 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08002949 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002950 out.startTag(null, "app-ops");
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002951 out.attribute(null, "v", String.valueOf(CURRENT_VERSION));
Svet Ganov2af57082015-07-30 08:44:20 -07002952
2953 final int uidStateCount = mUidStates.size();
2954 for (int i = 0; i < uidStateCount; i++) {
2955 UidState uidState = mUidStates.valueAt(i);
2956 if (uidState.opModes != null && uidState.opModes.size() > 0) {
2957 out.startTag(null, "uid");
2958 out.attribute(null, "n", Integer.toString(uidState.uid));
2959 SparseIntArray uidOpModes = uidState.opModes;
2960 final int opCount = uidOpModes.size();
2961 for (int j = 0; j < opCount; j++) {
2962 final int op = uidOpModes.keyAt(j);
2963 final int mode = uidOpModes.valueAt(j);
2964 out.startTag(null, "op");
2965 out.attribute(null, "n", Integer.toString(op));
2966 out.attribute(null, "m", Integer.toString(mode));
2967 out.endTag(null, "op");
2968 }
2969 out.endTag(null, "uid");
2970 }
2971 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002972
2973 if (allOps != null) {
2974 String lastPkg = null;
2975 for (int i=0; i<allOps.size(); i++) {
2976 AppOpsManager.PackageOps pkg = allOps.get(i);
2977 if (!pkg.getPackageName().equals(lastPkg)) {
2978 if (lastPkg != null) {
2979 out.endTag(null, "pkg");
2980 }
2981 lastPkg = pkg.getPackageName();
2982 out.startTag(null, "pkg");
2983 out.attribute(null, "n", lastPkg);
2984 }
2985 out.startTag(null, "uid");
2986 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04002987 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07002988 Ops ops = getOpsRawLocked(pkg.getUid(), pkg.getPackageName(),
2989 false /* edit */, false /* uidMismatchExpected */);
Jason Monk1c7c3192014-06-26 12:52:18 -04002990 // Should always be present as the list of PackageOps is generated
2991 // from Ops.
2992 if (ops != null) {
2993 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
2994 } else {
2995 out.attribute(null, "p", Boolean.toString(false));
2996 }
2997 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002998 List<AppOpsManager.OpEntry> ops = pkg.getOps();
2999 for (int j=0; j<ops.size(); j++) {
3000 AppOpsManager.OpEntry op = ops.get(j);
3001 out.startTag(null, "op");
3002 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07003003 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003004 out.attribute(null, "m", Integer.toString(op.getMode()));
3005 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003006
3007 final LongSparseArray keys = op.collectKeys();
3008 if (keys == null || keys.size() <= 0) {
Svet Ganov8e5bf962019-03-19 23:59:03 -07003009 out.endTag(null, "op");
Svet Ganovaf189e32019-02-15 18:45:29 -08003010 continue;
3011 }
3012
3013 final int keyCount = keys.size();
3014 for (int k = 0; k < keyCount; k++) {
3015 final long key = keys.keyAt(k);
3016
3017 final int uidState = AppOpsManager.extractUidStateFromKey(key);
3018 final int flags = AppOpsManager.extractFlagsFromKey(key);
3019
3020 final long accessTime = op.getLastAccessTime(
3021 uidState, uidState, flags);
3022 final long rejectTime = op.getLastRejectTime(
3023 uidState, uidState, flags);
3024 final long accessDuration = op.getLastDuration(
3025 uidState, uidState, flags);
3026 final String proxyPkg = op.getProxyPackageName(uidState, flags);
3027 final int proxyUid = op.getProxyUid(uidState, flags);
3028
3029 if (accessTime <= 0 && rejectTime <= 0 && accessDuration <= 0
3030 && proxyPkg == null && proxyUid < 0) {
3031 continue;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003032 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003033
3034 out.startTag(null, "st");
3035 out.attribute(null, "n", Long.toString(key));
3036 if (accessTime > 0) {
3037 out.attribute(null, "t", Long.toString(accessTime));
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003038 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003039 if (rejectTime > 0) {
3040 out.attribute(null, "r", Long.toString(rejectTime));
3041 }
3042 if (accessDuration > 0) {
3043 out.attribute(null, "d", Long.toString(accessDuration));
3044 }
3045 if (proxyPkg != null) {
3046 out.attribute(null, "pp", proxyPkg);
3047 }
3048 if (proxyUid >= 0) {
3049 out.attribute(null, "pu", Integer.toString(proxyUid));
3050 }
3051 out.endTag(null, "st");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003052 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003053
Dianne Hackborn35654b62013-01-14 17:38:02 -08003054 out.endTag(null, "op");
3055 }
3056 out.endTag(null, "uid");
3057 }
3058 if (lastPkg != null) {
3059 out.endTag(null, "pkg");
3060 }
3061 }
3062
3063 out.endTag(null, "app-ops");
3064 out.endDocument();
3065 mFile.finishWrite(stream);
3066 } catch (IOException e) {
3067 Slog.w(TAG, "Failed to write state, restoring backup.", e);
3068 mFile.failWrite(stream);
3069 }
3070 }
3071 }
3072
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003073 static class Shell extends ShellCommand {
3074 final IAppOpsService mInterface;
3075 final AppOpsService mInternal;
3076
3077 int userId = UserHandle.USER_SYSTEM;
3078 String packageName;
3079 String opStr;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003080 String modeStr;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003081 int op;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003082 int mode;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003083 int packageUid;
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003084 int nonpackageUid;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003085 final static Binder sBinder = new Binder();
3086 IBinder mToken;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003087
3088 Shell(IAppOpsService iface, AppOpsService internal) {
3089 mInterface = iface;
3090 mInternal = internal;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003091 try {
3092 mToken = mInterface.getToken(sBinder);
3093 } catch (RemoteException e) {
3094 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003095 }
3096
3097 @Override
3098 public int onCommand(String cmd) {
3099 return onShellCommand(this, cmd);
3100 }
3101
3102 @Override
3103 public void onHelp() {
3104 PrintWriter pw = getOutPrintWriter();
3105 dumpCommandHelp(pw);
3106 }
3107
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003108 static private int strOpToOp(String op, PrintWriter err) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003109 try {
3110 return AppOpsManager.strOpToOp(op);
3111 } catch (IllegalArgumentException e) {
3112 }
3113 try {
3114 return Integer.parseInt(op);
3115 } catch (NumberFormatException e) {
3116 }
3117 try {
3118 return AppOpsManager.strDebugOpToOp(op);
3119 } catch (IllegalArgumentException e) {
3120 err.println("Error: " + e.getMessage());
3121 return -1;
3122 }
3123 }
3124
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003125 static int strModeToMode(String modeStr, PrintWriter err) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003126 for (int i = AppOpsManager.MODE_NAMES.length - 1; i >= 0; i--) {
3127 if (AppOpsManager.MODE_NAMES[i].equals(modeStr)) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003128 return i;
3129 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003130 }
3131 try {
3132 return Integer.parseInt(modeStr);
3133 } catch (NumberFormatException e) {
3134 }
3135 err.println("Error: Mode " + modeStr + " is not valid");
3136 return -1;
3137 }
3138
3139 int parseUserOpMode(int defMode, PrintWriter err) throws RemoteException {
3140 userId = UserHandle.USER_CURRENT;
3141 opStr = null;
3142 modeStr = null;
3143 for (String argument; (argument = getNextArg()) != null;) {
3144 if ("--user".equals(argument)) {
3145 userId = UserHandle.parseUserArg(getNextArgRequired());
3146 } else {
3147 if (opStr == null) {
3148 opStr = argument;
3149 } else if (modeStr == null) {
3150 modeStr = argument;
3151 break;
3152 }
3153 }
3154 }
3155 if (opStr == null) {
3156 err.println("Error: Operation not specified.");
3157 return -1;
3158 }
3159 op = strOpToOp(opStr, err);
3160 if (op < 0) {
3161 return -1;
3162 }
3163 if (modeStr != null) {
3164 if ((mode=strModeToMode(modeStr, err)) < 0) {
3165 return -1;
3166 }
3167 } else {
3168 mode = defMode;
3169 }
3170 return 0;
3171 }
3172
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003173 int parseUserPackageOp(boolean reqOp, PrintWriter err) throws RemoteException {
3174 userId = UserHandle.USER_CURRENT;
3175 packageName = null;
3176 opStr = null;
3177 for (String argument; (argument = getNextArg()) != null;) {
3178 if ("--user".equals(argument)) {
3179 userId = UserHandle.parseUserArg(getNextArgRequired());
3180 } else {
3181 if (packageName == null) {
3182 packageName = argument;
3183 } else if (opStr == null) {
3184 opStr = argument;
3185 break;
3186 }
3187 }
3188 }
3189 if (packageName == null) {
3190 err.println("Error: Package name not specified.");
3191 return -1;
3192 } else if (opStr == null && reqOp) {
3193 err.println("Error: Operation not specified.");
3194 return -1;
3195 }
3196 if (opStr != null) {
3197 op = strOpToOp(opStr, err);
3198 if (op < 0) {
3199 return -1;
3200 }
3201 } else {
3202 op = AppOpsManager.OP_NONE;
3203 }
3204 if (userId == UserHandle.USER_CURRENT) {
3205 userId = ActivityManager.getCurrentUser();
3206 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003207 nonpackageUid = -1;
3208 try {
3209 nonpackageUid = Integer.parseInt(packageName);
3210 } catch (NumberFormatException e) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003211 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003212 if (nonpackageUid == -1 && packageName.length() > 1 && packageName.charAt(0) == 'u'
3213 && packageName.indexOf('.') < 0) {
3214 int i = 1;
3215 while (i < packageName.length() && packageName.charAt(i) >= '0'
3216 && packageName.charAt(i) <= '9') {
3217 i++;
3218 }
3219 if (i > 1 && i < packageName.length()) {
3220 String userStr = packageName.substring(1, i);
3221 try {
3222 int user = Integer.parseInt(userStr);
3223 char type = packageName.charAt(i);
3224 i++;
3225 int startTypeVal = i;
3226 while (i < packageName.length() && packageName.charAt(i) >= '0'
3227 && packageName.charAt(i) <= '9') {
3228 i++;
3229 }
3230 if (i > startTypeVal) {
3231 String typeValStr = packageName.substring(startTypeVal, i);
3232 try {
3233 int typeVal = Integer.parseInt(typeValStr);
3234 if (type == 'a') {
3235 nonpackageUid = UserHandle.getUid(user,
3236 typeVal + Process.FIRST_APPLICATION_UID);
3237 } else if (type == 's') {
3238 nonpackageUid = UserHandle.getUid(user, typeVal);
3239 }
3240 } catch (NumberFormatException e) {
3241 }
3242 }
3243 } catch (NumberFormatException e) {
3244 }
3245 }
3246 }
3247 if (nonpackageUid != -1) {
3248 packageName = null;
3249 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08003250 packageUid = resolveUid(packageName);
3251 if (packageUid < 0) {
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003252 packageUid = AppGlobals.getPackageManager().getPackageUid(packageName,
3253 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
3254 }
3255 if (packageUid < 0) {
3256 err.println("Error: No UID for " + packageName + " in user " + userId);
3257 return -1;
3258 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003259 }
3260 return 0;
3261 }
3262 }
3263
3264 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003265 FileDescriptor err, String[] args, ShellCallback callback,
3266 ResultReceiver resultReceiver) {
3267 (new Shell(this, this)).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003268 }
3269
3270 static void dumpCommandHelp(PrintWriter pw) {
3271 pw.println("AppOps service (appops) commands:");
3272 pw.println(" help");
3273 pw.println(" Print this help text.");
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003274 pw.println(" start [--user <USER_ID>] <PACKAGE | UID> <OP> ");
3275 pw.println(" Starts a given operation for a particular application.");
3276 pw.println(" stop [--user <USER_ID>] <PACKAGE | UID> <OP> ");
3277 pw.println(" Stops a given operation for a particular application.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003278 pw.println(" set [--user <USER_ID>] <PACKAGE | UID> <OP> <MODE>");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003279 pw.println(" Set the mode for a particular application and operation.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003280 pw.println(" get [--user <USER_ID>] <PACKAGE | UID> [<OP>]");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003281 pw.println(" Return the mode for a particular application and optional operation.");
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003282 pw.println(" query-op [--user <USER_ID>] <OP> [<MODE>]");
3283 pw.println(" Print all packages that currently have the given op in the given mode.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003284 pw.println(" reset [--user <USER_ID>] [<PACKAGE>]");
3285 pw.println(" Reset the given application or all applications to default modes.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003286 pw.println(" write-settings");
3287 pw.println(" Immediately write pending changes to storage.");
3288 pw.println(" read-settings");
3289 pw.println(" Read the last written settings, replacing current state in RAM.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003290 pw.println(" options:");
3291 pw.println(" <PACKAGE> an Android package name.");
3292 pw.println(" <OP> an AppOps operation.");
3293 pw.println(" <MODE> one of allow, ignore, deny, or default");
3294 pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
3295 pw.println(" specified, the current user is assumed.");
3296 }
3297
3298 static int onShellCommand(Shell shell, String cmd) {
3299 if (cmd == null) {
3300 return shell.handleDefaultCommands(cmd);
3301 }
3302 PrintWriter pw = shell.getOutPrintWriter();
3303 PrintWriter err = shell.getErrPrintWriter();
3304 try {
3305 switch (cmd) {
3306 case "set": {
3307 int res = shell.parseUserPackageOp(true, err);
3308 if (res < 0) {
3309 return res;
3310 }
3311 String modeStr = shell.getNextArg();
3312 if (modeStr == null) {
3313 err.println("Error: Mode not specified.");
3314 return -1;
3315 }
3316
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003317 final int mode = shell.strModeToMode(modeStr, err);
3318 if (mode < 0) {
3319 return -1;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003320 }
3321
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003322 if (shell.packageName != null) {
3323 shell.mInterface.setMode(shell.op, shell.packageUid, shell.packageName,
3324 mode);
3325 } else {
3326 shell.mInterface.setUidMode(shell.op, shell.nonpackageUid, mode);
3327 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003328 return 0;
3329 }
3330 case "get": {
3331 int res = shell.parseUserPackageOp(false, err);
3332 if (res < 0) {
3333 return res;
3334 }
3335
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003336 List<AppOpsManager.PackageOps> ops = new ArrayList<>();
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003337 if (shell.packageName != null) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003338 // Uid mode overrides package mode, so make sure it's also reported
3339 List<AppOpsManager.PackageOps> r = shell.mInterface.getUidOps(
3340 shell.packageUid,
3341 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
3342 if (r != null) {
3343 ops.addAll(r);
3344 }
3345 r = shell.mInterface.getOpsForPackage(
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003346 shell.packageUid, shell.packageName,
3347 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003348 if (r != null) {
3349 ops.addAll(r);
3350 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003351 } else {
3352 ops = shell.mInterface.getUidOps(
3353 shell.nonpackageUid,
3354 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
3355 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003356 if (ops == null || ops.size() <= 0) {
3357 pw.println("No operations.");
Svet Ganov82f09bc2018-01-12 22:08:40 -08003358 if (shell.op > AppOpsManager.OP_NONE && shell.op < AppOpsManager._NUM_OP) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003359 pw.println("Default mode: " + AppOpsManager.modeToName(
Svet Ganov82f09bc2018-01-12 22:08:40 -08003360 AppOpsManager.opToDefaultMode(shell.op)));
3361 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003362 return 0;
3363 }
3364 final long now = System.currentTimeMillis();
3365 for (int i=0; i<ops.size(); i++) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003366 AppOpsManager.PackageOps packageOps = ops.get(i);
3367 if (packageOps.getPackageName() == null) {
3368 pw.print("Uid mode: ");
3369 }
3370 List<AppOpsManager.OpEntry> entries = packageOps.getOps();
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003371 for (int j=0; j<entries.size(); j++) {
3372 AppOpsManager.OpEntry ent = entries.get(j);
3373 pw.print(AppOpsManager.opToName(ent.getOp()));
3374 pw.print(": ");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003375 pw.print(AppOpsManager.modeToName(ent.getMode()));
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003376 if (ent.getTime() != 0) {
3377 pw.print("; time=");
3378 TimeUtils.formatDuration(now - ent.getTime(), pw);
3379 pw.print(" ago");
3380 }
3381 if (ent.getRejectTime() != 0) {
3382 pw.print("; rejectTime=");
3383 TimeUtils.formatDuration(now - ent.getRejectTime(), pw);
3384 pw.print(" ago");
3385 }
3386 if (ent.getDuration() == -1) {
3387 pw.print(" (running)");
3388 } else if (ent.getDuration() != 0) {
3389 pw.print("; duration=");
3390 TimeUtils.formatDuration(ent.getDuration(), pw);
3391 }
3392 pw.println();
3393 }
3394 }
3395 return 0;
3396 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003397 case "query-op": {
3398 int res = shell.parseUserOpMode(AppOpsManager.MODE_IGNORED, err);
3399 if (res < 0) {
3400 return res;
3401 }
3402 List<AppOpsManager.PackageOps> ops = shell.mInterface.getPackagesForOps(
3403 new int[] {shell.op});
3404 if (ops == null || ops.size() <= 0) {
3405 pw.println("No operations.");
3406 return 0;
3407 }
3408 for (int i=0; i<ops.size(); i++) {
3409 final AppOpsManager.PackageOps pkg = ops.get(i);
3410 boolean hasMatch = false;
3411 final List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
3412 for (int j=0; j<entries.size(); j++) {
3413 AppOpsManager.OpEntry ent = entries.get(j);
3414 if (ent.getOp() == shell.op && ent.getMode() == shell.mode) {
3415 hasMatch = true;
3416 break;
3417 }
3418 }
3419 if (hasMatch) {
3420 pw.println(pkg.getPackageName());
3421 }
3422 }
3423 return 0;
3424 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003425 case "reset": {
3426 String packageName = null;
3427 int userId = UserHandle.USER_CURRENT;
3428 for (String argument; (argument = shell.getNextArg()) != null;) {
3429 if ("--user".equals(argument)) {
3430 String userStr = shell.getNextArgRequired();
3431 userId = UserHandle.parseUserArg(userStr);
3432 } else {
3433 if (packageName == null) {
3434 packageName = argument;
3435 } else {
3436 err.println("Error: Unsupported argument: " + argument);
3437 return -1;
3438 }
3439 }
3440 }
3441
3442 if (userId == UserHandle.USER_CURRENT) {
3443 userId = ActivityManager.getCurrentUser();
3444 }
3445
3446 shell.mInterface.resetAllModes(userId, packageName);
3447 pw.print("Reset all modes for: ");
3448 if (userId == UserHandle.USER_ALL) {
3449 pw.print("all users");
3450 } else {
3451 pw.print("user "); pw.print(userId);
3452 }
3453 pw.print(", ");
3454 if (packageName == null) {
3455 pw.println("all packages");
3456 } else {
3457 pw.print("package "); pw.println(packageName);
3458 }
3459 return 0;
3460 }
3461 case "write-settings": {
Dianne Hackbornd5254412018-05-11 18:02:58 -07003462 shell.mInternal.enforceManageAppOpsModes(Binder.getCallingPid(),
3463 Binder.getCallingUid(), -1);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003464 long token = Binder.clearCallingIdentity();
3465 try {
3466 synchronized (shell.mInternal) {
3467 shell.mInternal.mHandler.removeCallbacks(shell.mInternal.mWriteRunner);
3468 }
3469 shell.mInternal.writeState();
3470 pw.println("Current settings written.");
3471 } finally {
3472 Binder.restoreCallingIdentity(token);
3473 }
3474 return 0;
3475 }
3476 case "read-settings": {
Dianne Hackbornd5254412018-05-11 18:02:58 -07003477 shell.mInternal.enforceManageAppOpsModes(Binder.getCallingPid(),
3478 Binder.getCallingUid(), -1);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003479 long token = Binder.clearCallingIdentity();
3480 try {
3481 shell.mInternal.readState();
3482 pw.println("Last settings read.");
3483 } finally {
3484 Binder.restoreCallingIdentity(token);
3485 }
3486 return 0;
3487 }
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003488 case "start": {
3489 int res = shell.parseUserPackageOp(true, err);
3490 if (res < 0) {
3491 return res;
3492 }
3493
3494 if (shell.packageName != null) {
3495 shell.mInterface.startOperation(shell.mToken,
3496 shell.op, shell.packageUid, shell.packageName, true);
3497 } else {
3498 return -1;
3499 }
3500 return 0;
3501 }
3502 case "stop": {
3503 int res = shell.parseUserPackageOp(true, err);
3504 if (res < 0) {
3505 return res;
3506 }
3507
3508 if (shell.packageName != null) {
3509 shell.mInterface.finishOperation(shell.mToken,
3510 shell.op, shell.packageUid, shell.packageName);
3511 } else {
3512 return -1;
3513 }
3514 return 0;
3515 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003516 default:
3517 return shell.handleDefaultCommands(cmd);
3518 }
3519 } catch (RemoteException e) {
3520 pw.println("Remote exception: " + e);
3521 }
3522 return -1;
3523 }
3524
3525 private void dumpHelp(PrintWriter pw) {
3526 pw.println("AppOps service (appops) dump options:");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003527 pw.println(" -h");
3528 pw.println(" Print this help text.");
3529 pw.println(" --op [OP]");
3530 pw.println(" Limit output to data associated with the given app op code.");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003531 pw.println(" --mode [MODE]");
3532 pw.println(" Limit output to data associated with the given app op mode.");
3533 pw.println(" --package [PACKAGE]");
3534 pw.println(" Limit output to data associated with the given package name.");
Dianne Hackborn125dc532019-01-09 13:31:48 -08003535 pw.println(" --watchers");
3536 pw.println(" Only output the watcher sections.");
Svet Ganovaf189e32019-02-15 18:45:29 -08003537 pw.println(" --history");
3538 pw.println(" Output the historical data.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003539 }
3540
Svet Ganovaf189e32019-02-15 18:45:29 -08003541 private void dumpStatesLocked(@NonNull PrintWriter pw, @NonNull Op op,
3542 long now, @NonNull SimpleDateFormat sdf, @NonNull Date date, @NonNull String prefix) {
3543
3544 final OpEntry entry = new OpEntry(op.op, op.running, op.mode, op.mAccessTimes,
3545 op.mRejectTimes, op.mDurations, op.mProxyUids, op.mProxyPackageNames);
3546
3547 final LongSparseArray keys = entry.collectKeys();
3548 if (keys == null || keys.size() <= 0) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003549 return;
3550 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003551
3552 final int keyCount = keys.size();
3553 for (int k = 0; k < keyCount; k++) {
3554 final long key = keys.keyAt(k);
3555
3556 final int uidState = AppOpsManager.extractUidStateFromKey(key);
3557 final int flags = AppOpsManager.extractFlagsFromKey(key);
3558
3559 final long accessTime = entry.getLastAccessTime(
3560 uidState, uidState, flags);
3561 final long rejectTime = entry.getLastRejectTime(
3562 uidState, uidState, flags);
3563 final long accessDuration = entry.getLastDuration(
3564 uidState, uidState, flags);
3565 final String proxyPkg = entry.getProxyPackageName(uidState, flags);
3566 final int proxyUid = entry.getProxyUid(uidState, flags);
3567
3568 if (accessTime > 0) {
3569 pw.print(prefix);
3570 pw.print("Access: ");
3571 pw.print(AppOpsManager.keyToString(key));
3572 pw.print(" ");
3573 date.setTime(accessTime);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003574 pw.print(sdf.format(date));
3575 pw.print(" (");
Svet Ganovaf189e32019-02-15 18:45:29 -08003576 TimeUtils.formatDuration(accessTime - now, pw);
3577 pw.print(")");
3578 if (accessDuration > 0) {
3579 pw.print(" duration=");
3580 TimeUtils.formatDuration(accessDuration, pw);
3581 }
3582 if (proxyUid >= 0) {
3583 pw.print(" proxy[");
3584 pw.print("uid=");
3585 pw.print(proxyUid);
3586 pw.print(", pkg=");
3587 pw.print(proxyPkg);
3588 pw.print("]");
3589 }
3590 pw.println();
3591 }
3592
3593 if (rejectTime > 0) {
3594 pw.print(prefix);
3595 pw.print("Reject: ");
3596 pw.print(AppOpsManager.keyToString(key));
3597 date.setTime(rejectTime);
3598 pw.print(sdf.format(date));
3599 pw.print(" (");
3600 TimeUtils.formatDuration(rejectTime - now, pw);
3601 pw.print(")");
3602 if (proxyUid >= 0) {
3603 pw.print(" proxy[");
3604 pw.print("uid=");
3605 pw.print(proxyUid);
3606 pw.print(", pkg=");
3607 pw.print(proxyPkg);
3608 pw.print("]");
3609 }
3610 pw.println();
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003611 }
3612 }
3613 }
3614
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003615 @Override
3616 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06003617 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003618
Svet Ganov8455ba22019-01-02 13:05:56 -08003619 int dumpOp = OP_NONE;
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003620 String dumpPackage = null;
Svet Ganov8455ba22019-01-02 13:05:56 -08003621 int dumpUid = Process.INVALID_UID;
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003622 int dumpMode = -1;
Dianne Hackborn125dc532019-01-09 13:31:48 -08003623 boolean dumpWatchers = false;
Svet Ganovaf189e32019-02-15 18:45:29 -08003624 boolean dumpHistory = false;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003625
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003626 if (args != null) {
3627 for (int i=0; i<args.length; i++) {
3628 String arg = args[i];
3629 if ("-h".equals(arg)) {
3630 dumpHelp(pw);
3631 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07003632 } else if ("-a".equals(arg)) {
3633 // dump all data
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003634 } else if ("--op".equals(arg)) {
3635 i++;
3636 if (i >= args.length) {
3637 pw.println("No argument for --op option");
3638 return;
3639 }
3640 dumpOp = Shell.strOpToOp(args[i], pw);
3641 if (dumpOp < 0) {
3642 return;
3643 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003644 } else if ("--package".equals(arg)) {
3645 i++;
3646 if (i >= args.length) {
3647 pw.println("No argument for --package option");
3648 return;
3649 }
3650 dumpPackage = args[i];
3651 try {
3652 dumpUid = AppGlobals.getPackageManager().getPackageUid(dumpPackage,
3653 PackageManager.MATCH_KNOWN_PACKAGES | PackageManager.MATCH_INSTANT,
3654 0);
3655 } catch (RemoteException e) {
3656 }
3657 if (dumpUid < 0) {
3658 pw.println("Unknown package: " + dumpPackage);
3659 return;
3660 }
3661 dumpUid = UserHandle.getAppId(dumpUid);
3662 } else if ("--mode".equals(arg)) {
3663 i++;
3664 if (i >= args.length) {
3665 pw.println("No argument for --mode option");
3666 return;
3667 }
3668 dumpMode = Shell.strModeToMode(args[i], pw);
3669 if (dumpMode < 0) {
3670 return;
3671 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08003672 } else if ("--watchers".equals(arg)) {
3673 dumpWatchers = true;
Svet Ganovaf189e32019-02-15 18:45:29 -08003674 } else if ("--history".equals(arg)) {
3675 dumpHistory = true;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003676 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
3677 pw.println("Unknown option: " + arg);
3678 return;
3679 } else {
3680 pw.println("Unknown command: " + arg);
3681 return;
3682 }
3683 }
3684 }
3685
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003686 synchronized (this) {
3687 pw.println("Current AppOps Service state:");
Svet Ganovaf189e32019-02-15 18:45:29 -08003688 if (!dumpHistory && !dumpWatchers) {
3689 mConstants.dump(pw);
3690 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003691 pw.println();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003692 final long now = System.currentTimeMillis();
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003693 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003694 final long nowUptime = SystemClock.uptimeMillis();
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003695 final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
3696 final Date date = new Date();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003697 boolean needSep = false;
Dianne Hackborn125dc532019-01-09 13:31:48 -08003698 if (dumpOp < 0 && dumpMode < 0 && dumpPackage == null && mProfileOwners != null
Svet Ganovaf189e32019-02-15 18:45:29 -08003699 && !dumpWatchers && !dumpHistory) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07003700 pw.println(" Profile owners:");
3701 for (int poi = 0; poi < mProfileOwners.size(); poi++) {
3702 pw.print(" User #");
3703 pw.print(mProfileOwners.keyAt(poi));
3704 pw.print(": ");
3705 UserHandle.formatUid(pw, mProfileOwners.valueAt(poi));
3706 pw.println();
3707 }
3708 pw.println();
3709 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003710 if (mOpModeWatchers.size() > 0 && !dumpHistory) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003711 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003712 for (int i=0; i<mOpModeWatchers.size(); i++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003713 if (dumpOp >= 0 && dumpOp != mOpModeWatchers.keyAt(i)) {
3714 continue;
3715 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003716 boolean printedOpHeader = false;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003717 ArraySet<ModeCallback> callbacks = mOpModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003718 for (int j=0; j<callbacks.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003719 final ModeCallback cb = callbacks.valueAt(j);
Dianne Hackborn125dc532019-01-09 13:31:48 -08003720 if (dumpPackage != null
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003721 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3722 continue;
3723 }
3724 needSep = true;
3725 if (!printedHeader) {
3726 pw.println(" Op mode watchers:");
3727 printedHeader = true;
3728 }
3729 if (!printedOpHeader) {
3730 pw.print(" Op ");
3731 pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
3732 pw.println(":");
3733 printedOpHeader = true;
3734 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003735 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003736 pw.println(cb);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003737 }
3738 }
3739 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003740 if (mPackageModeWatchers.size() > 0 && dumpOp < 0 && !dumpHistory) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003741 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003742 for (int i=0; i<mPackageModeWatchers.size(); i++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003743 if (dumpPackage != null && !dumpPackage.equals(mPackageModeWatchers.keyAt(i))) {
3744 continue;
3745 }
3746 needSep = true;
3747 if (!printedHeader) {
3748 pw.println(" Package mode watchers:");
3749 printedHeader = true;
3750 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003751 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
3752 pw.println(":");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003753 ArraySet<ModeCallback> callbacks = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003754 for (int j=0; j<callbacks.size(); j++) {
3755 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08003756 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003757 }
3758 }
3759 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003760 if (mModeWatchers.size() > 0 && dumpOp < 0 && !dumpHistory) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003761 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003762 for (int i=0; i<mModeWatchers.size(); i++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003763 final ModeCallback cb = mModeWatchers.valueAt(i);
Dianne Hackborn125dc532019-01-09 13:31:48 -08003764 if (dumpPackage != null
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003765 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3766 continue;
3767 }
3768 needSep = true;
3769 if (!printedHeader) {
3770 pw.println(" All op mode watchers:");
3771 printedHeader = true;
3772 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003773 pw.print(" ");
3774 pw.print(Integer.toHexString(System.identityHashCode(mModeWatchers.keyAt(i))));
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003775 pw.print(": "); pw.println(cb);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003776 }
3777 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003778 if (mActiveWatchers.size() > 0 && dumpMode < 0) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003779 needSep = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003780 boolean printedHeader = false;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003781 for (int i = 0; i < mActiveWatchers.size(); i++) {
3782 final SparseArray<ActiveCallback> activeWatchers = mActiveWatchers.valueAt(i);
3783 if (activeWatchers.size() <= 0) {
3784 continue;
3785 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003786 final ActiveCallback cb = activeWatchers.valueAt(0);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003787 if (dumpOp >= 0 && activeWatchers.indexOfKey(dumpOp) < 0) {
3788 continue;
3789 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08003790 if (dumpPackage != null
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003791 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3792 continue;
3793 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003794 if (!printedHeader) {
3795 pw.println(" All op active watchers:");
3796 printedHeader = true;
3797 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003798 pw.print(" ");
3799 pw.print(Integer.toHexString(System.identityHashCode(
3800 mActiveWatchers.keyAt(i))));
3801 pw.println(" ->");
3802 pw.print(" [");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003803 final int opCount = activeWatchers.size();
3804 for (i = 0; i < opCount; i++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003805 if (i > 0) {
3806 pw.print(' ');
3807 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003808 pw.print(AppOpsManager.opToName(activeWatchers.keyAt(i)));
3809 if (i < opCount - 1) {
3810 pw.print(',');
3811 }
3812 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003813 pw.println("]");
3814 pw.print(" ");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003815 pw.println(cb);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003816 }
3817 }
Svet Ganovb3d2ae22018-12-17 22:06:15 -08003818 if (mNotedWatchers.size() > 0 && dumpMode < 0) {
3819 needSep = true;
3820 boolean printedHeader = false;
3821 for (int i = 0; i < mNotedWatchers.size(); i++) {
3822 final SparseArray<NotedCallback> notedWatchers = mNotedWatchers.valueAt(i);
3823 if (notedWatchers.size() <= 0) {
3824 continue;
3825 }
3826 final NotedCallback cb = notedWatchers.valueAt(0);
3827 if (dumpOp >= 0 && notedWatchers.indexOfKey(dumpOp) < 0) {
3828 continue;
3829 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08003830 if (dumpPackage != null
Svet Ganovb3d2ae22018-12-17 22:06:15 -08003831 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3832 continue;
3833 }
3834 if (!printedHeader) {
3835 pw.println(" All op noted watchers:");
3836 printedHeader = true;
3837 }
3838 pw.print(" ");
3839 pw.print(Integer.toHexString(System.identityHashCode(
3840 mNotedWatchers.keyAt(i))));
3841 pw.println(" ->");
3842 pw.print(" [");
3843 final int opCount = notedWatchers.size();
3844 for (i = 0; i < opCount; i++) {
3845 if (i > 0) {
3846 pw.print(' ');
3847 }
3848 pw.print(AppOpsManager.opToName(notedWatchers.keyAt(i)));
3849 if (i < opCount - 1) {
3850 pw.print(',');
3851 }
3852 }
3853 pw.println("]");
3854 pw.print(" ");
3855 pw.println(cb);
3856 }
3857 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003858 if (mClients.size() > 0 && dumpMode < 0 && !dumpWatchers && !dumpHistory) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003859 needSep = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003860 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003861 for (int i=0; i<mClients.size(); i++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003862 boolean printedClient = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003863 ClientState cs = mClients.valueAt(i);
Svet Ganovf7b47252018-02-26 11:11:27 -08003864 if (cs.mStartedOps.size() > 0) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003865 boolean printedStarted = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003866 for (int j=0; j<cs.mStartedOps.size(); j++) {
3867 Op op = cs.mStartedOps.get(j);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003868 if (dumpOp >= 0 && op.op != dumpOp) {
3869 continue;
3870 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003871 if (dumpPackage != null && !dumpPackage.equals(op.packageName)) {
3872 continue;
3873 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003874 if (!printedHeader) {
3875 pw.println(" Clients:");
3876 printedHeader = true;
3877 }
3878 if (!printedClient) {
3879 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
3880 pw.print(" "); pw.println(cs);
3881 printedClient = true;
3882 }
3883 if (!printedStarted) {
3884 pw.println(" Started ops:");
3885 printedStarted = true;
3886 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003887 pw.print(" "); pw.print("uid="); pw.print(op.uidState.uid);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003888 pw.print(" pkg="); pw.print(op.packageName);
3889 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
3890 }
3891 }
3892 }
3893 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003894 if (mAudioRestrictions.size() > 0 && dumpOp < 0 && dumpPackage != null
Svet Ganovaf189e32019-02-15 18:45:29 -08003895 && dumpMode < 0 && !dumpWatchers && !dumpWatchers) {
John Spurlock1af30c72014-03-10 08:33:35 -04003896 boolean printedHeader = false;
3897 for (int o=0; o<mAudioRestrictions.size(); o++) {
3898 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
3899 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
3900 for (int i=0; i<restrictions.size(); i++) {
3901 if (!printedHeader){
3902 pw.println(" Audio Restrictions:");
3903 printedHeader = true;
3904 needSep = true;
3905 }
John Spurlock7b414672014-07-18 13:02:39 -04003906 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04003907 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04003908 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04003909 Restriction r = restrictions.valueAt(i);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003910 pw.print(": mode="); pw.println(AppOpsManager.modeToName(r.mode));
John Spurlock1af30c72014-03-10 08:33:35 -04003911 if (!r.exceptionPackages.isEmpty()) {
3912 pw.println(" Exceptions:");
3913 for (int j=0; j<r.exceptionPackages.size(); j++) {
3914 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
3915 }
3916 }
3917 }
3918 }
3919 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003920 if (needSep) {
3921 pw.println();
3922 }
Svet Ganov2af57082015-07-30 08:44:20 -07003923 for (int i=0; i<mUidStates.size(); i++) {
3924 UidState uidState = mUidStates.valueAt(i);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003925 final SparseIntArray opModes = uidState.opModes;
3926 final ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
3927
Svet Ganovaf189e32019-02-15 18:45:29 -08003928 if (dumpWatchers || dumpHistory) {
Dianne Hackborn125dc532019-01-09 13:31:48 -08003929 continue;
3930 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003931 if (dumpOp >= 0 || dumpPackage != null || dumpMode >= 0) {
3932 boolean hasOp = dumpOp < 0 || (uidState.opModes != null
3933 && uidState.opModes.indexOfKey(dumpOp) >= 0);
3934 boolean hasPackage = dumpPackage == null;
3935 boolean hasMode = dumpMode < 0;
3936 if (!hasMode && opModes != null) {
3937 for (int opi = 0; !hasMode && opi < opModes.size(); opi++) {
3938 if (opModes.valueAt(opi) == dumpMode) {
3939 hasMode = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003940 }
3941 }
3942 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003943 if (pkgOps != null) {
3944 for (int pkgi = 0;
Svet Ganov8455ba22019-01-02 13:05:56 -08003945 (!hasOp || !hasPackage || !hasMode) && pkgi < pkgOps.size();
3946 pkgi++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003947 Ops ops = pkgOps.valueAt(pkgi);
3948 if (!hasOp && ops != null && ops.indexOfKey(dumpOp) >= 0) {
3949 hasOp = true;
3950 }
3951 if (!hasMode) {
3952 for (int opi = 0; !hasMode && opi < ops.size(); opi++) {
3953 if (ops.valueAt(opi).mode == dumpMode) {
3954 hasMode = true;
3955 }
3956 }
3957 }
3958 if (!hasPackage && dumpPackage.equals(ops.packageName)) {
3959 hasPackage = true;
3960 }
3961 }
3962 }
3963 if (uidState.foregroundOps != null && !hasOp) {
3964 if (uidState.foregroundOps.indexOfKey(dumpOp) > 0) {
3965 hasOp = true;
3966 }
3967 }
3968 if (!hasOp || !hasPackage || !hasMode) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003969 continue;
3970 }
3971 }
Svet Ganov2af57082015-07-30 08:44:20 -07003972
3973 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003974 pw.print(" state=");
Svet Ganovaf189e32019-02-15 18:45:29 -08003975 pw.println(AppOpsManager.getUidStateName(uidState.state));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003976 if (uidState.state != uidState.pendingState) {
3977 pw.print(" pendingState=");
Svet Ganovaf189e32019-02-15 18:45:29 -08003978 pw.println(AppOpsManager.getUidStateName(uidState.pendingState));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003979 }
3980 if (uidState.pendingStateCommitTime != 0) {
3981 pw.print(" pendingStateCommitTime=");
Dianne Hackborn9fb93502018-06-18 12:29:44 -07003982 TimeUtils.formatDuration(uidState.pendingStateCommitTime, nowElapsed, pw);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003983 pw.println();
3984 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003985 if (uidState.startNesting != 0) {
3986 pw.print(" startNesting=");
3987 pw.println(uidState.startNesting);
3988 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003989 if (uidState.foregroundOps != null && (dumpMode < 0
3990 || dumpMode == AppOpsManager.MODE_FOREGROUND)) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003991 pw.println(" foregroundOps:");
3992 for (int j = 0; j < uidState.foregroundOps.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003993 if (dumpOp >= 0 && dumpOp != uidState.foregroundOps.keyAt(j)) {
3994 continue;
3995 }
3996 pw.print(" ");
3997 pw.print(AppOpsManager.opToName(uidState.foregroundOps.keyAt(j)));
3998 pw.print(": ");
3999 pw.println(uidState.foregroundOps.valueAt(j) ? "WATCHER" : "SILENT");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004000 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004001 pw.print(" hasForegroundWatchers=");
4002 pw.println(uidState.hasForegroundWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004003 }
Svet Ganovee438d42017-01-19 18:04:38 -08004004 needSep = true;
Svet Ganov2af57082015-07-30 08:44:20 -07004005
Svet Ganov2af57082015-07-30 08:44:20 -07004006 if (opModes != null) {
4007 final int opModeCount = opModes.size();
4008 for (int j = 0; j < opModeCount; j++) {
4009 final int code = opModes.keyAt(j);
4010 final int mode = opModes.valueAt(j);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004011 if (dumpOp >= 0 && dumpOp != code) {
4012 continue;
4013 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004014 if (dumpMode >= 0 && dumpMode != mode) {
4015 continue;
4016 }
Svet Ganov2af57082015-07-30 08:44:20 -07004017 pw.print(" "); pw.print(AppOpsManager.opToName(code));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004018 pw.print(": mode="); pw.println(AppOpsManager.modeToName(mode));
Svet Ganov2af57082015-07-30 08:44:20 -07004019 }
4020 }
4021
Svet Ganov2af57082015-07-30 08:44:20 -07004022 if (pkgOps == null) {
4023 continue;
4024 }
4025
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004026 for (int pkgi = 0; pkgi < pkgOps.size(); pkgi++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004027 final Ops ops = pkgOps.valueAt(pkgi);
4028 if (dumpPackage != null && !dumpPackage.equals(ops.packageName)) {
4029 continue;
4030 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004031 boolean printedPackage = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004032 for (int j=0; j<ops.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004033 final Op op = ops.valueAt(j);
Svet Ganovaf189e32019-02-15 18:45:29 -08004034 final int opCode = op.op;
4035 if (dumpOp >= 0 && dumpOp != opCode) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004036 continue;
4037 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004038 if (dumpMode >= 0 && dumpMode != op.mode) {
4039 continue;
4040 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004041 if (!printedPackage) {
4042 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
4043 printedPackage = true;
4044 }
Svet Ganovaf189e32019-02-15 18:45:29 -08004045 pw.print(" "); pw.print(AppOpsManager.opToName(opCode));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004046 pw.print(" ("); pw.print(AppOpsManager.modeToName(op.mode));
Svet Ganovaf189e32019-02-15 18:45:29 -08004047 final int switchOp = AppOpsManager.opToSwitch(opCode);
4048 if (switchOp != opCode) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004049 pw.print(" / switch ");
4050 pw.print(AppOpsManager.opToName(switchOp));
4051 final Op switchObj = ops.get(switchOp);
Svet Ganovaf189e32019-02-15 18:45:29 -08004052 int mode = switchObj != null ? switchObj.mode
4053 : AppOpsManager.opToDefaultMode(switchOp);
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004054 pw.print("="); pw.print(AppOpsManager.modeToName(mode));
4055 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004056 pw.println("): ");
Svet Ganovaf189e32019-02-15 18:45:29 -08004057 dumpStatesLocked(pw, op, now, sdf, date, " ");
4058 if (op.running) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07004059 pw.print(" Running start at: ");
4060 TimeUtils.formatDuration(nowElapsed-op.startRealtime, pw);
4061 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004062 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07004063 if (op.startNesting != 0) {
4064 pw.print(" startNesting=");
4065 pw.println(op.startNesting);
4066 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004067 }
4068 }
4069 }
Svet Ganovee438d42017-01-19 18:04:38 -08004070 if (needSep) {
4071 pw.println();
4072 }
4073
4074 final int userRestrictionCount = mOpUserRestrictions.size();
4075 for (int i = 0; i < userRestrictionCount; i++) {
4076 IBinder token = mOpUserRestrictions.keyAt(i);
4077 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
Dianne Hackborn125dc532019-01-09 13:31:48 -08004078 boolean printedTokenHeader = false;
4079
Svet Ganovaf189e32019-02-15 18:45:29 -08004080 if (dumpMode >= 0 || dumpWatchers || dumpHistory) {
Dianne Hackborn125dc532019-01-09 13:31:48 -08004081 continue;
4082 }
Svet Ganovee438d42017-01-19 18:04:38 -08004083
4084 final int restrictionCount = restrictionState.perUserRestrictions != null
4085 ? restrictionState.perUserRestrictions.size() : 0;
Dianne Hackborn125dc532019-01-09 13:31:48 -08004086 if (restrictionCount > 0 && dumpPackage == null) {
4087 boolean printedOpsHeader = false;
Svet Ganovee438d42017-01-19 18:04:38 -08004088 for (int j = 0; j < restrictionCount; j++) {
4089 int userId = restrictionState.perUserRestrictions.keyAt(j);
4090 boolean[] restrictedOps = restrictionState.perUserRestrictions.valueAt(j);
4091 if (restrictedOps == null) {
4092 continue;
4093 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08004094 if (dumpOp >= 0 && (dumpOp >= restrictedOps.length
4095 || !restrictedOps[dumpOp])) {
4096 continue;
4097 }
4098 if (!printedTokenHeader) {
4099 pw.println(" User restrictions for token " + token + ":");
4100 printedTokenHeader = true;
4101 }
4102 if (!printedOpsHeader) {
4103 pw.println(" Restricted ops:");
4104 printedOpsHeader = true;
4105 }
Svet Ganovee438d42017-01-19 18:04:38 -08004106 StringBuilder restrictedOpsValue = new StringBuilder();
4107 restrictedOpsValue.append("[");
4108 final int restrictedOpCount = restrictedOps.length;
4109 for (int k = 0; k < restrictedOpCount; k++) {
4110 if (restrictedOps[k]) {
4111 if (restrictedOpsValue.length() > 1) {
4112 restrictedOpsValue.append(", ");
4113 }
4114 restrictedOpsValue.append(AppOpsManager.opToName(k));
4115 }
4116 }
4117 restrictedOpsValue.append("]");
4118 pw.print(" "); pw.print("user: "); pw.print(userId);
4119 pw.print(" restricted ops: "); pw.println(restrictedOpsValue);
4120 }
4121 }
4122
4123 final int excludedPackageCount = restrictionState.perUserExcludedPackages != null
4124 ? restrictionState.perUserExcludedPackages.size() : 0;
Dianne Hackborn125dc532019-01-09 13:31:48 -08004125 if (excludedPackageCount > 0 && dumpOp < 0) {
4126 boolean printedPackagesHeader = false;
Svet Ganovee438d42017-01-19 18:04:38 -08004127 for (int j = 0; j < excludedPackageCount; j++) {
4128 int userId = restrictionState.perUserExcludedPackages.keyAt(j);
4129 String[] packageNames = restrictionState.perUserExcludedPackages.valueAt(j);
Dianne Hackborn125dc532019-01-09 13:31:48 -08004130 if (packageNames == null) {
4131 continue;
4132 }
4133 boolean hasPackage;
4134 if (dumpPackage != null) {
4135 hasPackage = false;
4136 for (String pkg : packageNames) {
4137 if (dumpPackage.equals(pkg)) {
4138 hasPackage = true;
4139 break;
4140 }
4141 }
4142 } else {
4143 hasPackage = true;
4144 }
4145 if (!hasPackage) {
4146 continue;
4147 }
4148 if (!printedTokenHeader) {
4149 pw.println(" User restrictions for token " + token + ":");
4150 printedTokenHeader = true;
4151 }
4152 if (!printedPackagesHeader) {
4153 pw.println(" Excluded packages:");
4154 printedPackagesHeader = true;
4155 }
Svet Ganovee438d42017-01-19 18:04:38 -08004156 pw.print(" "); pw.print("user: "); pw.print(userId);
4157 pw.print(" packages: "); pw.println(Arrays.toString(packageNames));
4158 }
4159 }
4160 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004161 }
Svet Ganov8455ba22019-01-02 13:05:56 -08004162
4163 // Must not hold the appops lock
Svet Ganovaf189e32019-02-15 18:45:29 -08004164 if (dumpHistory && !dumpWatchers) {
4165 mHistoricalRegistry.dump(" ", pw, dumpUid, dumpPackage, dumpOp);
4166 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004167 }
John Spurlock1af30c72014-03-10 08:33:35 -04004168
4169 private static final class Restriction {
4170 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
4171 int mode;
4172 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
4173 }
Jason Monk62062992014-05-06 09:55:28 -04004174
4175 @Override
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004176 public void setUserRestrictions(Bundle restrictions, IBinder token, int userHandle) {
Jason Monk62062992014-05-06 09:55:28 -04004177 checkSystemUid("setUserRestrictions");
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004178 Preconditions.checkNotNull(restrictions);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004179 Preconditions.checkNotNull(token);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004180 for (int i = 0; i < AppOpsManager._NUM_OP; i++) {
Jason Monk62062992014-05-06 09:55:28 -04004181 String restriction = AppOpsManager.opToRestriction(i);
Suprabh Shukla64e0dcb2016-05-24 16:23:11 -07004182 if (restriction != null) {
4183 setUserRestrictionNoCheck(i, restrictions.getBoolean(restriction, false), token,
4184 userHandle, null);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004185 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004186 }
4187 }
4188
4189 @Override
Ruben Brunk29931bc2016-03-11 00:24:26 -08004190 public void setUserRestriction(int code, boolean restricted, IBinder token, int userHandle,
4191 String[] exceptionPackages) {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004192 if (Binder.getCallingPid() != Process.myPid()) {
4193 mContext.enforcePermission(Manifest.permission.MANAGE_APP_OPS_RESTRICTIONS,
4194 Binder.getCallingPid(), Binder.getCallingUid(), null);
4195 }
4196 if (userHandle != UserHandle.getCallingUserId()) {
4197 if (mContext.checkCallingOrSelfPermission(Manifest.permission
4198 .INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
4199 && mContext.checkCallingOrSelfPermission(Manifest.permission
4200 .INTERACT_ACROSS_USERS) != PackageManager.PERMISSION_GRANTED) {
4201 throw new SecurityException("Need INTERACT_ACROSS_USERS_FULL or"
4202 + " INTERACT_ACROSS_USERS to interact cross user ");
Jason Monk62062992014-05-06 09:55:28 -04004203 }
4204 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004205 verifyIncomingOp(code);
4206 Preconditions.checkNotNull(token);
Ruben Brunk29931bc2016-03-11 00:24:26 -08004207 setUserRestrictionNoCheck(code, restricted, token, userHandle, exceptionPackages);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004208 }
4209
4210 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
Ruben Brunk29931bc2016-03-11 00:24:26 -08004211 int userHandle, String[] exceptionPackages) {
Svet Ganov442ed572016-08-17 17:29:43 -07004212 synchronized (AppOpsService.this) {
4213 ClientRestrictionState restrictionState = mOpUserRestrictions.get(token);
4214
4215 if (restrictionState == null) {
4216 try {
4217 restrictionState = new ClientRestrictionState(token);
4218 } catch (RemoteException e) {
4219 return;
4220 }
4221 mOpUserRestrictions.put(token, restrictionState);
Ruben Brunk29931bc2016-03-11 00:24:26 -08004222 }
Svet Ganov442ed572016-08-17 17:29:43 -07004223
4224 if (restrictionState.setRestriction(code, restricted, exceptionPackages, userHandle)) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004225 mHandler.sendMessage(PooledLambda.obtainMessage(
Svet Ganov3a95f832018-03-23 17:44:30 -07004226 AppOpsService::notifyWatchersOfChange, this, code, UID_ANY));
Svet Ganov442ed572016-08-17 17:29:43 -07004227 }
4228
4229 if (restrictionState.isDefault()) {
4230 mOpUserRestrictions.remove(token);
4231 restrictionState.destroy();
4232 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08004233 }
Julia Reynoldsbb21c252016-04-05 16:01:49 -04004234 }
4235
Svet Ganov3a95f832018-03-23 17:44:30 -07004236 private void notifyWatchersOfChange(int code, int uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004237 final ArraySet<ModeCallback> clonedCallbacks;
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004238 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004239 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004240 if (callbacks == null) {
4241 return;
4242 }
Dianne Hackborn68d76552017-02-27 15:32:03 -08004243 clonedCallbacks = new ArraySet<>(callbacks);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004244 }
4245
Svet Ganov3a95f832018-03-23 17:44:30 -07004246 notifyOpChanged(clonedCallbacks, code, uid, null);
Jason Monk62062992014-05-06 09:55:28 -04004247 }
4248
4249 @Override
4250 public void removeUser(int userHandle) throws RemoteException {
4251 checkSystemUid("removeUser");
Svet Ganov442ed572016-08-17 17:29:43 -07004252 synchronized (AppOpsService.this) {
4253 final int tokenCount = mOpUserRestrictions.size();
4254 for (int i = tokenCount - 1; i >= 0; i--) {
4255 ClientRestrictionState opRestrictions = mOpUserRestrictions.valueAt(i);
4256 opRestrictions.removeUser(userHandle);
4257 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07004258 removeUidsForUserLocked(userHandle);
4259 }
4260 }
4261
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004262 @Override
4263 public boolean isOperationActive(int code, int uid, String packageName) {
Svet Ganovf7b47252018-02-26 11:11:27 -08004264 if (Binder.getCallingUid() != uid) {
4265 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
4266 != PackageManager.PERMISSION_GRANTED) {
4267 return false;
4268 }
4269 }
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004270 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004271 final String resolvedPackageName = resolvePackageName(uid, packageName);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004272 if (resolvedPackageName == null) {
4273 return false;
4274 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004275 synchronized (AppOpsService.this) {
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004276 for (int i = mClients.size() - 1; i >= 0; i--) {
4277 final ClientState client = mClients.valueAt(i);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004278 for (int j = client.mStartedOps.size() - 1; j >= 0; j--) {
4279 final Op op = client.mStartedOps.get(j);
Svet Ganovaf189e32019-02-15 18:45:29 -08004280 if (op.op == code && op.uidState.uid == uid) return true;
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004281 }
4282 }
4283 }
4284 return false;
4285 }
4286
Svet Ganov8455ba22019-01-02 13:05:56 -08004287 @Override
4288 public void setHistoryParameters(@AppOpsManager.HistoricalMode int mode,
4289 long baseSnapshotInterval, int compressionStep) {
4290 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4291 "setHistoryParameters");
4292 // Must not hold the appops lock
4293 mHistoricalRegistry.setHistoryParameters(mode, baseSnapshotInterval, compressionStep);
4294 }
4295
4296 @Override
4297 public void offsetHistory(long offsetMillis) {
4298 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4299 "offsetHistory");
4300 // Must not hold the appops lock
4301 mHistoricalRegistry.offsetHistory(offsetMillis);
4302 }
4303
4304 @Override
4305 public void addHistoricalOps(HistoricalOps ops) {
4306 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4307 "addHistoricalOps");
4308 // Must not hold the appops lock
4309 mHistoricalRegistry.addHistoricalOps(ops);
4310 }
4311
4312 @Override
4313 public void resetHistoryParameters() {
4314 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4315 "resetHistoryParameters");
4316 // Must not hold the appops lock
4317 mHistoricalRegistry.resetHistoryParameters();
4318 }
4319
4320 @Override
4321 public void clearHistory() {
4322 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4323 "clearHistory");
4324 // Must not hold the appops lock
4325 mHistoricalRegistry.clearHistory();
4326 }
4327
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07004328 private void removeUidsForUserLocked(int userHandle) {
4329 for (int i = mUidStates.size() - 1; i >= 0; --i) {
4330 final int uid = mUidStates.keyAt(i);
4331 if (UserHandle.getUserId(uid) == userHandle) {
4332 mUidStates.removeAt(i);
4333 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004334 }
4335 }
4336
Jason Monk62062992014-05-06 09:55:28 -04004337 private void checkSystemUid(String function) {
4338 int uid = Binder.getCallingUid();
4339 if (uid != Process.SYSTEM_UID) {
4340 throw new SecurityException(function + " must by called by the system");
4341 }
4342 }
4343
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004344 private static String resolvePackageName(int uid, String packageName) {
Svet Ganov82f09bc2018-01-12 22:08:40 -08004345 if (uid == Process.ROOT_UID) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004346 return "root";
4347 } else if (uid == Process.SHELL_UID) {
4348 return "com.android.shell";
Svet Ganov82f09bc2018-01-12 22:08:40 -08004349 } else if (uid == Process.MEDIA_UID) {
4350 return "media";
4351 } else if (uid == Process.AUDIOSERVER_UID) {
4352 return "audioserver";
4353 } else if (uid == Process.CAMERASERVER_UID) {
4354 return "cameraserver";
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004355 } else if (uid == Process.SYSTEM_UID && packageName == null) {
4356 return "android";
4357 }
4358 return packageName;
4359 }
4360
Svet Ganov82f09bc2018-01-12 22:08:40 -08004361 private static int resolveUid(String packageName) {
4362 if (packageName == null) {
4363 return -1;
4364 }
4365 switch (packageName) {
4366 case "root":
4367 return Process.ROOT_UID;
4368 case "shell":
4369 return Process.SHELL_UID;
4370 case "media":
4371 return Process.MEDIA_UID;
4372 case "audioserver":
4373 return Process.AUDIOSERVER_UID;
4374 case "cameraserver":
4375 return Process.CAMERASERVER_UID;
4376 }
4377 return -1;
4378 }
4379
Svet Ganov2af57082015-07-30 08:44:20 -07004380 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07004381 String[] packageNames = null;
Philip P. Moltmann159d98b2018-12-20 08:30:53 -08004382
4383 // Very early during boot the package manager is not yet or not yet fully started. At this
4384 // time there are no packages yet.
4385 if (AppGlobals.getPackageManager() != null) {
4386 try {
4387 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
4388 } catch (RemoteException e) {
4389 /* ignore - local call */
4390 }
Svet Ganov2af57082015-07-30 08:44:20 -07004391 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07004392 if (packageNames == null) {
4393 return EmptyArray.STRING;
4394 }
4395 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07004396 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004397
4398 private final class ClientRestrictionState implements DeathRecipient {
4399 private final IBinder token;
4400 SparseArray<boolean[]> perUserRestrictions;
4401 SparseArray<String[]> perUserExcludedPackages;
4402
4403 public ClientRestrictionState(IBinder token)
4404 throws RemoteException {
4405 token.linkToDeath(this, 0);
4406 this.token = token;
4407 }
4408
4409 public boolean setRestriction(int code, boolean restricted,
4410 String[] excludedPackages, int userId) {
4411 boolean changed = false;
4412
4413 if (perUserRestrictions == null && restricted) {
4414 perUserRestrictions = new SparseArray<>();
4415 }
4416
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004417 int[] users;
4418 if (userId == UserHandle.USER_ALL) {
4419 List<UserInfo> liveUsers = UserManager.get(mContext).getUsers(false);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004420
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004421 users = new int[liveUsers.size()];
4422 for (int i = 0; i < liveUsers.size(); i++) {
4423 users[i] = liveUsers.get(i).id;
4424 }
4425 } else {
4426 users = new int[]{userId};
4427 }
4428
4429 if (perUserRestrictions != null) {
4430 int numUsers = users.length;
4431
4432 for (int i = 0; i < numUsers; i++) {
4433 int thisUserId = users[i];
4434
4435 boolean[] userRestrictions = perUserRestrictions.get(thisUserId);
4436 if (userRestrictions == null && restricted) {
4437 userRestrictions = new boolean[AppOpsManager._NUM_OP];
4438 perUserRestrictions.put(thisUserId, userRestrictions);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004439 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004440 if (userRestrictions != null && userRestrictions[code] != restricted) {
4441 userRestrictions[code] = restricted;
4442 if (!restricted && isDefault(userRestrictions)) {
4443 perUserRestrictions.remove(thisUserId);
4444 userRestrictions = null;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004445 }
4446 changed = true;
4447 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004448
4449 if (userRestrictions != null) {
4450 final boolean noExcludedPackages = ArrayUtils.isEmpty(excludedPackages);
4451 if (perUserExcludedPackages == null && !noExcludedPackages) {
4452 perUserExcludedPackages = new SparseArray<>();
4453 }
4454 if (perUserExcludedPackages != null && !Arrays.equals(excludedPackages,
4455 perUserExcludedPackages.get(thisUserId))) {
4456 if (noExcludedPackages) {
4457 perUserExcludedPackages.remove(thisUserId);
4458 if (perUserExcludedPackages.size() <= 0) {
4459 perUserExcludedPackages = null;
4460 }
4461 } else {
4462 perUserExcludedPackages.put(thisUserId, excludedPackages);
4463 }
4464 changed = true;
4465 }
4466 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004467 }
4468 }
4469
4470 return changed;
4471 }
4472
4473 public boolean hasRestriction(int restriction, String packageName, int userId) {
4474 if (perUserRestrictions == null) {
4475 return false;
4476 }
4477 boolean[] restrictions = perUserRestrictions.get(userId);
4478 if (restrictions == null) {
4479 return false;
4480 }
4481 if (!restrictions[restriction]) {
4482 return false;
4483 }
4484 if (perUserExcludedPackages == null) {
4485 return true;
4486 }
4487 String[] perUserExclusions = perUserExcludedPackages.get(userId);
4488 if (perUserExclusions == null) {
4489 return true;
4490 }
4491 return !ArrayUtils.contains(perUserExclusions, packageName);
4492 }
4493
4494 public void removeUser(int userId) {
4495 if (perUserExcludedPackages != null) {
4496 perUserExcludedPackages.remove(userId);
4497 if (perUserExcludedPackages.size() <= 0) {
4498 perUserExcludedPackages = null;
4499 }
4500 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07004501 if (perUserRestrictions != null) {
4502 perUserRestrictions.remove(userId);
4503 if (perUserRestrictions.size() <= 0) {
4504 perUserRestrictions = null;
4505 }
4506 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004507 }
4508
4509 public boolean isDefault() {
4510 return perUserRestrictions == null || perUserRestrictions.size() <= 0;
4511 }
4512
4513 @Override
4514 public void binderDied() {
4515 synchronized (AppOpsService.this) {
4516 mOpUserRestrictions.remove(token);
4517 if (perUserRestrictions == null) {
4518 return;
4519 }
4520 final int userCount = perUserRestrictions.size();
4521 for (int i = 0; i < userCount; i++) {
4522 final boolean[] restrictions = perUserRestrictions.valueAt(i);
4523 final int restrictionCount = restrictions.length;
4524 for (int j = 0; j < restrictionCount; j++) {
4525 if (restrictions[j]) {
4526 final int changedCode = j;
Svet Ganov3a95f832018-03-23 17:44:30 -07004527 mHandler.post(() -> notifyWatchersOfChange(changedCode, UID_ANY));
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004528 }
4529 }
4530 }
4531 destroy();
4532 }
4533 }
4534
4535 public void destroy() {
4536 token.unlinkToDeath(this, 0);
4537 }
4538
4539 private boolean isDefault(boolean[] array) {
4540 if (ArrayUtils.isEmpty(array)) {
4541 return true;
4542 }
4543 for (boolean value : array) {
4544 if (value) {
4545 return false;
4546 }
4547 }
4548 return true;
4549 }
4550 }
Dianne Hackbornd5254412018-05-11 18:02:58 -07004551
4552 private final class AppOpsManagerInternalImpl extends AppOpsManagerInternal {
4553 @Override public void setDeviceAndProfileOwners(SparseIntArray owners) {
4554 synchronized (AppOpsService.this) {
4555 mProfileOwners = owners;
4556 }
4557 }
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07004558
4559 @Override
Philip P. Moltmann159d98b2018-12-20 08:30:53 -08004560 public void setUidMode(int code, int uid, int mode) {
4561 AppOpsService.this.setUidMode(code, uid, mode);
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07004562 }
Philip P. Moltmanndde07852019-01-25 16:42:36 -08004563
4564 @Override
4565 public void setAllPkgModesToDefault(int code, int uid) {
4566 AppOpsService.this.setAllPkgModesToDefault(code, uid);
4567 }
Philip P. Moltmann724150d2019-03-11 17:01:05 -07004568
4569 @Override
4570 public @Mode int checkOperationUnchecked(int code, int uid, @NonNull String packageName) {
4571 return AppOpsService.this.checkOperationUnchecked(code, uid, packageName, true, false);
4572 }
Dianne Hackbornd5254412018-05-11 18:02:58 -07004573 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004574}