blob: ba7288e6d15ffac5559d9c1dae2b02d7b3dcf62a [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
1135 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
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
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001147 public List<AppOpsManager.PackageOps> getUidOps(int uid, int[] ops) {
1148 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
1149 Binder.getCallingPid(), Binder.getCallingUid(), null);
1150 synchronized (this) {
1151 UidState uidState = getUidStateLocked(uid, false);
1152 if (uidState == null) {
1153 return null;
1154 }
1155 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(uidState.opModes, ops);
1156 if (resOps == null) {
1157 return null;
1158 }
1159 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
1160 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
1161 null, uidState.uid, resOps);
1162 res.add(resPackage);
1163 return res;
1164 }
1165 }
1166
Dianne Hackborn607b4142013-08-02 18:10:10 -07001167 private void pruneOp(Op op, int uid, String packageName) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001168 if (!op.hasAnyTime()) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001169 Ops ops = getOpsRawLocked(uid, packageName, false /* edit */,
1170 false /* uidMismatchExpected */);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001171 if (ops != null) {
1172 ops.remove(op.op);
1173 if (ops.size() <= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -07001174 UidState uidState = ops.uidState;
1175 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
Dianne Hackborn607b4142013-08-02 18:10:10 -07001176 if (pkgOps != null) {
1177 pkgOps.remove(ops.packageName);
Svet Ganov2af57082015-07-30 08:44:20 -07001178 if (pkgOps.isEmpty()) {
1179 uidState.pkgOps = null;
1180 }
1181 if (uidState.isDefault()) {
1182 mUidStates.remove(uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001183 }
1184 }
1185 }
1186 }
1187 }
1188 }
1189
Svet Ganovaf189e32019-02-15 18:45:29 -08001190 private void enforceManageAppOpsModes(int callingPid, int callingUid, int targetUid) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07001191 if (callingPid == Process.myPid()) {
1192 return;
1193 }
1194 final int callingUser = UserHandle.getUserId(callingUid);
1195 synchronized (this) {
1196 if (mProfileOwners != null && mProfileOwners.get(callingUser, -1) == callingUid) {
1197 if (targetUid >= 0 && callingUser == UserHandle.getUserId(targetUid)) {
1198 // Profile owners are allowed to change modes but only for apps
1199 // within their user.
1200 return;
1201 }
1202 }
1203 }
1204 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
1205 Binder.getCallingPid(), Binder.getCallingUid(), null);
1206 }
1207
Dianne Hackborn72e39832013-01-18 18:36:09 -08001208 @Override
Svet Ganov2af57082015-07-30 08:44:20 -07001209 public void setUidMode(int code, int uid, int mode) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08001210 if (DEBUG) {
1211 Slog.i(TAG, "uid " + uid + " OP_" + opToName(code) + " := " + modeToName(mode)
1212 + " by uid " + Binder.getCallingUid());
1213 }
1214
Dianne Hackbornd5254412018-05-11 18:02:58 -07001215 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
Svet Ganov2af57082015-07-30 08:44:20 -07001216 verifyIncomingOp(code);
1217 code = AppOpsManager.opToSwitch(code);
1218
1219 synchronized (this) {
1220 final int defaultMode = AppOpsManager.opToDefaultMode(code);
1221
1222 UidState uidState = getUidStateLocked(uid, false);
1223 if (uidState == null) {
1224 if (mode == defaultMode) {
1225 return;
1226 }
1227 uidState = new UidState(uid);
1228 uidState.opModes = new SparseIntArray();
1229 uidState.opModes.put(code, mode);
1230 mUidStates.put(uid, uidState);
1231 scheduleWriteLocked();
1232 } else if (uidState.opModes == null) {
1233 if (mode != defaultMode) {
1234 uidState.opModes = new SparseIntArray();
1235 uidState.opModes.put(code, mode);
1236 scheduleWriteLocked();
1237 }
1238 } else {
Hai Zhang2b98fb32018-09-21 15:18:46 -07001239 if (uidState.opModes.indexOfKey(code) >= 0 && uidState.opModes.get(code) == mode) {
Svet Ganov2af57082015-07-30 08:44:20 -07001240 return;
1241 }
1242 if (mode == defaultMode) {
1243 uidState.opModes.delete(code);
1244 if (uidState.opModes.size() <= 0) {
1245 uidState.opModes = null;
1246 }
1247 } else {
1248 uidState.opModes.put(code, mode);
1249 }
1250 scheduleWriteLocked();
1251 }
1252 }
1253
Svetoslav215b44a2015-08-04 19:03:40 -07001254 String[] uidPackageNames = getPackagesForUid(uid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001255 ArrayMap<ModeCallback, ArraySet<String>> callbackSpecs = null;
Svet Ganov2af57082015-07-30 08:44:20 -07001256
riddle_hsu40b300f2015-11-23 13:22:03 +08001257 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001258 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001259 if (callbacks != null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001260 final int callbackCount = callbacks.size();
1261 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001262 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +08001263 ArraySet<String> changedPackages = new ArraySet<>();
1264 Collections.addAll(changedPackages, uidPackageNames);
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001265 if (callbackSpecs == null) {
1266 callbackSpecs = new ArrayMap<>();
1267 }
riddle_hsu40b300f2015-11-23 13:22:03 +08001268 callbackSpecs.put(callback, changedPackages);
1269 }
1270 }
1271
1272 for (String uidPackageName : uidPackageNames) {
1273 callbacks = mPackageModeWatchers.get(uidPackageName);
1274 if (callbacks != null) {
1275 if (callbackSpecs == null) {
1276 callbackSpecs = new ArrayMap<>();
Svet Ganov2af57082015-07-30 08:44:20 -07001277 }
riddle_hsu40b300f2015-11-23 13:22:03 +08001278 final int callbackCount = callbacks.size();
1279 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001280 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +08001281 ArraySet<String> changedPackages = callbackSpecs.get(callback);
1282 if (changedPackages == null) {
1283 changedPackages = new ArraySet<>();
1284 callbackSpecs.put(callback, changedPackages);
1285 }
1286 changedPackages.add(uidPackageName);
1287 }
Svet Ganov2af57082015-07-30 08:44:20 -07001288 }
1289 }
1290 }
1291
1292 if (callbackSpecs == null) {
1293 return;
1294 }
1295
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001296 for (int i = 0; i < callbackSpecs.size(); i++) {
1297 final ModeCallback callback = callbackSpecs.keyAt(i);
1298 final ArraySet<String> reportedPackageNames = callbackSpecs.valueAt(i);
1299 if (reportedPackageNames == null) {
1300 mHandler.sendMessage(PooledLambda.obtainMessage(
1301 AppOpsService::notifyOpChanged,
1302 this, callback, code, uid, (String) null));
1303
1304 } else {
1305 final int reportedPackageCount = reportedPackageNames.size();
1306 for (int j = 0; j < reportedPackageCount; j++) {
1307 final String reportedPackageName = reportedPackageNames.valueAt(j);
1308 mHandler.sendMessage(PooledLambda.obtainMessage(
1309 AppOpsService::notifyOpChanged,
1310 this, callback, code, uid, reportedPackageName));
Svet Ganov2af57082015-07-30 08:44:20 -07001311 }
1312 }
Svet Ganov2af57082015-07-30 08:44:20 -07001313 }
1314 }
1315
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001316 /**
1317 * Set all {@link #setMode (package) modes} for this uid to the default value.
1318 *
1319 * @param code The app-op
1320 * @param uid The uid
1321 */
1322 private void setAllPkgModesToDefault(int code, int uid) {
1323 synchronized (this) {
1324 UidState uidState = getUidStateLocked(uid, false);
1325 if (uidState == null) {
1326 return;
1327 }
1328
1329 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
1330 if (pkgOps == null) {
1331 return;
1332 }
1333
Svet Ganovaf189e32019-02-15 18:45:29 -08001334 boolean scheduleWrite = false;
1335
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001336 int numPkgs = pkgOps.size();
1337 for (int pkgNum = 0; pkgNum < numPkgs; pkgNum++) {
1338 Ops ops = pkgOps.valueAt(pkgNum);
1339
1340 Op op = ops.get(code);
1341 if (op == null) {
1342 continue;
1343 }
1344
1345 int defaultMode = AppOpsManager.opToDefaultMode(code);
1346 if (op.mode != defaultMode) {
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001347 op.mode = defaultMode;
Svet Ganovaf189e32019-02-15 18:45:29 -08001348 scheduleWrite = true;
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001349 }
1350 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001351
1352 if (scheduleWrite) {
1353 scheduleWriteLocked();
1354 }
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001355 }
1356 }
1357
Svet Ganov2af57082015-07-30 08:44:20 -07001358 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001359 public void setMode(int code, int uid, String packageName, int mode) {
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07001360 setMode(code, uid, packageName, mode, true, false);
1361 }
1362
1363 /**
1364 * Sets the mode for a certain op and uid.
1365 *
1366 * @param code The op code to set
1367 * @param uid The UID for which to set
1368 * @param packageName The package for which to set
1369 * @param mode The new mode to set
1370 * @param verifyUid Iff {@code true}, check that the package name belongs to the uid
1371 * @param isPrivileged Whether the package is privileged. (Only used if {@code verifyUid ==
1372 * false})
1373 */
1374 private void setMode(int code, int uid, @NonNull String packageName, int mode,
1375 boolean verifyUid, boolean isPrivileged) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07001376 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001377 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001378 ArraySet<ModeCallback> repCbs = null;
Dianne Hackbornc2293022013-02-06 23:14:49 -08001379 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001380 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -07001381 UidState uidState = getUidStateLocked(uid, false);
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07001382 Op op = getOpLocked(code, uid, packageName, true, verifyUid, isPrivileged);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001383 if (op != null) {
1384 if (op.mode != mode) {
1385 op.mode = mode;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001386 if (uidState != null) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001387 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001388 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001389 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001390 if (cbs != null) {
1391 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001392 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001393 }
1394 repCbs.addAll(cbs);
1395 }
1396 cbs = mPackageModeWatchers.get(packageName);
1397 if (cbs != null) {
1398 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001399 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001400 }
1401 repCbs.addAll(cbs);
1402 }
David Braunf5d83192013-09-16 13:43:51 -07001403 if (mode == AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001404 // If going into the default mode, prune this op
1405 // if there is nothing else interesting in it.
Dianne Hackborn607b4142013-08-02 18:10:10 -07001406 pruneOp(op, uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001407 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001408 scheduleFastWriteLocked();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001409 }
1410 }
1411 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001412 if (repCbs != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001413 mHandler.sendMessage(PooledLambda.obtainMessage(
1414 AppOpsService::notifyOpChanged,
1415 this, repCbs, code, uid, packageName));
Dianne Hackbornc2293022013-02-06 23:14:49 -08001416 }
1417 }
1418
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001419 private void notifyOpChanged(ArraySet<ModeCallback> callbacks, int code,
1420 int uid, String packageName) {
1421 for (int i = 0; i < callbacks.size(); i++) {
1422 final ModeCallback callback = callbacks.valueAt(i);
1423 notifyOpChanged(callback, code, uid, packageName);
1424 }
1425 }
1426
1427 private void notifyOpChanged(ModeCallback callback, int code,
1428 int uid, String packageName) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001429 if (uid != UID_ANY && callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001430 return;
1431 }
1432 // There are components watching for mode changes such as window manager
1433 // and location manager which are in our process. The callbacks in these
1434 // components may require permissions our remote caller does not have.
1435 final long identity = Binder.clearCallingIdentity();
1436 try {
1437 callback.mCallback.opChanged(code, uid, packageName);
1438 } catch (RemoteException e) {
1439 /* ignore */
1440 } finally {
1441 Binder.restoreCallingIdentity(identity);
1442 }
1443 }
1444
1445 private static HashMap<ModeCallback, ArrayList<ChangeRec>> addCallbacks(
1446 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks,
1447 int op, int uid, String packageName, ArraySet<ModeCallback> cbs) {
Dianne Hackborn607b4142013-08-02 18:10:10 -07001448 if (cbs == null) {
1449 return callbacks;
1450 }
1451 if (callbacks == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001452 callbacks = new HashMap<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001453 }
Svet Ganov2af57082015-07-30 08:44:20 -07001454 boolean duplicate = false;
Dianne Hackborn68d76552017-02-27 15:32:03 -08001455 final int N = cbs.size();
1456 for (int i=0; i<N; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001457 ModeCallback cb = cbs.valueAt(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001458 ArrayList<ChangeRec> reports = callbacks.get(cb);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001459 if (reports == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001460 reports = new ArrayList<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001461 callbacks.put(cb, reports);
Svet Ganov2af57082015-07-30 08:44:20 -07001462 } else {
1463 final int reportCount = reports.size();
1464 for (int j = 0; j < reportCount; j++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001465 ChangeRec report = reports.get(j);
1466 if (report.op == op && report.pkg.equals(packageName)) {
Svet Ganov2af57082015-07-30 08:44:20 -07001467 duplicate = true;
1468 break;
1469 }
1470 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001471 }
Svet Ganov2af57082015-07-30 08:44:20 -07001472 if (!duplicate) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001473 reports.add(new ChangeRec(op, uid, packageName));
Svet Ganov2af57082015-07-30 08:44:20 -07001474 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001475 }
1476 return callbacks;
1477 }
1478
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001479 static final class ChangeRec {
1480 final int op;
1481 final int uid;
1482 final String pkg;
1483
1484 ChangeRec(int _op, int _uid, String _pkg) {
1485 op = _op;
1486 uid = _uid;
1487 pkg = _pkg;
1488 }
1489 }
1490
Dianne Hackborn607b4142013-08-02 18:10:10 -07001491 @Override
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001492 public void resetAllModes(int reqUserId, String reqPackageName) {
1493 final int callingPid = Binder.getCallingPid();
1494 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001495 reqUserId = ActivityManager.handleIncomingUser(callingPid, callingUid, reqUserId,
1496 true, true, "resetAllModes", null);
Svet Ganov2af57082015-07-30 08:44:20 -07001497
1498 int reqUid = -1;
1499 if (reqPackageName != null) {
1500 try {
1501 reqUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -07001502 reqPackageName, PackageManager.MATCH_UNINSTALLED_PACKAGES, reqUserId);
Svet Ganov2af57082015-07-30 08:44:20 -07001503 } catch (RemoteException e) {
1504 /* ignore - local call */
1505 }
1506 }
1507
Dianne Hackbornd5254412018-05-11 18:02:58 -07001508 enforceManageAppOpsModes(callingPid, callingUid, reqUid);
1509
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001510 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks = null;
Dianne Hackborn607b4142013-08-02 18:10:10 -07001511 synchronized (this) {
1512 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -07001513 for (int i = mUidStates.size() - 1; i >= 0; i--) {
1514 UidState uidState = mUidStates.valueAt(i);
1515
1516 SparseIntArray opModes = uidState.opModes;
1517 if (opModes != null && (uidState.uid == reqUid || reqUid == -1)) {
1518 final int uidOpCount = opModes.size();
1519 for (int j = uidOpCount - 1; j >= 0; j--) {
1520 final int code = opModes.keyAt(j);
1521 if (AppOpsManager.opAllowsReset(code)) {
1522 opModes.removeAt(j);
1523 if (opModes.size() <= 0) {
1524 uidState.opModes = null;
1525 }
1526 for (String packageName : getPackagesForUid(uidState.uid)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001527 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -07001528 mOpModeWatchers.get(code));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001529 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -07001530 mPackageModeWatchers.get(packageName));
1531 }
1532 }
1533 }
1534 }
1535
1536 if (uidState.pkgOps == null) {
1537 continue;
1538 }
1539
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001540 if (reqUserId != UserHandle.USER_ALL
Svet Ganov2af57082015-07-30 08:44:20 -07001541 && reqUserId != UserHandle.getUserId(uidState.uid)) {
Alexandra Gherghinad6a98972014-08-04 17:05:34 +01001542 // Skip any ops for a different user
1543 continue;
1544 }
Svet Ganov2af57082015-07-30 08:44:20 -07001545
1546 Map<String, Ops> packages = uidState.pkgOps;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001547 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001548 boolean uidChanged = false;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001549 while (it.hasNext()) {
1550 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001551 String packageName = ent.getKey();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001552 if (reqPackageName != null && !reqPackageName.equals(packageName)) {
1553 // Skip any ops for a different package
1554 continue;
1555 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001556 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001557 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -07001558 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -07001559 if (AppOpsManager.opAllowsReset(curOp.op)
1560 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -07001561 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001562 changed = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001563 uidChanged = true;
Svet Ganovaf189e32019-02-15 18:45:29 -08001564 final int uid = curOp.uidState.uid;
1565 callbacks = addCallbacks(callbacks, curOp.op, uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -07001566 mOpModeWatchers.get(curOp.op));
Svet Ganovaf189e32019-02-15 18:45:29 -08001567 callbacks = addCallbacks(callbacks, curOp.op, uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -07001568 mPackageModeWatchers.get(packageName));
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001569 if (!curOp.hasAnyTime()) {
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001570 pkgOps.removeAt(j);
1571 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001572 }
1573 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001574 if (pkgOps.size() == 0) {
1575 it.remove();
1576 }
1577 }
Svet Ganov2af57082015-07-30 08:44:20 -07001578 if (uidState.isDefault()) {
1579 mUidStates.remove(uidState.uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001580 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001581 if (uidChanged) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001582 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001583 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001584 }
Svet Ganov2af57082015-07-30 08:44:20 -07001585
Dianne Hackborn607b4142013-08-02 18:10:10 -07001586 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001587 scheduleFastWriteLocked();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001588 }
1589 }
1590 if (callbacks != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001591 for (Map.Entry<ModeCallback, ArrayList<ChangeRec>> ent : callbacks.entrySet()) {
1592 ModeCallback cb = ent.getKey();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001593 ArrayList<ChangeRec> reports = ent.getValue();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001594 for (int i=0; i<reports.size(); i++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001595 ChangeRec rep = reports.get(i);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001596 mHandler.sendMessage(PooledLambda.obtainMessage(
1597 AppOpsService::notifyOpChanged,
1598 this, cb, rep.op, rep.uid, rep.pkg));
Dianne Hackborn607b4142013-08-02 18:10:10 -07001599 }
1600 }
1601 }
1602 }
1603
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001604 private void evalAllForegroundOpsLocked() {
1605 for (int uidi = mUidStates.size() - 1; uidi >= 0; uidi--) {
1606 final UidState uidState = mUidStates.valueAt(uidi);
1607 if (uidState.foregroundOps != null) {
1608 uidState.evalForegroundOps(mOpModeWatchers);
1609 }
1610 }
1611 }
1612
Dianne Hackbornc2293022013-02-06 23:14:49 -08001613 @Override
1614 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001615 startWatchingModeWithFlags(op, packageName, 0, callback);
1616 }
1617
1618 @Override
1619 public void startWatchingModeWithFlags(int op, String packageName, int flags,
1620 IAppOpsCallback callback) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001621 int watchedUid = -1;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001622 final int callingUid = Binder.getCallingUid();
1623 final int callingPid = Binder.getCallingPid();
Dianne Hackborn5376edd2018-06-05 13:21:16 -07001624 // TODO: should have a privileged permission to protect this.
1625 // Also, if the caller has requested WATCH_FOREGROUND_CHANGES, should we require
1626 // the USAGE_STATS permission since this can provide information about when an
1627 // app is in the foreground?
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001628 Preconditions.checkArgumentInRange(op, AppOpsManager.OP_NONE,
1629 AppOpsManager._NUM_OP - 1, "Invalid op code: " + op);
Svetoslav Ganov8de59712015-12-09 18:25:13 -08001630 if (callback == null) {
1631 return;
1632 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001633 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -07001634 op = (op != AppOpsManager.OP_NONE) ? AppOpsManager.opToSwitch(op) : op;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001635 ModeCallback cb = mModeWatchers.get(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -08001636 if (cb == null) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001637 cb = new ModeCallback(callback, watchedUid, flags, callingUid, callingPid);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001638 mModeWatchers.put(callback.asBinder(), cb);
1639 }
1640 if (op != AppOpsManager.OP_NONE) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001641 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(op);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001642 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08001643 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001644 mOpModeWatchers.put(op, cbs);
1645 }
1646 cbs.add(cb);
1647 }
1648 if (packageName != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001649 ArraySet<ModeCallback> cbs = mPackageModeWatchers.get(packageName);
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 mPackageModeWatchers.put(packageName, cbs);
1653 }
1654 cbs.add(cb);
1655 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001656 evalAllForegroundOpsLocked();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001657 }
1658 }
1659
1660 @Override
1661 public void stopWatchingMode(IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -08001662 if (callback == null) {
1663 return;
1664 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001665 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001666 ModeCallback cb = mModeWatchers.remove(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -08001667 if (cb != null) {
1668 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001669 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001670 ArraySet<ModeCallback> cbs = mOpModeWatchers.valueAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001671 cbs.remove(cb);
1672 if (cbs.size() <= 0) {
1673 mOpModeWatchers.removeAt(i);
1674 }
1675 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001676 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001677 ArraySet<ModeCallback> cbs = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001678 cbs.remove(cb);
1679 if (cbs.size() <= 0) {
1680 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001681 }
1682 }
1683 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001684 evalAllForegroundOpsLocked();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001685 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001686 }
1687
1688 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001689 public IBinder getToken(IBinder clientToken) {
1690 synchronized (this) {
1691 ClientState cs = mClients.get(clientToken);
1692 if (cs == null) {
1693 cs = new ClientState(clientToken);
1694 mClients.put(clientToken, cs);
1695 }
1696 return cs;
1697 }
1698 }
1699
Svet Ganovd873ae62018-06-25 16:39:23 -07001700 public CheckOpsDelegate getAppOpsServiceDelegate() {
1701 synchronized (this) {
1702 return mCheckOpsDelegate;
1703 }
1704 }
1705
1706 public void setAppOpsServiceDelegate(CheckOpsDelegate delegate) {
1707 synchronized (this) {
1708 mCheckOpsDelegate = delegate;
1709 }
1710 }
1711
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001712 @Override
Svet Ganov9d528a12018-12-19 17:23:11 -08001713 public int checkOperationRaw(int code, int uid, String packageName) {
1714 return checkOperationInternal(code, uid, packageName, true /*raw*/);
1715 }
1716
1717 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -08001718 public int checkOperation(int code, int uid, String packageName) {
Svet Ganov9d528a12018-12-19 17:23:11 -08001719 return checkOperationInternal(code, uid, packageName, false /*raw*/);
1720 }
1721
1722 private int checkOperationInternal(int code, int uid, String packageName, boolean raw) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001723 final CheckOpsDelegate delegate;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001724 synchronized (this) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001725 delegate = mCheckOpsDelegate;
1726 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001727 if (delegate == null) {
Svet Ganov9d528a12018-12-19 17:23:11 -08001728 return checkOperationImpl(code, uid, packageName, raw);
Todd Kennedy556efba2018-11-15 07:43:55 -08001729 }
Svet Ganov9d528a12018-12-19 17:23:11 -08001730 return delegate.checkOperation(code, uid, packageName, raw,
Svet Ganovd873ae62018-06-25 16:39:23 -07001731 AppOpsService.this::checkOperationImpl);
1732 }
1733
Svet Ganov9d528a12018-12-19 17:23:11 -08001734 private int checkOperationImpl(int code, int uid, String packageName,
1735 boolean raw) {
Todd Kennedy556efba2018-11-15 07:43:55 -08001736 verifyIncomingUid(uid);
1737 verifyIncomingOp(code);
1738 String resolvedPackageName = resolvePackageName(uid, packageName);
1739 if (resolvedPackageName == null) {
1740 return AppOpsManager.MODE_IGNORED;
1741 }
Svet Ganov9d528a12018-12-19 17:23:11 -08001742 return checkOperationUnchecked(code, uid, resolvedPackageName, raw);
Todd Kennedy556efba2018-11-15 07:43:55 -08001743 }
1744
Svet Ganov9d528a12018-12-19 17:23:11 -08001745 private int checkOperationUnchecked(int code, int uid, String packageName,
1746 boolean raw) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001747 synchronized (this) {
Svet Ganovaf189e32019-02-15 18:45:29 -08001748 checkPackage(uid, packageName);
Todd Kennedy556efba2018-11-15 07:43:55 -08001749 if (isOpRestrictedLocked(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001750 return AppOpsManager.MODE_IGNORED;
1751 }
Svet Ganov2af57082015-07-30 08:44:20 -07001752 code = AppOpsManager.opToSwitch(code);
1753 UidState uidState = getUidStateLocked(uid, false);
Svet Ganovee438d42017-01-19 18:04:38 -08001754 if (uidState != null && uidState.opModes != null
1755 && uidState.opModes.indexOfKey(code) >= 0) {
Svet Ganov9d528a12018-12-19 17:23:11 -08001756 final int rawMode = uidState.opModes.get(code);
Svet Ganovaf189e32019-02-15 18:45:29 -08001757 return raw ? rawMode : uidState.evalMode(code, rawMode);
Svet Ganov2af57082015-07-30 08:44:20 -07001758 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001759 Op op = getOpLocked(code, uid, packageName, false, true, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001760 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -07001761 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001762 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001763 return raw ? op.mode : op.evalMode();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001764 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001765 }
1766
1767 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001768 public int checkAudioOperation(int code, int usage, int uid, String packageName) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001769 final CheckOpsDelegate delegate;
John Spurlock1af30c72014-03-10 08:33:35 -04001770 synchronized (this) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001771 delegate = mCheckOpsDelegate;
1772 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001773 if (delegate == null) {
1774 return checkAudioOperationImpl(code, usage, uid, packageName);
1775 }
Svet Ganovd873ae62018-06-25 16:39:23 -07001776 return delegate.checkAudioOperation(code, usage, uid, packageName,
1777 AppOpsService.this::checkAudioOperationImpl);
1778 }
1779
1780 private int checkAudioOperationImpl(int code, int usage, int uid, String packageName) {
Todd Kennedy556efba2018-11-15 07:43:55 -08001781 boolean suspended;
1782 try {
1783 suspended = isPackageSuspendedForUser(packageName, uid);
1784 } catch (IllegalArgumentException ex) {
1785 // Package not found.
1786 suspended = false;
1787 }
1788
1789 if (suspended) {
1790 Slog.i(TAG, "Audio disabled for suspended package=" + packageName
1791 + " for uid=" + uid);
1792 return AppOpsManager.MODE_IGNORED;
1793 }
1794
Svet Ganovd873ae62018-06-25 16:39:23 -07001795 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001796 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -04001797 if (mode != AppOpsManager.MODE_ALLOWED) {
1798 return mode;
1799 }
1800 }
1801 return checkOperation(code, uid, packageName);
1802 }
1803
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001804 private boolean isPackageSuspendedForUser(String pkg, int uid) {
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001805 try {
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001806 return AppGlobals.getPackageManager().isPackageSuspendedForUser(
1807 pkg, UserHandle.getUserId(uid));
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001808 } catch (RemoteException re) {
1809 throw new SecurityException("Could not talk to package manager service");
1810 }
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001811 }
1812
John Spurlock7b414672014-07-18 13:02:39 -04001813 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
1814 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1815 if (usageRestrictions != null) {
1816 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001817 if (r != null && !r.exceptionPackages.contains(packageName)) {
1818 return r.mode;
1819 }
1820 }
1821 return AppOpsManager.MODE_ALLOWED;
1822 }
1823
1824 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001825 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -04001826 String[] exceptionPackages) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07001827 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
John Spurlock1af30c72014-03-10 08:33:35 -04001828 verifyIncomingUid(uid);
1829 verifyIncomingOp(code);
1830 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001831 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1832 if (usageRestrictions == null) {
1833 usageRestrictions = new SparseArray<Restriction>();
1834 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -04001835 }
John Spurlock7b414672014-07-18 13:02:39 -04001836 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001837 if (mode != AppOpsManager.MODE_ALLOWED) {
1838 final Restriction r = new Restriction();
1839 r.mode = mode;
1840 if (exceptionPackages != null) {
1841 final int N = exceptionPackages.length;
1842 r.exceptionPackages = new ArraySet<String>(N);
1843 for (int i = 0; i < N; i++) {
1844 final String pkg = exceptionPackages[i];
1845 if (pkg != null) {
1846 r.exceptionPackages.add(pkg.trim());
1847 }
1848 }
1849 }
John Spurlock7b414672014-07-18 13:02:39 -04001850 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -04001851 }
1852 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001853
1854 mHandler.sendMessage(PooledLambda.obtainMessage(
Svet Ganov3a95f832018-03-23 17:44:30 -07001855 AppOpsService::notifyWatchersOfChange, this, code, UID_ANY));
John Spurlock1af30c72014-03-10 08:33:35 -04001856 }
1857
1858 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001859 public int checkPackage(int uid, String packageName) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001860 Preconditions.checkNotNull(packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001861 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001862 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1863 true /* uidMismatchExpected */);
1864 if (ops != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001865 return AppOpsManager.MODE_ALLOWED;
1866 } else {
1867 return AppOpsManager.MODE_ERRORED;
1868 }
1869 }
1870 }
1871
1872 @Override
Svet Ganovd873ae62018-06-25 16:39:23 -07001873 public int noteProxyOperation(int code, int proxyUid,
1874 String proxyPackageName, int proxiedUid, String proxiedPackageName) {
1875 verifyIncomingUid(proxyUid);
Svet Ganov99b60432015-06-27 13:15:22 -07001876 verifyIncomingOp(code);
Svet Ganovaf189e32019-02-15 18:45:29 -08001877
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001878 String resolveProxyPackageName = resolvePackageName(proxyUid, proxyPackageName);
1879 if (resolveProxyPackageName == null) {
1880 return AppOpsManager.MODE_IGNORED;
1881 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001882
1883 final boolean isProxyTrusted = mContext.checkPermission(
1884 Manifest.permission.UPDATE_APP_OPS_STATS, -1, proxyUid)
1885 == PackageManager.PERMISSION_GRANTED;
1886
1887 final int proxyFlags = isProxyTrusted ? AppOpsManager.OP_FLAG_TRUSTED_PROXY
1888 : AppOpsManager.OP_FLAG_UNTRUSTED_PROXY;
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001889 final int proxyMode = noteOperationUnchecked(code, proxyUid,
Svet Ganovaf189e32019-02-15 18:45:29 -08001890 resolveProxyPackageName, Process.INVALID_UID, null, proxyFlags);
Svet Ganov99b60432015-06-27 13:15:22 -07001891 if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
1892 return proxyMode;
1893 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001894
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001895 String resolveProxiedPackageName = resolvePackageName(proxiedUid, proxiedPackageName);
1896 if (resolveProxiedPackageName == null) {
1897 return AppOpsManager.MODE_IGNORED;
1898 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001899 final int proxiedFlags = isProxyTrusted ? AppOpsManager.OP_FLAG_TRUSTED_PROXIED
1900 : AppOpsManager.OP_FLAG_UNTRUSTED_PROXIED;
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001901 return noteOperationUnchecked(code, proxiedUid, resolveProxiedPackageName,
Svet Ganovaf189e32019-02-15 18:45:29 -08001902 proxyUid, resolveProxyPackageName, proxiedFlags);
Svet Ganov99b60432015-06-27 13:15:22 -07001903 }
1904
1905 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001906 public int noteOperation(int code, int uid, String packageName) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001907 final CheckOpsDelegate delegate;
1908 synchronized (this) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001909 delegate = mCheckOpsDelegate;
1910 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001911 if (delegate == null) {
1912 return noteOperationImpl(code, uid, packageName);
1913 }
Svet Ganovd873ae62018-06-25 16:39:23 -07001914 return delegate.noteOperation(code, uid, packageName,
1915 AppOpsService.this::noteOperationImpl);
1916 }
1917
1918 private int noteOperationImpl(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001919 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001920 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001921 String resolvedPackageName = resolvePackageName(uid, packageName);
1922 if (resolvedPackageName == null) {
1923 return AppOpsManager.MODE_IGNORED;
1924 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001925 return noteOperationUnchecked(code, uid, resolvedPackageName, Process.INVALID_UID, null,
1926 AppOpsManager.OP_FLAG_SELF);
Svet Ganov99b60432015-06-27 13:15:22 -07001927 }
1928
1929 private int noteOperationUnchecked(int code, int uid, String packageName,
Svet Ganovaf189e32019-02-15 18:45:29 -08001930 int proxyUid, String proxyPackageName, @OpFlags int flags) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001931 synchronized (this) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001932 final Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
Yohei Yukawaa965d652017-10-12 15:02:26 -07001933 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001934 if (ops == null) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -08001935 scheduleOpNotedIfNeededLocked(code, uid, packageName,
1936 AppOpsManager.MODE_IGNORED);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001937 if (DEBUG) Slog.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001938 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001939 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001940 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001941 final Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07001942 if (isOpRestrictedLocked(uid, code, packageName)) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -08001943 scheduleOpNotedIfNeededLocked(code, uid, packageName,
1944 AppOpsManager.MODE_IGNORED);
Jason Monk62062992014-05-06 09:55:28 -04001945 return AppOpsManager.MODE_IGNORED;
1946 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001947 final UidState uidState = ops.uidState;
Svet Ganovaf189e32019-02-15 18:45:29 -08001948 if (op.running) {
1949 final OpEntry entry = new OpEntry(op.op, op.running, op.mode, op.mAccessTimes,
1950 op.mRejectTimes, op.mDurations, op.mProxyUids, op.mProxyPackageNames);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001951 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
Svet Ganovaf189e32019-02-15 18:45:29 -08001952 + " code " + code + " time=" + entry.getLastAccessTime(uidState.state,
1953 uidState.state, flags) + " duration=" + entry.getLastDuration(
1954 uidState.state, uidState.state, flags));
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001955 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001956
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001957 final int switchCode = AppOpsManager.opToSwitch(code);
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001958 // If there is a non-default per UID policy (we set UID op mode only if
1959 // non-default) it takes over, otherwise use the per package policy.
1960 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Svet Ganovaf189e32019-02-15 18:45:29 -08001961 final int uidMode = uidState.evalMode(code, uidState.opModes.get(switchCode));
Svet Ganov2af57082015-07-30 08:44:20 -07001962 if (uidMode != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001963 if (DEBUG) Slog.d(TAG, "noteOperation: uid reject #" + uidMode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07001964 + switchCode + " (" + code + ") uid " + uid + " package "
1965 + packageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08001966 op.rejected(System.currentTimeMillis(), proxyUid, proxyPackageName,
1967 uidState.state, flags);
1968 mHistoricalRegistry.incrementOpRejected(code, uid, packageName,
1969 uidState.state, flags);
Svet Ganovb3d2ae22018-12-17 22:06:15 -08001970 scheduleOpNotedIfNeededLocked(code, uid, packageName, uidMode);
Svet Ganov2af57082015-07-30 08:44:20 -07001971 return uidMode;
1972 }
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001973 } else {
1974 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
Svet Ganovaf189e32019-02-15 18:45:29 -08001975 final int mode = switchOp.evalMode();
1976 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001977 if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + mode + " for code "
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001978 + switchCode + " (" + code + ") uid " + uid + " package "
1979 + packageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08001980 op.rejected(System.currentTimeMillis(), proxyUid, proxyPackageName,
1981 uidState.state, flags);
1982 mHistoricalRegistry.incrementOpRejected(code, uid, packageName,
1983 uidState.state, flags);
1984 scheduleOpNotedIfNeededLocked(code, uid, packageName, mode);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001985 return mode;
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001986 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001987 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001988 if (DEBUG) Slog.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001989 + " package " + packageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08001990 op.accessed(System.currentTimeMillis(), proxyUid, proxyPackageName,
1991 uidState.state, flags);
Svet Ganov8455ba22019-01-02 13:05:56 -08001992 mHistoricalRegistry.incrementOpAccessedCount(op.op, uid, packageName,
Svet Ganovaf189e32019-02-15 18:45:29 -08001993 uidState.state, flags);
Svet Ganovb3d2ae22018-12-17 22:06:15 -08001994 scheduleOpNotedIfNeededLocked(code, uid, packageName,
1995 AppOpsManager.MODE_ALLOWED);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001996 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001997 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001998 }
1999
2000 @Override
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002001 public void startWatchingActive(int[] ops, IAppOpsActiveCallback callback) {
Svet Ganovf7b47252018-02-26 11:11:27 -08002002 int watchedUid = -1;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002003 final int callingUid = Binder.getCallingUid();
2004 final int callingPid = Binder.getCallingPid();
Svet Ganovf7b47252018-02-26 11:11:27 -08002005 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
2006 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002007 watchedUid = callingUid;
Svet Ganovf7b47252018-02-26 11:11:27 -08002008 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002009 if (ops != null) {
2010 Preconditions.checkArrayElementsInRange(ops, 0,
2011 AppOpsManager._NUM_OP - 1, "Invalid op code in: " + Arrays.toString(ops));
2012 }
2013 if (callback == null) {
2014 return;
2015 }
2016 synchronized (this) {
2017 SparseArray<ActiveCallback> callbacks = mActiveWatchers.get(callback.asBinder());
2018 if (callbacks == null) {
2019 callbacks = new SparseArray<>();
2020 mActiveWatchers.put(callback.asBinder(), callbacks);
2021 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002022 final ActiveCallback activeCallback = new ActiveCallback(callback, watchedUid,
2023 callingUid, callingPid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002024 for (int op : ops) {
2025 callbacks.put(op, activeCallback);
2026 }
2027 }
2028 }
2029
2030 @Override
2031 public void stopWatchingActive(IAppOpsActiveCallback callback) {
2032 if (callback == null) {
2033 return;
2034 }
2035 synchronized (this) {
2036 final SparseArray<ActiveCallback> activeCallbacks =
2037 mActiveWatchers.remove(callback.asBinder());
2038 if (activeCallbacks == null) {
2039 return;
2040 }
2041 final int callbackCount = activeCallbacks.size();
2042 for (int i = 0; i < callbackCount; i++) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002043 activeCallbacks.valueAt(i).destroy();
2044 }
2045 }
2046 }
2047
2048 @Override
2049 public void startWatchingNoted(@NonNull int[] ops, @NonNull IAppOpsNotedCallback callback) {
2050 int watchedUid = Process.INVALID_UID;
2051 final int callingUid = Binder.getCallingUid();
2052 final int callingPid = Binder.getCallingPid();
2053 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
2054 != PackageManager.PERMISSION_GRANTED) {
2055 watchedUid = callingUid;
2056 }
2057 Preconditions.checkArgument(!ArrayUtils.isEmpty(ops), "Ops cannot be null or empty");
2058 Preconditions.checkArrayElementsInRange(ops, 0, AppOpsManager._NUM_OP - 1,
2059 "Invalid op code in: " + Arrays.toString(ops));
2060 Preconditions.checkNotNull(callback, "Callback cannot be null");
2061 synchronized (this) {
2062 SparseArray<NotedCallback> callbacks = mNotedWatchers.get(callback.asBinder());
2063 if (callbacks == null) {
2064 callbacks = new SparseArray<>();
2065 mNotedWatchers.put(callback.asBinder(), callbacks);
2066 }
2067 final NotedCallback notedCallback = new NotedCallback(callback, watchedUid,
2068 callingUid, callingPid);
2069 for (int op : ops) {
2070 callbacks.put(op, notedCallback);
2071 }
2072 }
2073 }
2074
2075 @Override
2076 public void stopWatchingNoted(IAppOpsNotedCallback callback) {
2077 Preconditions.checkNotNull(callback, "Callback cannot be null");
2078 synchronized (this) {
2079 final SparseArray<NotedCallback> notedCallbacks =
2080 mNotedWatchers.remove(callback.asBinder());
2081 if (notedCallbacks == null) {
2082 return;
2083 }
2084 final int callbackCount = notedCallbacks.size();
2085 for (int i = 0; i < callbackCount; i++) {
2086 notedCallbacks.valueAt(i).destroy();
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002087 }
2088 }
2089 }
2090
2091 @Override
Svet Ganovf7b47252018-02-26 11:11:27 -08002092 public int startOperation(IBinder token, int code, int uid, String packageName,
2093 boolean startIfModeDefault) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002094 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08002095 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002096 String resolvedPackageName = resolvePackageName(uid, packageName);
2097 if (resolvedPackageName == null) {
2098 return AppOpsManager.MODE_IGNORED;
2099 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002100 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002101 synchronized (this) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002102 final Ops ops = getOpsRawLocked(uid, resolvedPackageName, true /* edit */,
Yohei Yukawaa965d652017-10-12 15:02:26 -07002103 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002104 if (ops == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002105 if (DEBUG) Slog.d(TAG, "startOperation: no op for code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002106 + " package " + resolvedPackageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07002107 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002108 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002109 final Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07002110 if (isOpRestrictedLocked(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -04002111 return AppOpsManager.MODE_IGNORED;
2112 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002113 final int switchCode = AppOpsManager.opToSwitch(code);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002114 final UidState uidState = ops.uidState;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002115 // If there is a non-default per UID policy (we set UID op mode only if
2116 // non-default) it takes over, otherwise use the per package policy.
Svet Ganovaf189e32019-02-15 18:45:29 -08002117 final int opCode = op.op;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002118 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002119 final int uidMode = uidState.evalMode(code, uidState.opModes.get(switchCode));
Svet Ganovf7b47252018-02-26 11:11:27 -08002120 if (uidMode != AppOpsManager.MODE_ALLOWED
2121 && (!startIfModeDefault || uidMode != AppOpsManager.MODE_DEFAULT)) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002122 if (DEBUG) Slog.d(TAG, "noteOperation: uid reject #" + uidMode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07002123 + switchCode + " (" + code + ") uid " + uid + " package "
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002124 + resolvedPackageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08002125 // We don't support proxy long running ops (start/stop)
2126 op.rejected(System.currentTimeMillis(), -1 /*proxyUid*/,
2127 null /*proxyPackage*/, uidState.state, AppOpsManager.OP_FLAG_SELF);
2128 mHistoricalRegistry.incrementOpRejected(opCode, uid, packageName,
2129 uidState.state, AppOpsManager.OP_FLAG_SELF);
Svet Ganov2af57082015-07-30 08:44:20 -07002130 return uidMode;
2131 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002132 } else {
2133 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
Svet Ganovaf189e32019-02-15 18:45:29 -08002134 final int mode = switchOp.evalMode();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002135 if (mode != AppOpsManager.MODE_ALLOWED
2136 && (!startIfModeDefault || mode != AppOpsManager.MODE_DEFAULT)) {
2137 if (DEBUG) Slog.d(TAG, "startOperation: reject #" + mode + " for code "
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002138 + switchCode + " (" + code + ") uid " + uid + " package "
2139 + resolvedPackageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08002140 // We don't support proxy long running ops (start/stop)
2141 op.rejected(System.currentTimeMillis(), -1 /*proxyUid*/,
2142 null /*proxyPackage*/, uidState.state, AppOpsManager.OP_FLAG_SELF);
2143 mHistoricalRegistry.incrementOpRejected(opCode, uid, packageName,
2144 uidState.state, AppOpsManager.OP_FLAG_SELF);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002145 return mode;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002146 }
Svet Ganov2af57082015-07-30 08:44:20 -07002147 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002148 if (DEBUG) Slog.d(TAG, "startOperation: allowing code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002149 + " package " + resolvedPackageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002150 if (op.startNesting == 0) {
2151 op.startRealtime = SystemClock.elapsedRealtime();
Svet Ganovaf189e32019-02-15 18:45:29 -08002152 // We don't support proxy long running ops (start/stop)
2153 op.started(System.currentTimeMillis(), uidState.state,
2154 AppOpsManager.OP_FLAG_SELF);
2155 mHistoricalRegistry.incrementOpAccessedCount(opCode, uid, packageName,
2156 uidState.state, AppOpsManager.OP_FLAG_SELF);
2157
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002158 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002159 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002160 op.startNesting++;
2161 uidState.startNesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002162 if (client.mStartedOps != null) {
2163 client.mStartedOps.add(op);
2164 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002165 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002166
2167 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002168 }
2169
2170 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002171 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002172 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08002173 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002174 String resolvedPackageName = resolvePackageName(uid, packageName);
2175 if (resolvedPackageName == null) {
2176 return;
2177 }
2178 if (!(token instanceof ClientState)) {
2179 return;
2180 }
2181 ClientState client = (ClientState) token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002182 synchronized (this) {
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07002183 Op op = getOpLocked(code, uid, resolvedPackageName, true, true, false);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002184 if (op == null) {
2185 return;
2186 }
Svet Ganovf7b47252018-02-26 11:11:27 -08002187 if (!client.mStartedOps.remove(op)) {
Svet Ganovf5d5af12018-03-18 11:51:17 -07002188 // We finish ops when packages get removed to guarantee no dangling
2189 // started ops. However, some part of the system may asynchronously
2190 // finish ops for an already gone package. Hence, finishing an op
2191 // for a non existing package is fine and we don't log as a wtf.
2192 final long identity = Binder.clearCallingIdentity();
2193 try {
2194 if (LocalServices.getService(PackageManagerInternal.class).getPackageUid(
2195 resolvedPackageName, 0, UserHandle.getUserId(uid)) < 0) {
2196 Slog.i(TAG, "Finishing op=" + AppOpsManager.opToName(code)
2197 + " for non-existing package=" + resolvedPackageName
2198 + " in uid=" + uid);
2199 return;
2200 }
2201 } finally {
2202 Binder.restoreCallingIdentity(identity);
2203 }
Svet Ganovaf189e32019-02-15 18:45:29 -08002204 Slog.wtf(TAG, "Operation not started: uid=" + op.uidState.uid + " pkg="
Svet Ganovf5d5af12018-03-18 11:51:17 -07002205 + op.packageName + " op=" + AppOpsManager.opToName(op.op));
Svet Ganov31d83ae2018-03-15 10:45:56 -07002206 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002207 }
Svet Ganova7a0db62018-02-27 20:08:01 -08002208 finishOperationLocked(op, /*finishNested*/ false);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002209 if (op.startNesting <= 0) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002210 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, false);
2211 }
2212 }
2213 }
2214
2215 private void scheduleOpActiveChangedIfNeededLocked(int code, int uid, String packageName,
2216 boolean active) {
2217 ArraySet<ActiveCallback> dispatchedCallbacks = null;
2218 final int callbackListCount = mActiveWatchers.size();
2219 for (int i = 0; i < callbackListCount; i++) {
2220 final SparseArray<ActiveCallback> callbacks = mActiveWatchers.valueAt(i);
2221 ActiveCallback callback = callbacks.get(code);
2222 if (callback != null) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002223 if (callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
Svet Ganovf7b47252018-02-26 11:11:27 -08002224 continue;
2225 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002226 if (dispatchedCallbacks == null) {
2227 dispatchedCallbacks = new ArraySet<>();
2228 }
2229 dispatchedCallbacks.add(callback);
2230 }
2231 }
2232 if (dispatchedCallbacks == null) {
2233 return;
2234 }
2235 mHandler.sendMessage(PooledLambda.obtainMessage(
2236 AppOpsService::notifyOpActiveChanged,
2237 this, dispatchedCallbacks, code, uid, packageName, active));
2238 }
2239
2240 private void notifyOpActiveChanged(ArraySet<ActiveCallback> callbacks,
2241 int code, int uid, String packageName, boolean active) {
2242 // There are components watching for mode changes such as window manager
2243 // and location manager which are in our process. The callbacks in these
2244 // components may require permissions our remote caller does not have.
2245 final long identity = Binder.clearCallingIdentity();
2246 try {
2247 final int callbackCount = callbacks.size();
2248 for (int i = 0; i < callbackCount; i++) {
2249 final ActiveCallback callback = callbacks.valueAt(i);
2250 try {
2251 callback.mCallback.opActiveChanged(code, uid, packageName, active);
2252 } catch (RemoteException e) {
2253 /* do nothing */
2254 }
2255 }
2256 } finally {
2257 Binder.restoreCallingIdentity(identity);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002258 }
2259 }
2260
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002261 private void scheduleOpNotedIfNeededLocked(int code, int uid, String packageName,
2262 int result) {
2263 ArraySet<NotedCallback> dispatchedCallbacks = null;
2264 final int callbackListCount = mNotedWatchers.size();
2265 for (int i = 0; i < callbackListCount; i++) {
2266 final SparseArray<NotedCallback> callbacks = mNotedWatchers.valueAt(i);
2267 final NotedCallback callback = callbacks.get(code);
2268 if (callback != null) {
2269 if (callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
2270 continue;
2271 }
2272 if (dispatchedCallbacks == null) {
2273 dispatchedCallbacks = new ArraySet<>();
2274 }
2275 dispatchedCallbacks.add(callback);
2276 }
2277 }
2278 if (dispatchedCallbacks == null) {
2279 return;
2280 }
2281 mHandler.sendMessage(PooledLambda.obtainMessage(
2282 AppOpsService::notifyOpChecked,
2283 this, dispatchedCallbacks, code, uid, packageName, result));
2284 }
2285
2286 private void notifyOpChecked(ArraySet<NotedCallback> callbacks,
2287 int code, int uid, String packageName, int result) {
2288 // There are components watching for checks in our process. The callbacks in
2289 // these components may require permissions our remote caller does not have.
2290 final long identity = Binder.clearCallingIdentity();
2291 try {
2292 final int callbackCount = callbacks.size();
2293 for (int i = 0; i < callbackCount; i++) {
2294 final NotedCallback callback = callbacks.valueAt(i);
2295 try {
2296 callback.mCallback.opNoted(code, uid, packageName, result);
2297 } catch (RemoteException e) {
2298 /* do nothing */
2299 }
2300 }
2301 } finally {
2302 Binder.restoreCallingIdentity(identity);
2303 }
2304 }
2305
Svet Ganovb9d71a62015-04-30 10:38:13 -07002306 @Override
2307 public int permissionToOpCode(String permission) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002308 if (permission == null) {
2309 return AppOpsManager.OP_NONE;
2310 }
Svet Ganovb9d71a62015-04-30 10:38:13 -07002311 return AppOpsManager.permissionToOpCode(permission);
2312 }
2313
Svet Ganova7a0db62018-02-27 20:08:01 -08002314 void finishOperationLocked(Op op, boolean finishNested) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002315 final int opCode = op.op;
2316 final int uid = op.uidState.uid;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002317 if (op.startNesting <= 1 || finishNested) {
2318 if (op.startNesting == 1 || finishNested) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002319 // We don't support proxy long running ops (start/stop)
2320 final long duration = SystemClock.elapsedRealtime() - op.startRealtime;
2321 op.finished(System.currentTimeMillis(), duration, op.uidState.state,
2322 AppOpsManager.OP_FLAG_SELF);
2323 mHistoricalRegistry.increaseOpAccessDuration(opCode, uid, op.packageName,
2324 op.uidState.state, AppOpsManager.OP_FLAG_SELF, duration);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002325 } else {
Svet Ganovaf189e32019-02-15 18:45:29 -08002326 final OpEntry entry = new OpEntry(op.op, op.running, op.mode, op.mAccessTimes,
2327 op.mRejectTimes, op.mDurations, op.mProxyUids, op.mProxyPackageNames);
2328 Slog.w(TAG, "Finishing op nesting under-run: uid " + uid + " pkg "
2329 + op.packageName + " code " + opCode + " time="
2330 + entry.getLastAccessTime(OP_FLAGS_ALL)
2331 + " duration=" + entry.getLastDuration(MAX_PRIORITY_UID_STATE,
2332 MIN_PRIORITY_UID_STATE, OP_FLAGS_ALL) + " nesting=" + op.startNesting);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002333 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002334 if (op.startNesting >= 1) {
2335 op.uidState.startNesting -= op.startNesting;
2336 }
2337 op.startNesting = 0;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002338 } else {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002339 op.startNesting--;
2340 op.uidState.startNesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002341 }
2342 }
2343
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002344 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002345 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002346 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002347 }
2348 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002349 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002350 }
2351 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
2352 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002353 }
2354
Dianne Hackborn961321f2013-02-05 17:22:41 -08002355 private void verifyIncomingOp(int op) {
2356 if (op >= 0 && op < AppOpsManager._NUM_OP) {
2357 return;
2358 }
2359 throw new IllegalArgumentException("Bad operation #" + op);
2360 }
2361
Svet Ganovaf189e32019-02-15 18:45:29 -08002362 private @NonNull UidState getUidStateLocked(int uid, boolean edit) {
Svet Ganov2af57082015-07-30 08:44:20 -07002363 UidState uidState = mUidStates.get(uid);
2364 if (uidState == null) {
2365 if (!edit) {
2366 return null;
2367 }
2368 uidState = new UidState(uid);
2369 mUidStates.put(uid, uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002370 } else {
2371 if (uidState.pendingStateCommitTime != 0) {
Dianne Hackborn9fb93502018-06-18 12:29:44 -07002372 if (uidState.pendingStateCommitTime < mLastRealtime) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002373 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002374 } else {
Dianne Hackborn9fb93502018-06-18 12:29:44 -07002375 mLastRealtime = SystemClock.elapsedRealtime();
2376 if (uidState.pendingStateCommitTime < mLastRealtime) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002377 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002378 }
2379 }
2380 }
Svet Ganov2af57082015-07-30 08:44:20 -07002381 }
2382 return uidState;
2383 }
2384
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002385 private void commitUidPendingStateLocked(UidState uidState) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002386 final boolean lastForeground = uidState.state <= UID_STATE_MAX_LAST_NON_RESTRICTED;
2387 final boolean nowForeground = uidState.pendingState <= UID_STATE_MAX_LAST_NON_RESTRICTED;
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002388 uidState.state = uidState.pendingState;
2389 uidState.pendingStateCommitTime = 0;
Dianne Hackborne93ab412018-05-14 17:52:30 -07002390 if (uidState.hasForegroundWatchers && lastForeground != nowForeground) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002391 for (int fgi = uidState.foregroundOps.size() - 1; fgi >= 0; fgi--) {
2392 if (!uidState.foregroundOps.valueAt(fgi)) {
2393 continue;
2394 }
2395 final int code = uidState.foregroundOps.keyAt(fgi);
Svet Ganovaf189e32019-02-15 18:45:29 -08002396 // For location ops we consider fg state only if the fg service
2397 // is of location type, for all other ops any fg service will do.
2398 final long resolvedLastRestrictedUidState = resolveFirstUnrestrictedUidState(code);
2399 final boolean resolvedLastFg = uidState.state <= resolvedLastRestrictedUidState;
2400 final boolean resolvedNowBg = uidState.pendingState
2401 <= resolvedLastRestrictedUidState;
2402 if (resolvedLastFg == resolvedNowBg) {
2403 continue;
2404 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002405 final ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
2406 if (callbacks != null) {
2407 for (int cbi = callbacks.size() - 1; cbi >= 0; cbi--) {
2408 final ModeCallback callback = callbacks.valueAt(cbi);
2409 if ((callback.mFlags & AppOpsManager.WATCH_FOREGROUND_CHANGES) == 0
2410 || !callback.isWatchingUid(uidState.uid)) {
2411 continue;
2412 }
2413 boolean doAllPackages = uidState.opModes != null
Hai Zhang2b98fb32018-09-21 15:18:46 -07002414 && uidState.opModes.indexOfKey(code) >= 0
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002415 && uidState.opModes.get(code) == AppOpsManager.MODE_FOREGROUND;
2416 if (uidState.pkgOps != null) {
2417 for (int pkgi = uidState.pkgOps.size() - 1; pkgi >= 0; pkgi--) {
2418 final Op op = uidState.pkgOps.valueAt(pkgi).get(code);
Svet Ganovaf189e32019-02-15 18:45:29 -08002419 if (op == null) {
2420 continue;
2421 }
2422 if (doAllPackages || op.mode == AppOpsManager.MODE_FOREGROUND) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002423 mHandler.sendMessage(PooledLambda.obtainMessage(
2424 AppOpsService::notifyOpChanged,
2425 this, callback, code, uidState.uid,
2426 uidState.pkgOps.keyAt(pkgi)));
2427 }
2428 }
2429 }
2430 }
2431 }
2432 }
2433 }
2434 }
2435
Yohei Yukawaa965d652017-10-12 15:02:26 -07002436 private Ops getOpsRawLocked(int uid, String packageName, boolean edit,
2437 boolean uidMismatchExpected) {
Svet Ganov2af57082015-07-30 08:44:20 -07002438 UidState uidState = getUidStateLocked(uid, edit);
2439 if (uidState == null) {
2440 return null;
2441 }
2442
2443 if (uidState.pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002444 if (!edit) {
2445 return null;
2446 }
Svet Ganov2af57082015-07-30 08:44:20 -07002447 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002448 }
Svet Ganov2af57082015-07-30 08:44:20 -07002449
2450 Ops ops = uidState.pkgOps.get(packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002451 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002452 if (!edit) {
2453 return null;
2454 }
Jason Monk1c7c3192014-06-26 12:52:18 -04002455 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002456 // This is the first time we have seen this package name under this uid,
2457 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -08002458 if (uid != 0) {
2459 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002460 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -08002461 int pkgUid = -1;
2462 try {
Jason Monk1c7c3192014-06-26 12:52:18 -04002463 ApplicationInfo appInfo = ActivityThread.getPackageManager()
Jeff Sharkeycd654482016-01-08 17:42:11 -07002464 .getApplicationInfo(packageName,
Svet Ganovad0a49b2018-10-29 10:07:08 -07002465 PackageManager.MATCH_DIRECT_BOOT_AWARE
Svet Ganov8455ba22019-01-02 13:05:56 -08002466 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkeycd654482016-01-08 17:42:11 -07002467 UserHandle.getUserId(uid));
Jason Monk1c7c3192014-06-26 12:52:18 -04002468 if (appInfo != null) {
2469 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002470 isPrivileged = (appInfo.privateFlags
2471 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04002472 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08002473 pkgUid = resolveUid(packageName);
2474 if (pkgUid >= 0) {
Chien-Yu Chen75cade02016-01-11 10:56:21 -08002475 isPrivileged = false;
Jason Monk1c7c3192014-06-26 12:52:18 -04002476 }
Dianne Hackborn713df152013-05-17 11:27:57 -07002477 }
Jason Monk1c7c3192014-06-26 12:52:18 -04002478 } catch (RemoteException e) {
2479 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08002480 }
2481 if (pkgUid != uid) {
2482 // Oops! The package name is not valid for the uid they are calling
2483 // under. Abort.
Yohei Yukawaa965d652017-10-12 15:02:26 -07002484 if (!uidMismatchExpected) {
2485 RuntimeException ex = new RuntimeException("here");
2486 ex.fillInStackTrace();
2487 Slog.w(TAG, "Bad call: specified package " + packageName
2488 + " under uid " + uid + " but it is really " + pkgUid, ex);
2489 }
Dianne Hackborn514074f2013-02-11 10:52:46 -08002490 return null;
2491 }
2492 } finally {
2493 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002494 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002495 }
Svet Ganov2af57082015-07-30 08:44:20 -07002496 ops = new Ops(packageName, uidState, isPrivileged);
2497 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002498 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08002499 return ops;
2500 }
2501
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07002502 /**
2503 * Get the state of all ops for a package, <b>don't verify that package belongs to uid</b>.
2504 *
2505 * <p>Usually callers should use {@link #getOpLocked} and not call this directly.
2506 *
2507 * @param uid The uid the of the package
2508 * @param packageName The package name for which to get the state for
2509 * @param edit Iff {@code true} create the {@link Ops} object if not yet created
2510 * @param isPrivileged Whether the package is privileged or not
2511 *
2512 * @return The {@link Ops state} of all ops for the package
2513 */
2514 private @Nullable Ops getOpsRawNoVerifyLocked(int uid, @NonNull String packageName,
2515 boolean edit, boolean isPrivileged) {
2516 UidState uidState = getUidStateLocked(uid, edit);
2517 if (uidState == null) {
2518 return null;
2519 }
2520
2521 if (uidState.pkgOps == null) {
2522 if (!edit) {
2523 return null;
2524 }
2525 uidState.pkgOps = new ArrayMap<>();
2526 }
2527
2528 Ops ops = uidState.pkgOps.get(packageName);
2529 if (ops == null) {
2530 if (!edit) {
2531 return null;
2532 }
2533 ops = new Ops(packageName, uidState, isPrivileged);
2534 uidState.pkgOps.put(packageName, ops);
2535 }
2536 return ops;
2537 }
2538
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002539 private void scheduleWriteLocked() {
2540 if (!mWriteScheduled) {
2541 mWriteScheduled = true;
2542 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
2543 }
2544 }
2545
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002546 private void scheduleFastWriteLocked() {
2547 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002548 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002549 mFastWriteScheduled = true;
2550 mHandler.removeCallbacks(mWriteRunner);
2551 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002552 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002553 }
2554
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07002555 /**
2556 * Get the state of an op for a uid.
2557 *
2558 * @param code The code of the op
2559 * @param uid The uid the of the package
2560 * @param packageName The package name for which to get the state for
2561 * @param edit Iff {@code true} create the {@link Op} object if not yet created
2562 * @param verifyUid Iff {@code true} check that the package belongs to the uid
2563 * @param isPrivileged Whether the package is privileged or not (only used if {@code verifyUid
2564 * == false})
2565 *
2566 * @return The {@link Op state} of the op
2567 */
2568 private @Nullable Op getOpLocked(int code, int uid, @NonNull String packageName, boolean edit,
2569 boolean verifyUid, boolean isPrivileged) {
2570 Ops ops;
2571
2572 if (verifyUid) {
2573 ops = getOpsRawLocked(uid, packageName, edit, false /* uidMismatchExpected */);
2574 } else {
2575 ops = getOpsRawNoVerifyLocked(uid, packageName, edit, isPrivileged);
2576 }
2577
Dianne Hackborn72e39832013-01-18 18:36:09 -08002578 if (ops == null) {
2579 return null;
2580 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002581 return getOpLocked(ops, code, edit);
2582 }
2583
2584 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002585 Op op = ops.get(code);
2586 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002587 if (!edit) {
2588 return null;
2589 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002590 op = new Op(ops.uidState, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002591 ops.put(code, op);
2592 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002593 if (edit) {
2594 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002595 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002596 return op;
2597 }
2598
Svet Ganov442ed572016-08-17 17:29:43 -07002599 private boolean isOpRestrictedLocked(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04002600 int userHandle = UserHandle.getUserId(uid);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002601 final int restrictionSetCount = mOpUserRestrictions.size();
Ruben Brunk29931bc2016-03-11 00:24:26 -08002602
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002603 for (int i = 0; i < restrictionSetCount; i++) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002604 // For each client, check that the given op is not restricted, or that the given
2605 // package is exempt from the restriction.
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002606 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07002607 if (restrictionState.hasRestriction(code, packageName, userHandle)) {
2608 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
2609 // If we are the system, bypass user restrictions for certain codes
2610 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07002611 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
2612 false /* uidMismatchExpected */);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07002613 if ((ops != null) && ops.isPrivileged) {
2614 return false;
2615 }
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002616 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002617 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002618 return true;
Jason Monk1c7c3192014-06-26 12:52:18 -04002619 }
Jason Monk62062992014-05-06 09:55:28 -04002620 }
2621 return false;
2622 }
2623
Dianne Hackborn35654b62013-01-14 17:38:02 -08002624 void readState() {
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002625 int oldVersion = NO_VERSION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08002626 synchronized (mFile) {
2627 synchronized (this) {
2628 FileInputStream stream;
2629 try {
2630 stream = mFile.openRead();
2631 } catch (FileNotFoundException e) {
2632 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
2633 return;
2634 }
2635 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002636 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002637 try {
2638 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002639 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08002640 int type;
2641 while ((type = parser.next()) != XmlPullParser.START_TAG
2642 && type != XmlPullParser.END_DOCUMENT) {
2643 ;
2644 }
2645
2646 if (type != XmlPullParser.START_TAG) {
2647 throw new IllegalStateException("no start tag found");
2648 }
2649
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002650 final String versionString = parser.getAttributeValue(null, "v");
2651 if (versionString != null) {
2652 oldVersion = Integer.parseInt(versionString);
2653 }
2654
Dianne Hackborn35654b62013-01-14 17:38:02 -08002655 int outerDepth = parser.getDepth();
2656 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2657 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2658 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2659 continue;
2660 }
2661
2662 String tagName = parser.getName();
2663 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00002664 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07002665 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07002666 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002667 } else {
2668 Slog.w(TAG, "Unknown element under <app-ops>: "
2669 + parser.getName());
2670 XmlUtils.skipCurrentTag(parser);
2671 }
2672 }
2673 success = true;
2674 } catch (IllegalStateException e) {
2675 Slog.w(TAG, "Failed parsing " + e);
2676 } catch (NullPointerException e) {
2677 Slog.w(TAG, "Failed parsing " + e);
2678 } catch (NumberFormatException e) {
2679 Slog.w(TAG, "Failed parsing " + e);
2680 } catch (XmlPullParserException e) {
2681 Slog.w(TAG, "Failed parsing " + e);
2682 } catch (IOException e) {
2683 Slog.w(TAG, "Failed parsing " + e);
2684 } catch (IndexOutOfBoundsException e) {
2685 Slog.w(TAG, "Failed parsing " + e);
2686 } finally {
2687 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07002688 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002689 }
2690 try {
2691 stream.close();
2692 } catch (IOException e) {
2693 }
2694 }
2695 }
2696 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002697 synchronized (this) {
2698 upgradeLocked(oldVersion);
2699 }
2700 }
2701
2702 private void upgradeRunAnyInBackgroundLocked() {
2703 for (int i = 0; i < mUidStates.size(); i++) {
2704 final UidState uidState = mUidStates.valueAt(i);
2705 if (uidState == null) {
2706 continue;
2707 }
2708 if (uidState.opModes != null) {
2709 final int idx = uidState.opModes.indexOfKey(AppOpsManager.OP_RUN_IN_BACKGROUND);
2710 if (idx >= 0) {
2711 uidState.opModes.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND,
Svet Ganovaf189e32019-02-15 18:45:29 -08002712 uidState.opModes.valueAt(idx));
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002713 }
2714 }
2715 if (uidState.pkgOps == null) {
2716 continue;
2717 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002718 boolean changed = false;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002719 for (int j = 0; j < uidState.pkgOps.size(); j++) {
2720 Ops ops = uidState.pkgOps.valueAt(j);
2721 if (ops != null) {
2722 final Op op = ops.get(AppOpsManager.OP_RUN_IN_BACKGROUND);
2723 if (op != null && op.mode != AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002724 final Op copy = new Op(op.uidState, op.packageName,
Svet Ganovaf189e32019-02-15 18:45:29 -08002725 AppOpsManager.OP_RUN_ANY_IN_BACKGROUND);
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002726 copy.mode = op.mode;
2727 ops.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, copy);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002728 changed = true;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002729 }
2730 }
2731 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002732 if (changed) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002733 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002734 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002735 }
2736 }
2737
2738 private void upgradeLocked(int oldVersion) {
2739 if (oldVersion >= CURRENT_VERSION) {
2740 return;
2741 }
2742 Slog.d(TAG, "Upgrading app-ops xml from version " + oldVersion + " to " + CURRENT_VERSION);
2743 switch (oldVersion) {
2744 case NO_VERSION:
2745 upgradeRunAnyInBackgroundLocked();
2746 // fall through
2747 case 1:
2748 // for future upgrades
2749 }
2750 scheduleFastWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002751 }
2752
Svet Ganovaf189e32019-02-15 18:45:29 -08002753 private void readUidOps(XmlPullParser parser) throws NumberFormatException,
Svet Ganov2af57082015-07-30 08:44:20 -07002754 XmlPullParserException, IOException {
2755 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
2756 int outerDepth = parser.getDepth();
2757 int type;
2758 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2759 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2760 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2761 continue;
2762 }
2763
2764 String tagName = parser.getName();
2765 if (tagName.equals("op")) {
2766 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
2767 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
2768 UidState uidState = getUidStateLocked(uid, true);
2769 if (uidState.opModes == null) {
2770 uidState.opModes = new SparseIntArray();
2771 }
2772 uidState.opModes.put(code, mode);
2773 } else {
2774 Slog.w(TAG, "Unknown element under <uid-ops>: "
2775 + parser.getName());
2776 XmlUtils.skipCurrentTag(parser);
2777 }
2778 }
2779 }
2780
Svet Ganovaf189e32019-02-15 18:45:29 -08002781 private void readPackage(XmlPullParser parser)
2782 throws NumberFormatException, XmlPullParserException, IOException {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002783 String pkgName = parser.getAttributeValue(null, "n");
2784 int outerDepth = parser.getDepth();
2785 int type;
2786 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2787 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2788 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2789 continue;
2790 }
2791
2792 String tagName = parser.getName();
2793 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00002794 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002795 } else {
2796 Slog.w(TAG, "Unknown element under <pkg>: "
2797 + parser.getName());
2798 XmlUtils.skipCurrentTag(parser);
2799 }
2800 }
2801 }
2802
Svet Ganovaf189e32019-02-15 18:45:29 -08002803 private void readUid(XmlPullParser parser, String pkgName)
2804 throws NumberFormatException, XmlPullParserException, IOException {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002805 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Svet Ganovaf189e32019-02-15 18:45:29 -08002806 final UidState uidState = getUidStateLocked(uid, true);
Jason Monk1c7c3192014-06-26 12:52:18 -04002807 String isPrivilegedString = parser.getAttributeValue(null, "p");
2808 boolean isPrivileged = false;
2809 if (isPrivilegedString == null) {
2810 try {
2811 IPackageManager packageManager = ActivityThread.getPackageManager();
2812 if (packageManager != null) {
2813 ApplicationInfo appInfo = ActivityThread.getPackageManager()
2814 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
2815 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002816 isPrivileged = (appInfo.privateFlags
2817 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04002818 }
2819 } else {
2820 // Could not load data, don't add to cache so it will be loaded later.
2821 return;
2822 }
2823 } catch (RemoteException e) {
2824 Slog.w(TAG, "Could not contact PackageManager", e);
2825 }
2826 } else {
2827 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
2828 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002829 int outerDepth = parser.getDepth();
2830 int type;
2831 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2832 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2833 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2834 continue;
2835 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002836 String tagName = parser.getName();
2837 if (tagName.equals("op")) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002838 readOp(parser, uidState, pkgName, isPrivileged);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002839 } else {
2840 Slog.w(TAG, "Unknown element under <pkg>: "
2841 + parser.getName());
2842 XmlUtils.skipCurrentTag(parser);
2843 }
2844 }
Svet Ganovaf189e32019-02-15 18:45:29 -08002845 uidState.evalForegroundOps(mOpModeWatchers);
2846 }
2847
2848 private void readOp(XmlPullParser parser, @NonNull UidState uidState,
2849 @NonNull String pkgName, boolean isPrivileged) throws NumberFormatException,
2850 XmlPullParserException, IOException {
2851 Op op = new Op(uidState, pkgName,
2852 Integer.parseInt(parser.getAttributeValue(null, "n")));
2853
2854 final int mode = XmlUtils.readIntAttribute(parser, "m",
2855 AppOpsManager.opToDefaultMode(op.op));
2856 op.mode = mode;
2857
2858 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 }
2865 String tagName = parser.getName();
2866 if (tagName.equals("st")) {
2867 final long key = XmlUtils.readLongAttribute(parser, "n");
2868
2869 final int flags = AppOpsManager.extractFlagsFromKey(key);
2870 final int state = AppOpsManager.extractUidStateFromKey(key);
2871
2872 final long accessTime = XmlUtils.readLongAttribute(parser, "t", 0);
2873 final long rejectTime = XmlUtils.readLongAttribute(parser, "r", 0);
2874 final long accessDuration = XmlUtils.readLongAttribute(parser, "d", 0);
2875 final String proxyPkg = XmlUtils.readStringAttribute(parser, "pp");
2876 final int proxyUid = XmlUtils.readIntAttribute(parser, "pu", 0);
2877
2878 if (accessTime > 0) {
2879 op.accessed(accessTime, proxyUid, proxyPkg, state, flags);
2880 }
2881 if (rejectTime > 0) {
2882 op.rejected(rejectTime, proxyUid, proxyPkg, state, flags);
2883 }
2884 if (accessDuration > 0) {
2885 op.running(accessTime, accessDuration, state, flags);
2886 }
2887 } else {
2888 Slog.w(TAG, "Unknown element under <op>: "
2889 + parser.getName());
2890 XmlUtils.skipCurrentTag(parser);
2891 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002892 }
Svet Ganovaf189e32019-02-15 18:45:29 -08002893
2894 if (uidState.pkgOps == null) {
2895 uidState.pkgOps = new ArrayMap<>();
2896 }
2897 Ops ops = uidState.pkgOps.get(pkgName);
2898 if (ops == null) {
2899 ops = new Ops(pkgName, uidState, isPrivileged);
2900 uidState.pkgOps.put(pkgName, ops);
2901 }
2902 ops.put(op.op, op);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002903 }
2904
2905 void writeState() {
2906 synchronized (mFile) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002907 FileOutputStream stream;
2908 try {
2909 stream = mFile.startWrite();
2910 } catch (IOException e) {
2911 Slog.w(TAG, "Failed to write state: " + e);
2912 return;
2913 }
2914
Dianne Hackborne17b4452018-01-10 13:15:40 -08002915 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
2916
Dianne Hackborn35654b62013-01-14 17:38:02 -08002917 try {
2918 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002919 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08002920 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002921 out.startTag(null, "app-ops");
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002922 out.attribute(null, "v", String.valueOf(CURRENT_VERSION));
Svet Ganov2af57082015-07-30 08:44:20 -07002923
2924 final int uidStateCount = mUidStates.size();
2925 for (int i = 0; i < uidStateCount; i++) {
2926 UidState uidState = mUidStates.valueAt(i);
2927 if (uidState.opModes != null && uidState.opModes.size() > 0) {
2928 out.startTag(null, "uid");
2929 out.attribute(null, "n", Integer.toString(uidState.uid));
2930 SparseIntArray uidOpModes = uidState.opModes;
2931 final int opCount = uidOpModes.size();
2932 for (int j = 0; j < opCount; j++) {
2933 final int op = uidOpModes.keyAt(j);
2934 final int mode = uidOpModes.valueAt(j);
2935 out.startTag(null, "op");
2936 out.attribute(null, "n", Integer.toString(op));
2937 out.attribute(null, "m", Integer.toString(mode));
2938 out.endTag(null, "op");
2939 }
2940 out.endTag(null, "uid");
2941 }
2942 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002943
2944 if (allOps != null) {
2945 String lastPkg = null;
2946 for (int i=0; i<allOps.size(); i++) {
2947 AppOpsManager.PackageOps pkg = allOps.get(i);
2948 if (!pkg.getPackageName().equals(lastPkg)) {
2949 if (lastPkg != null) {
2950 out.endTag(null, "pkg");
2951 }
2952 lastPkg = pkg.getPackageName();
2953 out.startTag(null, "pkg");
2954 out.attribute(null, "n", lastPkg);
2955 }
2956 out.startTag(null, "uid");
2957 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04002958 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07002959 Ops ops = getOpsRawLocked(pkg.getUid(), pkg.getPackageName(),
2960 false /* edit */, false /* uidMismatchExpected */);
Jason Monk1c7c3192014-06-26 12:52:18 -04002961 // Should always be present as the list of PackageOps is generated
2962 // from Ops.
2963 if (ops != null) {
2964 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
2965 } else {
2966 out.attribute(null, "p", Boolean.toString(false));
2967 }
2968 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002969 List<AppOpsManager.OpEntry> ops = pkg.getOps();
2970 for (int j=0; j<ops.size(); j++) {
2971 AppOpsManager.OpEntry op = ops.get(j);
2972 out.startTag(null, "op");
2973 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07002974 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002975 out.attribute(null, "m", Integer.toString(op.getMode()));
2976 }
Svet Ganovaf189e32019-02-15 18:45:29 -08002977
2978 final LongSparseArray keys = op.collectKeys();
2979 if (keys == null || keys.size() <= 0) {
2980 continue;
2981 }
2982
2983 final int keyCount = keys.size();
2984 for (int k = 0; k < keyCount; k++) {
2985 final long key = keys.keyAt(k);
2986
2987 final int uidState = AppOpsManager.extractUidStateFromKey(key);
2988 final int flags = AppOpsManager.extractFlagsFromKey(key);
2989
2990 final long accessTime = op.getLastAccessTime(
2991 uidState, uidState, flags);
2992 final long rejectTime = op.getLastRejectTime(
2993 uidState, uidState, flags);
2994 final long accessDuration = op.getLastDuration(
2995 uidState, uidState, flags);
2996 final String proxyPkg = op.getProxyPackageName(uidState, flags);
2997 final int proxyUid = op.getProxyUid(uidState, flags);
2998
2999 if (accessTime <= 0 && rejectTime <= 0 && accessDuration <= 0
3000 && proxyPkg == null && proxyUid < 0) {
3001 continue;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003002 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003003
3004 out.startTag(null, "st");
3005 out.attribute(null, "n", Long.toString(key));
3006 if (accessTime > 0) {
3007 out.attribute(null, "t", Long.toString(accessTime));
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003008 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003009 if (rejectTime > 0) {
3010 out.attribute(null, "r", Long.toString(rejectTime));
3011 }
3012 if (accessDuration > 0) {
3013 out.attribute(null, "d", Long.toString(accessDuration));
3014 }
3015 if (proxyPkg != null) {
3016 out.attribute(null, "pp", proxyPkg);
3017 }
3018 if (proxyUid >= 0) {
3019 out.attribute(null, "pu", Integer.toString(proxyUid));
3020 }
3021 out.endTag(null, "st");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003022 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003023
Dianne Hackborn35654b62013-01-14 17:38:02 -08003024 out.endTag(null, "op");
3025 }
3026 out.endTag(null, "uid");
3027 }
3028 if (lastPkg != null) {
3029 out.endTag(null, "pkg");
3030 }
3031 }
3032
3033 out.endTag(null, "app-ops");
3034 out.endDocument();
3035 mFile.finishWrite(stream);
3036 } catch (IOException e) {
3037 Slog.w(TAG, "Failed to write state, restoring backup.", e);
3038 mFile.failWrite(stream);
3039 }
3040 }
3041 }
3042
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003043 static class Shell extends ShellCommand {
3044 final IAppOpsService mInterface;
3045 final AppOpsService mInternal;
3046
3047 int userId = UserHandle.USER_SYSTEM;
3048 String packageName;
3049 String opStr;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003050 String modeStr;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003051 int op;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003052 int mode;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003053 int packageUid;
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003054 int nonpackageUid;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003055 final static Binder sBinder = new Binder();
3056 IBinder mToken;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003057
3058 Shell(IAppOpsService iface, AppOpsService internal) {
3059 mInterface = iface;
3060 mInternal = internal;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003061 try {
3062 mToken = mInterface.getToken(sBinder);
3063 } catch (RemoteException e) {
3064 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003065 }
3066
3067 @Override
3068 public int onCommand(String cmd) {
3069 return onShellCommand(this, cmd);
3070 }
3071
3072 @Override
3073 public void onHelp() {
3074 PrintWriter pw = getOutPrintWriter();
3075 dumpCommandHelp(pw);
3076 }
3077
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003078 static private int strOpToOp(String op, PrintWriter err) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003079 try {
3080 return AppOpsManager.strOpToOp(op);
3081 } catch (IllegalArgumentException e) {
3082 }
3083 try {
3084 return Integer.parseInt(op);
3085 } catch (NumberFormatException e) {
3086 }
3087 try {
3088 return AppOpsManager.strDebugOpToOp(op);
3089 } catch (IllegalArgumentException e) {
3090 err.println("Error: " + e.getMessage());
3091 return -1;
3092 }
3093 }
3094
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003095 static int strModeToMode(String modeStr, PrintWriter err) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003096 for (int i = AppOpsManager.MODE_NAMES.length - 1; i >= 0; i--) {
3097 if (AppOpsManager.MODE_NAMES[i].equals(modeStr)) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003098 return i;
3099 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003100 }
3101 try {
3102 return Integer.parseInt(modeStr);
3103 } catch (NumberFormatException e) {
3104 }
3105 err.println("Error: Mode " + modeStr + " is not valid");
3106 return -1;
3107 }
3108
3109 int parseUserOpMode(int defMode, PrintWriter err) throws RemoteException {
3110 userId = UserHandle.USER_CURRENT;
3111 opStr = null;
3112 modeStr = null;
3113 for (String argument; (argument = getNextArg()) != null;) {
3114 if ("--user".equals(argument)) {
3115 userId = UserHandle.parseUserArg(getNextArgRequired());
3116 } else {
3117 if (opStr == null) {
3118 opStr = argument;
3119 } else if (modeStr == null) {
3120 modeStr = argument;
3121 break;
3122 }
3123 }
3124 }
3125 if (opStr == null) {
3126 err.println("Error: Operation not specified.");
3127 return -1;
3128 }
3129 op = strOpToOp(opStr, err);
3130 if (op < 0) {
3131 return -1;
3132 }
3133 if (modeStr != null) {
3134 if ((mode=strModeToMode(modeStr, err)) < 0) {
3135 return -1;
3136 }
3137 } else {
3138 mode = defMode;
3139 }
3140 return 0;
3141 }
3142
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003143 int parseUserPackageOp(boolean reqOp, PrintWriter err) throws RemoteException {
3144 userId = UserHandle.USER_CURRENT;
3145 packageName = null;
3146 opStr = null;
3147 for (String argument; (argument = getNextArg()) != null;) {
3148 if ("--user".equals(argument)) {
3149 userId = UserHandle.parseUserArg(getNextArgRequired());
3150 } else {
3151 if (packageName == null) {
3152 packageName = argument;
3153 } else if (opStr == null) {
3154 opStr = argument;
3155 break;
3156 }
3157 }
3158 }
3159 if (packageName == null) {
3160 err.println("Error: Package name not specified.");
3161 return -1;
3162 } else if (opStr == null && reqOp) {
3163 err.println("Error: Operation not specified.");
3164 return -1;
3165 }
3166 if (opStr != null) {
3167 op = strOpToOp(opStr, err);
3168 if (op < 0) {
3169 return -1;
3170 }
3171 } else {
3172 op = AppOpsManager.OP_NONE;
3173 }
3174 if (userId == UserHandle.USER_CURRENT) {
3175 userId = ActivityManager.getCurrentUser();
3176 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003177 nonpackageUid = -1;
3178 try {
3179 nonpackageUid = Integer.parseInt(packageName);
3180 } catch (NumberFormatException e) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003181 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003182 if (nonpackageUid == -1 && packageName.length() > 1 && packageName.charAt(0) == 'u'
3183 && packageName.indexOf('.') < 0) {
3184 int i = 1;
3185 while (i < packageName.length() && packageName.charAt(i) >= '0'
3186 && packageName.charAt(i) <= '9') {
3187 i++;
3188 }
3189 if (i > 1 && i < packageName.length()) {
3190 String userStr = packageName.substring(1, i);
3191 try {
3192 int user = Integer.parseInt(userStr);
3193 char type = packageName.charAt(i);
3194 i++;
3195 int startTypeVal = i;
3196 while (i < packageName.length() && packageName.charAt(i) >= '0'
3197 && packageName.charAt(i) <= '9') {
3198 i++;
3199 }
3200 if (i > startTypeVal) {
3201 String typeValStr = packageName.substring(startTypeVal, i);
3202 try {
3203 int typeVal = Integer.parseInt(typeValStr);
3204 if (type == 'a') {
3205 nonpackageUid = UserHandle.getUid(user,
3206 typeVal + Process.FIRST_APPLICATION_UID);
3207 } else if (type == 's') {
3208 nonpackageUid = UserHandle.getUid(user, typeVal);
3209 }
3210 } catch (NumberFormatException e) {
3211 }
3212 }
3213 } catch (NumberFormatException e) {
3214 }
3215 }
3216 }
3217 if (nonpackageUid != -1) {
3218 packageName = null;
3219 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08003220 packageUid = resolveUid(packageName);
3221 if (packageUid < 0) {
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003222 packageUid = AppGlobals.getPackageManager().getPackageUid(packageName,
3223 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
3224 }
3225 if (packageUid < 0) {
3226 err.println("Error: No UID for " + packageName + " in user " + userId);
3227 return -1;
3228 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003229 }
3230 return 0;
3231 }
3232 }
3233
3234 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003235 FileDescriptor err, String[] args, ShellCallback callback,
3236 ResultReceiver resultReceiver) {
3237 (new Shell(this, this)).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003238 }
3239
3240 static void dumpCommandHelp(PrintWriter pw) {
3241 pw.println("AppOps service (appops) commands:");
3242 pw.println(" help");
3243 pw.println(" Print this help text.");
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003244 pw.println(" start [--user <USER_ID>] <PACKAGE | UID> <OP> ");
3245 pw.println(" Starts a given operation for a particular application.");
3246 pw.println(" stop [--user <USER_ID>] <PACKAGE | UID> <OP> ");
3247 pw.println(" Stops a given operation for a particular application.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003248 pw.println(" set [--user <USER_ID>] <PACKAGE | UID> <OP> <MODE>");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003249 pw.println(" Set the mode for a particular application and operation.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003250 pw.println(" get [--user <USER_ID>] <PACKAGE | UID> [<OP>]");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003251 pw.println(" Return the mode for a particular application and optional operation.");
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003252 pw.println(" query-op [--user <USER_ID>] <OP> [<MODE>]");
3253 pw.println(" Print all packages that currently have the given op in the given mode.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003254 pw.println(" reset [--user <USER_ID>] [<PACKAGE>]");
3255 pw.println(" Reset the given application or all applications to default modes.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003256 pw.println(" write-settings");
3257 pw.println(" Immediately write pending changes to storage.");
3258 pw.println(" read-settings");
3259 pw.println(" Read the last written settings, replacing current state in RAM.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003260 pw.println(" options:");
3261 pw.println(" <PACKAGE> an Android package name.");
3262 pw.println(" <OP> an AppOps operation.");
3263 pw.println(" <MODE> one of allow, ignore, deny, or default");
3264 pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
3265 pw.println(" specified, the current user is assumed.");
3266 }
3267
3268 static int onShellCommand(Shell shell, String cmd) {
3269 if (cmd == null) {
3270 return shell.handleDefaultCommands(cmd);
3271 }
3272 PrintWriter pw = shell.getOutPrintWriter();
3273 PrintWriter err = shell.getErrPrintWriter();
3274 try {
3275 switch (cmd) {
3276 case "set": {
3277 int res = shell.parseUserPackageOp(true, err);
3278 if (res < 0) {
3279 return res;
3280 }
3281 String modeStr = shell.getNextArg();
3282 if (modeStr == null) {
3283 err.println("Error: Mode not specified.");
3284 return -1;
3285 }
3286
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003287 final int mode = shell.strModeToMode(modeStr, err);
3288 if (mode < 0) {
3289 return -1;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003290 }
3291
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003292 if (shell.packageName != null) {
3293 shell.mInterface.setMode(shell.op, shell.packageUid, shell.packageName,
3294 mode);
3295 } else {
3296 shell.mInterface.setUidMode(shell.op, shell.nonpackageUid, mode);
3297 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003298 return 0;
3299 }
3300 case "get": {
3301 int res = shell.parseUserPackageOp(false, err);
3302 if (res < 0) {
3303 return res;
3304 }
3305
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003306 List<AppOpsManager.PackageOps> ops = new ArrayList<>();
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003307 if (shell.packageName != null) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003308 // Uid mode overrides package mode, so make sure it's also reported
3309 List<AppOpsManager.PackageOps> r = shell.mInterface.getUidOps(
3310 shell.packageUid,
3311 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
3312 if (r != null) {
3313 ops.addAll(r);
3314 }
3315 r = shell.mInterface.getOpsForPackage(
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003316 shell.packageUid, shell.packageName,
3317 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003318 if (r != null) {
3319 ops.addAll(r);
3320 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003321 } else {
3322 ops = shell.mInterface.getUidOps(
3323 shell.nonpackageUid,
3324 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
3325 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003326 if (ops == null || ops.size() <= 0) {
3327 pw.println("No operations.");
Svet Ganov82f09bc2018-01-12 22:08:40 -08003328 if (shell.op > AppOpsManager.OP_NONE && shell.op < AppOpsManager._NUM_OP) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003329 pw.println("Default mode: " + AppOpsManager.modeToName(
Svet Ganov82f09bc2018-01-12 22:08:40 -08003330 AppOpsManager.opToDefaultMode(shell.op)));
3331 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003332 return 0;
3333 }
3334 final long now = System.currentTimeMillis();
3335 for (int i=0; i<ops.size(); i++) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003336 AppOpsManager.PackageOps packageOps = ops.get(i);
3337 if (packageOps.getPackageName() == null) {
3338 pw.print("Uid mode: ");
3339 }
3340 List<AppOpsManager.OpEntry> entries = packageOps.getOps();
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003341 for (int j=0; j<entries.size(); j++) {
3342 AppOpsManager.OpEntry ent = entries.get(j);
3343 pw.print(AppOpsManager.opToName(ent.getOp()));
3344 pw.print(": ");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003345 pw.print(AppOpsManager.modeToName(ent.getMode()));
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003346 if (ent.getTime() != 0) {
3347 pw.print("; time=");
3348 TimeUtils.formatDuration(now - ent.getTime(), pw);
3349 pw.print(" ago");
3350 }
3351 if (ent.getRejectTime() != 0) {
3352 pw.print("; rejectTime=");
3353 TimeUtils.formatDuration(now - ent.getRejectTime(), pw);
3354 pw.print(" ago");
3355 }
3356 if (ent.getDuration() == -1) {
3357 pw.print(" (running)");
3358 } else if (ent.getDuration() != 0) {
3359 pw.print("; duration=");
3360 TimeUtils.formatDuration(ent.getDuration(), pw);
3361 }
3362 pw.println();
3363 }
3364 }
3365 return 0;
3366 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003367 case "query-op": {
3368 int res = shell.parseUserOpMode(AppOpsManager.MODE_IGNORED, err);
3369 if (res < 0) {
3370 return res;
3371 }
3372 List<AppOpsManager.PackageOps> ops = shell.mInterface.getPackagesForOps(
3373 new int[] {shell.op});
3374 if (ops == null || ops.size() <= 0) {
3375 pw.println("No operations.");
3376 return 0;
3377 }
3378 for (int i=0; i<ops.size(); i++) {
3379 final AppOpsManager.PackageOps pkg = ops.get(i);
3380 boolean hasMatch = false;
3381 final List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
3382 for (int j=0; j<entries.size(); j++) {
3383 AppOpsManager.OpEntry ent = entries.get(j);
3384 if (ent.getOp() == shell.op && ent.getMode() == shell.mode) {
3385 hasMatch = true;
3386 break;
3387 }
3388 }
3389 if (hasMatch) {
3390 pw.println(pkg.getPackageName());
3391 }
3392 }
3393 return 0;
3394 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003395 case "reset": {
3396 String packageName = null;
3397 int userId = UserHandle.USER_CURRENT;
3398 for (String argument; (argument = shell.getNextArg()) != null;) {
3399 if ("--user".equals(argument)) {
3400 String userStr = shell.getNextArgRequired();
3401 userId = UserHandle.parseUserArg(userStr);
3402 } else {
3403 if (packageName == null) {
3404 packageName = argument;
3405 } else {
3406 err.println("Error: Unsupported argument: " + argument);
3407 return -1;
3408 }
3409 }
3410 }
3411
3412 if (userId == UserHandle.USER_CURRENT) {
3413 userId = ActivityManager.getCurrentUser();
3414 }
3415
3416 shell.mInterface.resetAllModes(userId, packageName);
3417 pw.print("Reset all modes for: ");
3418 if (userId == UserHandle.USER_ALL) {
3419 pw.print("all users");
3420 } else {
3421 pw.print("user "); pw.print(userId);
3422 }
3423 pw.print(", ");
3424 if (packageName == null) {
3425 pw.println("all packages");
3426 } else {
3427 pw.print("package "); pw.println(packageName);
3428 }
3429 return 0;
3430 }
3431 case "write-settings": {
Dianne Hackbornd5254412018-05-11 18:02:58 -07003432 shell.mInternal.enforceManageAppOpsModes(Binder.getCallingPid(),
3433 Binder.getCallingUid(), -1);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003434 long token = Binder.clearCallingIdentity();
3435 try {
3436 synchronized (shell.mInternal) {
3437 shell.mInternal.mHandler.removeCallbacks(shell.mInternal.mWriteRunner);
3438 }
3439 shell.mInternal.writeState();
3440 pw.println("Current settings written.");
3441 } finally {
3442 Binder.restoreCallingIdentity(token);
3443 }
3444 return 0;
3445 }
3446 case "read-settings": {
Dianne Hackbornd5254412018-05-11 18:02:58 -07003447 shell.mInternal.enforceManageAppOpsModes(Binder.getCallingPid(),
3448 Binder.getCallingUid(), -1);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003449 long token = Binder.clearCallingIdentity();
3450 try {
3451 shell.mInternal.readState();
3452 pw.println("Last settings read.");
3453 } finally {
3454 Binder.restoreCallingIdentity(token);
3455 }
3456 return 0;
3457 }
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003458 case "start": {
3459 int res = shell.parseUserPackageOp(true, err);
3460 if (res < 0) {
3461 return res;
3462 }
3463
3464 if (shell.packageName != null) {
3465 shell.mInterface.startOperation(shell.mToken,
3466 shell.op, shell.packageUid, shell.packageName, true);
3467 } else {
3468 return -1;
3469 }
3470 return 0;
3471 }
3472 case "stop": {
3473 int res = shell.parseUserPackageOp(true, err);
3474 if (res < 0) {
3475 return res;
3476 }
3477
3478 if (shell.packageName != null) {
3479 shell.mInterface.finishOperation(shell.mToken,
3480 shell.op, shell.packageUid, shell.packageName);
3481 } else {
3482 return -1;
3483 }
3484 return 0;
3485 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003486 default:
3487 return shell.handleDefaultCommands(cmd);
3488 }
3489 } catch (RemoteException e) {
3490 pw.println("Remote exception: " + e);
3491 }
3492 return -1;
3493 }
3494
3495 private void dumpHelp(PrintWriter pw) {
3496 pw.println("AppOps service (appops) dump options:");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003497 pw.println(" -h");
3498 pw.println(" Print this help text.");
3499 pw.println(" --op [OP]");
3500 pw.println(" Limit output to data associated with the given app op code.");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003501 pw.println(" --mode [MODE]");
3502 pw.println(" Limit output to data associated with the given app op mode.");
3503 pw.println(" --package [PACKAGE]");
3504 pw.println(" Limit output to data associated with the given package name.");
Dianne Hackborn125dc532019-01-09 13:31:48 -08003505 pw.println(" --watchers");
3506 pw.println(" Only output the watcher sections.");
Svet Ganovaf189e32019-02-15 18:45:29 -08003507 pw.println(" --history");
3508 pw.println(" Output the historical data.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003509 }
3510
Svet Ganovaf189e32019-02-15 18:45:29 -08003511 private void dumpStatesLocked(@NonNull PrintWriter pw, @NonNull Op op,
3512 long now, @NonNull SimpleDateFormat sdf, @NonNull Date date, @NonNull String prefix) {
3513
3514 final OpEntry entry = new OpEntry(op.op, op.running, op.mode, op.mAccessTimes,
3515 op.mRejectTimes, op.mDurations, op.mProxyUids, op.mProxyPackageNames);
3516
3517 final LongSparseArray keys = entry.collectKeys();
3518 if (keys == null || keys.size() <= 0) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003519 return;
3520 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003521
3522 final int keyCount = keys.size();
3523 for (int k = 0; k < keyCount; k++) {
3524 final long key = keys.keyAt(k);
3525
3526 final int uidState = AppOpsManager.extractUidStateFromKey(key);
3527 final int flags = AppOpsManager.extractFlagsFromKey(key);
3528
3529 final long accessTime = entry.getLastAccessTime(
3530 uidState, uidState, flags);
3531 final long rejectTime = entry.getLastRejectTime(
3532 uidState, uidState, flags);
3533 final long accessDuration = entry.getLastDuration(
3534 uidState, uidState, flags);
3535 final String proxyPkg = entry.getProxyPackageName(uidState, flags);
3536 final int proxyUid = entry.getProxyUid(uidState, flags);
3537
3538 if (accessTime > 0) {
3539 pw.print(prefix);
3540 pw.print("Access: ");
3541 pw.print(AppOpsManager.keyToString(key));
3542 pw.print(" ");
3543 date.setTime(accessTime);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003544 pw.print(sdf.format(date));
3545 pw.print(" (");
Svet Ganovaf189e32019-02-15 18:45:29 -08003546 TimeUtils.formatDuration(accessTime - now, pw);
3547 pw.print(")");
3548 if (accessDuration > 0) {
3549 pw.print(" duration=");
3550 TimeUtils.formatDuration(accessDuration, pw);
3551 }
3552 if (proxyUid >= 0) {
3553 pw.print(" proxy[");
3554 pw.print("uid=");
3555 pw.print(proxyUid);
3556 pw.print(", pkg=");
3557 pw.print(proxyPkg);
3558 pw.print("]");
3559 }
3560 pw.println();
3561 }
3562
3563 if (rejectTime > 0) {
3564 pw.print(prefix);
3565 pw.print("Reject: ");
3566 pw.print(AppOpsManager.keyToString(key));
3567 date.setTime(rejectTime);
3568 pw.print(sdf.format(date));
3569 pw.print(" (");
3570 TimeUtils.formatDuration(rejectTime - now, pw);
3571 pw.print(")");
3572 if (proxyUid >= 0) {
3573 pw.print(" proxy[");
3574 pw.print("uid=");
3575 pw.print(proxyUid);
3576 pw.print(", pkg=");
3577 pw.print(proxyPkg);
3578 pw.print("]");
3579 }
3580 pw.println();
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003581 }
3582 }
3583 }
3584
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003585 @Override
3586 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06003587 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003588
Svet Ganov8455ba22019-01-02 13:05:56 -08003589 int dumpOp = OP_NONE;
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003590 String dumpPackage = null;
Svet Ganov8455ba22019-01-02 13:05:56 -08003591 int dumpUid = Process.INVALID_UID;
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003592 int dumpMode = -1;
Dianne Hackborn125dc532019-01-09 13:31:48 -08003593 boolean dumpWatchers = false;
Svet Ganovaf189e32019-02-15 18:45:29 -08003594 boolean dumpHistory = false;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003595
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003596 if (args != null) {
3597 for (int i=0; i<args.length; i++) {
3598 String arg = args[i];
3599 if ("-h".equals(arg)) {
3600 dumpHelp(pw);
3601 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07003602 } else if ("-a".equals(arg)) {
3603 // dump all data
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003604 } else if ("--op".equals(arg)) {
3605 i++;
3606 if (i >= args.length) {
3607 pw.println("No argument for --op option");
3608 return;
3609 }
3610 dumpOp = Shell.strOpToOp(args[i], pw);
3611 if (dumpOp < 0) {
3612 return;
3613 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003614 } else if ("--package".equals(arg)) {
3615 i++;
3616 if (i >= args.length) {
3617 pw.println("No argument for --package option");
3618 return;
3619 }
3620 dumpPackage = args[i];
3621 try {
3622 dumpUid = AppGlobals.getPackageManager().getPackageUid(dumpPackage,
3623 PackageManager.MATCH_KNOWN_PACKAGES | PackageManager.MATCH_INSTANT,
3624 0);
3625 } catch (RemoteException e) {
3626 }
3627 if (dumpUid < 0) {
3628 pw.println("Unknown package: " + dumpPackage);
3629 return;
3630 }
3631 dumpUid = UserHandle.getAppId(dumpUid);
3632 } else if ("--mode".equals(arg)) {
3633 i++;
3634 if (i >= args.length) {
3635 pw.println("No argument for --mode option");
3636 return;
3637 }
3638 dumpMode = Shell.strModeToMode(args[i], pw);
3639 if (dumpMode < 0) {
3640 return;
3641 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08003642 } else if ("--watchers".equals(arg)) {
3643 dumpWatchers = true;
Svet Ganovaf189e32019-02-15 18:45:29 -08003644 } else if ("--history".equals(arg)) {
3645 dumpHistory = true;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003646 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
3647 pw.println("Unknown option: " + arg);
3648 return;
3649 } else {
3650 pw.println("Unknown command: " + arg);
3651 return;
3652 }
3653 }
3654 }
3655
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003656 synchronized (this) {
3657 pw.println("Current AppOps Service state:");
Svet Ganovaf189e32019-02-15 18:45:29 -08003658 if (!dumpHistory && !dumpWatchers) {
3659 mConstants.dump(pw);
3660 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003661 pw.println();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003662 final long now = System.currentTimeMillis();
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003663 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003664 final long nowUptime = SystemClock.uptimeMillis();
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003665 final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
3666 final Date date = new Date();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003667 boolean needSep = false;
Dianne Hackborn125dc532019-01-09 13:31:48 -08003668 if (dumpOp < 0 && dumpMode < 0 && dumpPackage == null && mProfileOwners != null
Svet Ganovaf189e32019-02-15 18:45:29 -08003669 && !dumpWatchers && !dumpHistory) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07003670 pw.println(" Profile owners:");
3671 for (int poi = 0; poi < mProfileOwners.size(); poi++) {
3672 pw.print(" User #");
3673 pw.print(mProfileOwners.keyAt(poi));
3674 pw.print(": ");
3675 UserHandle.formatUid(pw, mProfileOwners.valueAt(poi));
3676 pw.println();
3677 }
3678 pw.println();
3679 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003680 if (mOpModeWatchers.size() > 0 && !dumpHistory) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003681 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003682 for (int i=0; i<mOpModeWatchers.size(); i++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003683 if (dumpOp >= 0 && dumpOp != mOpModeWatchers.keyAt(i)) {
3684 continue;
3685 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003686 boolean printedOpHeader = false;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003687 ArraySet<ModeCallback> callbacks = mOpModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003688 for (int j=0; j<callbacks.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003689 final ModeCallback cb = callbacks.valueAt(j);
Dianne Hackborn125dc532019-01-09 13:31:48 -08003690 if (dumpPackage != null
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003691 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3692 continue;
3693 }
3694 needSep = true;
3695 if (!printedHeader) {
3696 pw.println(" Op mode watchers:");
3697 printedHeader = true;
3698 }
3699 if (!printedOpHeader) {
3700 pw.print(" Op ");
3701 pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
3702 pw.println(":");
3703 printedOpHeader = true;
3704 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003705 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003706 pw.println(cb);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003707 }
3708 }
3709 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003710 if (mPackageModeWatchers.size() > 0 && dumpOp < 0 && !dumpHistory) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003711 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003712 for (int i=0; i<mPackageModeWatchers.size(); i++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003713 if (dumpPackage != null && !dumpPackage.equals(mPackageModeWatchers.keyAt(i))) {
3714 continue;
3715 }
3716 needSep = true;
3717 if (!printedHeader) {
3718 pw.println(" Package mode watchers:");
3719 printedHeader = true;
3720 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003721 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
3722 pw.println(":");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003723 ArraySet<ModeCallback> callbacks = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003724 for (int j=0; j<callbacks.size(); j++) {
3725 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08003726 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003727 }
3728 }
3729 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003730 if (mModeWatchers.size() > 0 && dumpOp < 0 && !dumpHistory) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003731 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003732 for (int i=0; i<mModeWatchers.size(); i++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003733 final ModeCallback cb = mModeWatchers.valueAt(i);
Dianne Hackborn125dc532019-01-09 13:31:48 -08003734 if (dumpPackage != null
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003735 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3736 continue;
3737 }
3738 needSep = true;
3739 if (!printedHeader) {
3740 pw.println(" All op mode watchers:");
3741 printedHeader = true;
3742 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003743 pw.print(" ");
3744 pw.print(Integer.toHexString(System.identityHashCode(mModeWatchers.keyAt(i))));
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003745 pw.print(": "); pw.println(cb);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003746 }
3747 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003748 if (mActiveWatchers.size() > 0 && dumpMode < 0) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003749 needSep = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003750 boolean printedHeader = false;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003751 for (int i = 0; i < mActiveWatchers.size(); i++) {
3752 final SparseArray<ActiveCallback> activeWatchers = mActiveWatchers.valueAt(i);
3753 if (activeWatchers.size() <= 0) {
3754 continue;
3755 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003756 final ActiveCallback cb = activeWatchers.valueAt(0);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003757 if (dumpOp >= 0 && activeWatchers.indexOfKey(dumpOp) < 0) {
3758 continue;
3759 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08003760 if (dumpPackage != null
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003761 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3762 continue;
3763 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003764 if (!printedHeader) {
3765 pw.println(" All op active watchers:");
3766 printedHeader = true;
3767 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003768 pw.print(" ");
3769 pw.print(Integer.toHexString(System.identityHashCode(
3770 mActiveWatchers.keyAt(i))));
3771 pw.println(" ->");
3772 pw.print(" [");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003773 final int opCount = activeWatchers.size();
3774 for (i = 0; i < opCount; i++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003775 if (i > 0) {
3776 pw.print(' ');
3777 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003778 pw.print(AppOpsManager.opToName(activeWatchers.keyAt(i)));
3779 if (i < opCount - 1) {
3780 pw.print(',');
3781 }
3782 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003783 pw.println("]");
3784 pw.print(" ");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003785 pw.println(cb);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003786 }
3787 }
Svet Ganovb3d2ae22018-12-17 22:06:15 -08003788 if (mNotedWatchers.size() > 0 && dumpMode < 0) {
3789 needSep = true;
3790 boolean printedHeader = false;
3791 for (int i = 0; i < mNotedWatchers.size(); i++) {
3792 final SparseArray<NotedCallback> notedWatchers = mNotedWatchers.valueAt(i);
3793 if (notedWatchers.size() <= 0) {
3794 continue;
3795 }
3796 final NotedCallback cb = notedWatchers.valueAt(0);
3797 if (dumpOp >= 0 && notedWatchers.indexOfKey(dumpOp) < 0) {
3798 continue;
3799 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08003800 if (dumpPackage != null
Svet Ganovb3d2ae22018-12-17 22:06:15 -08003801 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3802 continue;
3803 }
3804 if (!printedHeader) {
3805 pw.println(" All op noted watchers:");
3806 printedHeader = true;
3807 }
3808 pw.print(" ");
3809 pw.print(Integer.toHexString(System.identityHashCode(
3810 mNotedWatchers.keyAt(i))));
3811 pw.println(" ->");
3812 pw.print(" [");
3813 final int opCount = notedWatchers.size();
3814 for (i = 0; i < opCount; i++) {
3815 if (i > 0) {
3816 pw.print(' ');
3817 }
3818 pw.print(AppOpsManager.opToName(notedWatchers.keyAt(i)));
3819 if (i < opCount - 1) {
3820 pw.print(',');
3821 }
3822 }
3823 pw.println("]");
3824 pw.print(" ");
3825 pw.println(cb);
3826 }
3827 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003828 if (mClients.size() > 0 && dumpMode < 0 && !dumpWatchers && !dumpHistory) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003829 needSep = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003830 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003831 for (int i=0; i<mClients.size(); i++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003832 boolean printedClient = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003833 ClientState cs = mClients.valueAt(i);
Svet Ganovf7b47252018-02-26 11:11:27 -08003834 if (cs.mStartedOps.size() > 0) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003835 boolean printedStarted = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003836 for (int j=0; j<cs.mStartedOps.size(); j++) {
3837 Op op = cs.mStartedOps.get(j);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003838 if (dumpOp >= 0 && op.op != dumpOp) {
3839 continue;
3840 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003841 if (dumpPackage != null && !dumpPackage.equals(op.packageName)) {
3842 continue;
3843 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003844 if (!printedHeader) {
3845 pw.println(" Clients:");
3846 printedHeader = true;
3847 }
3848 if (!printedClient) {
3849 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
3850 pw.print(" "); pw.println(cs);
3851 printedClient = true;
3852 }
3853 if (!printedStarted) {
3854 pw.println(" Started ops:");
3855 printedStarted = true;
3856 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003857 pw.print(" "); pw.print("uid="); pw.print(op.uidState.uid);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003858 pw.print(" pkg="); pw.print(op.packageName);
3859 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
3860 }
3861 }
3862 }
3863 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003864 if (mAudioRestrictions.size() > 0 && dumpOp < 0 && dumpPackage != null
Svet Ganovaf189e32019-02-15 18:45:29 -08003865 && dumpMode < 0 && !dumpWatchers && !dumpWatchers) {
John Spurlock1af30c72014-03-10 08:33:35 -04003866 boolean printedHeader = false;
3867 for (int o=0; o<mAudioRestrictions.size(); o++) {
3868 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
3869 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
3870 for (int i=0; i<restrictions.size(); i++) {
3871 if (!printedHeader){
3872 pw.println(" Audio Restrictions:");
3873 printedHeader = true;
3874 needSep = true;
3875 }
John Spurlock7b414672014-07-18 13:02:39 -04003876 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04003877 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04003878 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04003879 Restriction r = restrictions.valueAt(i);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003880 pw.print(": mode="); pw.println(AppOpsManager.modeToName(r.mode));
John Spurlock1af30c72014-03-10 08:33:35 -04003881 if (!r.exceptionPackages.isEmpty()) {
3882 pw.println(" Exceptions:");
3883 for (int j=0; j<r.exceptionPackages.size(); j++) {
3884 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
3885 }
3886 }
3887 }
3888 }
3889 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003890 if (needSep) {
3891 pw.println();
3892 }
Svet Ganov2af57082015-07-30 08:44:20 -07003893 for (int i=0; i<mUidStates.size(); i++) {
3894 UidState uidState = mUidStates.valueAt(i);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003895 final SparseIntArray opModes = uidState.opModes;
3896 final ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
3897
Svet Ganovaf189e32019-02-15 18:45:29 -08003898 if (dumpWatchers || dumpHistory) {
Dianne Hackborn125dc532019-01-09 13:31:48 -08003899 continue;
3900 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003901 if (dumpOp >= 0 || dumpPackage != null || dumpMode >= 0) {
3902 boolean hasOp = dumpOp < 0 || (uidState.opModes != null
3903 && uidState.opModes.indexOfKey(dumpOp) >= 0);
3904 boolean hasPackage = dumpPackage == null;
3905 boolean hasMode = dumpMode < 0;
3906 if (!hasMode && opModes != null) {
3907 for (int opi = 0; !hasMode && opi < opModes.size(); opi++) {
3908 if (opModes.valueAt(opi) == dumpMode) {
3909 hasMode = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003910 }
3911 }
3912 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003913 if (pkgOps != null) {
3914 for (int pkgi = 0;
Svet Ganov8455ba22019-01-02 13:05:56 -08003915 (!hasOp || !hasPackage || !hasMode) && pkgi < pkgOps.size();
3916 pkgi++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003917 Ops ops = pkgOps.valueAt(pkgi);
3918 if (!hasOp && ops != null && ops.indexOfKey(dumpOp) >= 0) {
3919 hasOp = true;
3920 }
3921 if (!hasMode) {
3922 for (int opi = 0; !hasMode && opi < ops.size(); opi++) {
3923 if (ops.valueAt(opi).mode == dumpMode) {
3924 hasMode = true;
3925 }
3926 }
3927 }
3928 if (!hasPackage && dumpPackage.equals(ops.packageName)) {
3929 hasPackage = true;
3930 }
3931 }
3932 }
3933 if (uidState.foregroundOps != null && !hasOp) {
3934 if (uidState.foregroundOps.indexOfKey(dumpOp) > 0) {
3935 hasOp = true;
3936 }
3937 }
3938 if (!hasOp || !hasPackage || !hasMode) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003939 continue;
3940 }
3941 }
Svet Ganov2af57082015-07-30 08:44:20 -07003942
3943 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003944 pw.print(" state=");
Svet Ganovaf189e32019-02-15 18:45:29 -08003945 pw.println(AppOpsManager.getUidStateName(uidState.state));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003946 if (uidState.state != uidState.pendingState) {
3947 pw.print(" pendingState=");
Svet Ganovaf189e32019-02-15 18:45:29 -08003948 pw.println(AppOpsManager.getUidStateName(uidState.pendingState));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003949 }
3950 if (uidState.pendingStateCommitTime != 0) {
3951 pw.print(" pendingStateCommitTime=");
Dianne Hackborn9fb93502018-06-18 12:29:44 -07003952 TimeUtils.formatDuration(uidState.pendingStateCommitTime, nowElapsed, pw);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003953 pw.println();
3954 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003955 if (uidState.startNesting != 0) {
3956 pw.print(" startNesting=");
3957 pw.println(uidState.startNesting);
3958 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003959 if (uidState.foregroundOps != null && (dumpMode < 0
3960 || dumpMode == AppOpsManager.MODE_FOREGROUND)) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003961 pw.println(" foregroundOps:");
3962 for (int j = 0; j < uidState.foregroundOps.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003963 if (dumpOp >= 0 && dumpOp != uidState.foregroundOps.keyAt(j)) {
3964 continue;
3965 }
3966 pw.print(" ");
3967 pw.print(AppOpsManager.opToName(uidState.foregroundOps.keyAt(j)));
3968 pw.print(": ");
3969 pw.println(uidState.foregroundOps.valueAt(j) ? "WATCHER" : "SILENT");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003970 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003971 pw.print(" hasForegroundWatchers=");
3972 pw.println(uidState.hasForegroundWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003973 }
Svet Ganovee438d42017-01-19 18:04:38 -08003974 needSep = true;
Svet Ganov2af57082015-07-30 08:44:20 -07003975
Svet Ganov2af57082015-07-30 08:44:20 -07003976 if (opModes != null) {
3977 final int opModeCount = opModes.size();
3978 for (int j = 0; j < opModeCount; j++) {
3979 final int code = opModes.keyAt(j);
3980 final int mode = opModes.valueAt(j);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003981 if (dumpOp >= 0 && dumpOp != code) {
3982 continue;
3983 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003984 if (dumpMode >= 0 && dumpMode != mode) {
3985 continue;
3986 }
Svet Ganov2af57082015-07-30 08:44:20 -07003987 pw.print(" "); pw.print(AppOpsManager.opToName(code));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003988 pw.print(": mode="); pw.println(AppOpsManager.modeToName(mode));
Svet Ganov2af57082015-07-30 08:44:20 -07003989 }
3990 }
3991
Svet Ganov2af57082015-07-30 08:44:20 -07003992 if (pkgOps == null) {
3993 continue;
3994 }
3995
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003996 for (int pkgi = 0; pkgi < pkgOps.size(); pkgi++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003997 final Ops ops = pkgOps.valueAt(pkgi);
3998 if (dumpPackage != null && !dumpPackage.equals(ops.packageName)) {
3999 continue;
4000 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004001 boolean printedPackage = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004002 for (int j=0; j<ops.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004003 final Op op = ops.valueAt(j);
Svet Ganovaf189e32019-02-15 18:45:29 -08004004 final int opCode = op.op;
4005 if (dumpOp >= 0 && dumpOp != opCode) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004006 continue;
4007 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004008 if (dumpMode >= 0 && dumpMode != op.mode) {
4009 continue;
4010 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004011 if (!printedPackage) {
4012 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
4013 printedPackage = true;
4014 }
Svet Ganovaf189e32019-02-15 18:45:29 -08004015 pw.print(" "); pw.print(AppOpsManager.opToName(opCode));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004016 pw.print(" ("); pw.print(AppOpsManager.modeToName(op.mode));
Svet Ganovaf189e32019-02-15 18:45:29 -08004017 final int switchOp = AppOpsManager.opToSwitch(opCode);
4018 if (switchOp != opCode) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004019 pw.print(" / switch ");
4020 pw.print(AppOpsManager.opToName(switchOp));
4021 final Op switchObj = ops.get(switchOp);
Svet Ganovaf189e32019-02-15 18:45:29 -08004022 int mode = switchObj != null ? switchObj.mode
4023 : AppOpsManager.opToDefaultMode(switchOp);
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004024 pw.print("="); pw.print(AppOpsManager.modeToName(mode));
4025 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004026 pw.println("): ");
Svet Ganovaf189e32019-02-15 18:45:29 -08004027 dumpStatesLocked(pw, op, now, sdf, date, " ");
4028 if (op.running) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07004029 pw.print(" Running start at: ");
4030 TimeUtils.formatDuration(nowElapsed-op.startRealtime, pw);
4031 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004032 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07004033 if (op.startNesting != 0) {
4034 pw.print(" startNesting=");
4035 pw.println(op.startNesting);
4036 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004037 }
4038 }
4039 }
Svet Ganovee438d42017-01-19 18:04:38 -08004040 if (needSep) {
4041 pw.println();
4042 }
4043
4044 final int userRestrictionCount = mOpUserRestrictions.size();
4045 for (int i = 0; i < userRestrictionCount; i++) {
4046 IBinder token = mOpUserRestrictions.keyAt(i);
4047 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
Dianne Hackborn125dc532019-01-09 13:31:48 -08004048 boolean printedTokenHeader = false;
4049
Svet Ganovaf189e32019-02-15 18:45:29 -08004050 if (dumpMode >= 0 || dumpWatchers || dumpHistory) {
Dianne Hackborn125dc532019-01-09 13:31:48 -08004051 continue;
4052 }
Svet Ganovee438d42017-01-19 18:04:38 -08004053
4054 final int restrictionCount = restrictionState.perUserRestrictions != null
4055 ? restrictionState.perUserRestrictions.size() : 0;
Dianne Hackborn125dc532019-01-09 13:31:48 -08004056 if (restrictionCount > 0 && dumpPackage == null) {
4057 boolean printedOpsHeader = false;
Svet Ganovee438d42017-01-19 18:04:38 -08004058 for (int j = 0; j < restrictionCount; j++) {
4059 int userId = restrictionState.perUserRestrictions.keyAt(j);
4060 boolean[] restrictedOps = restrictionState.perUserRestrictions.valueAt(j);
4061 if (restrictedOps == null) {
4062 continue;
4063 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08004064 if (dumpOp >= 0 && (dumpOp >= restrictedOps.length
4065 || !restrictedOps[dumpOp])) {
4066 continue;
4067 }
4068 if (!printedTokenHeader) {
4069 pw.println(" User restrictions for token " + token + ":");
4070 printedTokenHeader = true;
4071 }
4072 if (!printedOpsHeader) {
4073 pw.println(" Restricted ops:");
4074 printedOpsHeader = true;
4075 }
Svet Ganovee438d42017-01-19 18:04:38 -08004076 StringBuilder restrictedOpsValue = new StringBuilder();
4077 restrictedOpsValue.append("[");
4078 final int restrictedOpCount = restrictedOps.length;
4079 for (int k = 0; k < restrictedOpCount; k++) {
4080 if (restrictedOps[k]) {
4081 if (restrictedOpsValue.length() > 1) {
4082 restrictedOpsValue.append(", ");
4083 }
4084 restrictedOpsValue.append(AppOpsManager.opToName(k));
4085 }
4086 }
4087 restrictedOpsValue.append("]");
4088 pw.print(" "); pw.print("user: "); pw.print(userId);
4089 pw.print(" restricted ops: "); pw.println(restrictedOpsValue);
4090 }
4091 }
4092
4093 final int excludedPackageCount = restrictionState.perUserExcludedPackages != null
4094 ? restrictionState.perUserExcludedPackages.size() : 0;
Dianne Hackborn125dc532019-01-09 13:31:48 -08004095 if (excludedPackageCount > 0 && dumpOp < 0) {
4096 boolean printedPackagesHeader = false;
Svet Ganovee438d42017-01-19 18:04:38 -08004097 for (int j = 0; j < excludedPackageCount; j++) {
4098 int userId = restrictionState.perUserExcludedPackages.keyAt(j);
4099 String[] packageNames = restrictionState.perUserExcludedPackages.valueAt(j);
Dianne Hackborn125dc532019-01-09 13:31:48 -08004100 if (packageNames == null) {
4101 continue;
4102 }
4103 boolean hasPackage;
4104 if (dumpPackage != null) {
4105 hasPackage = false;
4106 for (String pkg : packageNames) {
4107 if (dumpPackage.equals(pkg)) {
4108 hasPackage = true;
4109 break;
4110 }
4111 }
4112 } else {
4113 hasPackage = true;
4114 }
4115 if (!hasPackage) {
4116 continue;
4117 }
4118 if (!printedTokenHeader) {
4119 pw.println(" User restrictions for token " + token + ":");
4120 printedTokenHeader = true;
4121 }
4122 if (!printedPackagesHeader) {
4123 pw.println(" Excluded packages:");
4124 printedPackagesHeader = true;
4125 }
Svet Ganovee438d42017-01-19 18:04:38 -08004126 pw.print(" "); pw.print("user: "); pw.print(userId);
4127 pw.print(" packages: "); pw.println(Arrays.toString(packageNames));
4128 }
4129 }
4130 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004131 }
Svet Ganov8455ba22019-01-02 13:05:56 -08004132
4133 // Must not hold the appops lock
Svet Ganovaf189e32019-02-15 18:45:29 -08004134 if (dumpHistory && !dumpWatchers) {
4135 mHistoricalRegistry.dump(" ", pw, dumpUid, dumpPackage, dumpOp);
4136 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004137 }
John Spurlock1af30c72014-03-10 08:33:35 -04004138
4139 private static final class Restriction {
4140 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
4141 int mode;
4142 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
4143 }
Jason Monk62062992014-05-06 09:55:28 -04004144
4145 @Override
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004146 public void setUserRestrictions(Bundle restrictions, IBinder token, int userHandle) {
Jason Monk62062992014-05-06 09:55:28 -04004147 checkSystemUid("setUserRestrictions");
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004148 Preconditions.checkNotNull(restrictions);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004149 Preconditions.checkNotNull(token);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004150 for (int i = 0; i < AppOpsManager._NUM_OP; i++) {
Jason Monk62062992014-05-06 09:55:28 -04004151 String restriction = AppOpsManager.opToRestriction(i);
Suprabh Shukla64e0dcb2016-05-24 16:23:11 -07004152 if (restriction != null) {
4153 setUserRestrictionNoCheck(i, restrictions.getBoolean(restriction, false), token,
4154 userHandle, null);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004155 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004156 }
4157 }
4158
4159 @Override
Ruben Brunk29931bc2016-03-11 00:24:26 -08004160 public void setUserRestriction(int code, boolean restricted, IBinder token, int userHandle,
4161 String[] exceptionPackages) {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004162 if (Binder.getCallingPid() != Process.myPid()) {
4163 mContext.enforcePermission(Manifest.permission.MANAGE_APP_OPS_RESTRICTIONS,
4164 Binder.getCallingPid(), Binder.getCallingUid(), null);
4165 }
4166 if (userHandle != UserHandle.getCallingUserId()) {
4167 if (mContext.checkCallingOrSelfPermission(Manifest.permission
4168 .INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
4169 && mContext.checkCallingOrSelfPermission(Manifest.permission
4170 .INTERACT_ACROSS_USERS) != PackageManager.PERMISSION_GRANTED) {
4171 throw new SecurityException("Need INTERACT_ACROSS_USERS_FULL or"
4172 + " INTERACT_ACROSS_USERS to interact cross user ");
Jason Monk62062992014-05-06 09:55:28 -04004173 }
4174 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004175 verifyIncomingOp(code);
4176 Preconditions.checkNotNull(token);
Ruben Brunk29931bc2016-03-11 00:24:26 -08004177 setUserRestrictionNoCheck(code, restricted, token, userHandle, exceptionPackages);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004178 }
4179
4180 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
Ruben Brunk29931bc2016-03-11 00:24:26 -08004181 int userHandle, String[] exceptionPackages) {
Svet Ganov442ed572016-08-17 17:29:43 -07004182 synchronized (AppOpsService.this) {
4183 ClientRestrictionState restrictionState = mOpUserRestrictions.get(token);
4184
4185 if (restrictionState == null) {
4186 try {
4187 restrictionState = new ClientRestrictionState(token);
4188 } catch (RemoteException e) {
4189 return;
4190 }
4191 mOpUserRestrictions.put(token, restrictionState);
Ruben Brunk29931bc2016-03-11 00:24:26 -08004192 }
Svet Ganov442ed572016-08-17 17:29:43 -07004193
4194 if (restrictionState.setRestriction(code, restricted, exceptionPackages, userHandle)) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004195 mHandler.sendMessage(PooledLambda.obtainMessage(
Svet Ganov3a95f832018-03-23 17:44:30 -07004196 AppOpsService::notifyWatchersOfChange, this, code, UID_ANY));
Svet Ganov442ed572016-08-17 17:29:43 -07004197 }
4198
4199 if (restrictionState.isDefault()) {
4200 mOpUserRestrictions.remove(token);
4201 restrictionState.destroy();
4202 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08004203 }
Julia Reynoldsbb21c252016-04-05 16:01:49 -04004204 }
4205
Svet Ganov3a95f832018-03-23 17:44:30 -07004206 private void notifyWatchersOfChange(int code, int uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004207 final ArraySet<ModeCallback> clonedCallbacks;
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004208 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004209 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004210 if (callbacks == null) {
4211 return;
4212 }
Dianne Hackborn68d76552017-02-27 15:32:03 -08004213 clonedCallbacks = new ArraySet<>(callbacks);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004214 }
4215
Svet Ganov3a95f832018-03-23 17:44:30 -07004216 notifyOpChanged(clonedCallbacks, code, uid, null);
Jason Monk62062992014-05-06 09:55:28 -04004217 }
4218
4219 @Override
4220 public void removeUser(int userHandle) throws RemoteException {
4221 checkSystemUid("removeUser");
Svet Ganov442ed572016-08-17 17:29:43 -07004222 synchronized (AppOpsService.this) {
4223 final int tokenCount = mOpUserRestrictions.size();
4224 for (int i = tokenCount - 1; i >= 0; i--) {
4225 ClientRestrictionState opRestrictions = mOpUserRestrictions.valueAt(i);
4226 opRestrictions.removeUser(userHandle);
4227 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07004228 removeUidsForUserLocked(userHandle);
4229 }
4230 }
4231
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004232 @Override
4233 public boolean isOperationActive(int code, int uid, String packageName) {
Svet Ganovf7b47252018-02-26 11:11:27 -08004234 if (Binder.getCallingUid() != uid) {
4235 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
4236 != PackageManager.PERMISSION_GRANTED) {
4237 return false;
4238 }
4239 }
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004240 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004241 final String resolvedPackageName = resolvePackageName(uid, packageName);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004242 if (resolvedPackageName == null) {
4243 return false;
4244 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004245 synchronized (AppOpsService.this) {
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004246 for (int i = mClients.size() - 1; i >= 0; i--) {
4247 final ClientState client = mClients.valueAt(i);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004248 for (int j = client.mStartedOps.size() - 1; j >= 0; j--) {
4249 final Op op = client.mStartedOps.get(j);
Svet Ganovaf189e32019-02-15 18:45:29 -08004250 if (op.op == code && op.uidState.uid == uid) return true;
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004251 }
4252 }
4253 }
4254 return false;
4255 }
4256
Svet Ganov8455ba22019-01-02 13:05:56 -08004257 @Override
4258 public void setHistoryParameters(@AppOpsManager.HistoricalMode int mode,
4259 long baseSnapshotInterval, int compressionStep) {
4260 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4261 "setHistoryParameters");
4262 // Must not hold the appops lock
4263 mHistoricalRegistry.setHistoryParameters(mode, baseSnapshotInterval, compressionStep);
4264 }
4265
4266 @Override
4267 public void offsetHistory(long offsetMillis) {
4268 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4269 "offsetHistory");
4270 // Must not hold the appops lock
4271 mHistoricalRegistry.offsetHistory(offsetMillis);
4272 }
4273
4274 @Override
4275 public void addHistoricalOps(HistoricalOps ops) {
4276 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4277 "addHistoricalOps");
4278 // Must not hold the appops lock
4279 mHistoricalRegistry.addHistoricalOps(ops);
4280 }
4281
4282 @Override
4283 public void resetHistoryParameters() {
4284 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4285 "resetHistoryParameters");
4286 // Must not hold the appops lock
4287 mHistoricalRegistry.resetHistoryParameters();
4288 }
4289
4290 @Override
4291 public void clearHistory() {
4292 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4293 "clearHistory");
4294 // Must not hold the appops lock
4295 mHistoricalRegistry.clearHistory();
4296 }
4297
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07004298 private void removeUidsForUserLocked(int userHandle) {
4299 for (int i = mUidStates.size() - 1; i >= 0; --i) {
4300 final int uid = mUidStates.keyAt(i);
4301 if (UserHandle.getUserId(uid) == userHandle) {
4302 mUidStates.removeAt(i);
4303 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004304 }
4305 }
4306
Jason Monk62062992014-05-06 09:55:28 -04004307 private void checkSystemUid(String function) {
4308 int uid = Binder.getCallingUid();
4309 if (uid != Process.SYSTEM_UID) {
4310 throw new SecurityException(function + " must by called by the system");
4311 }
4312 }
4313
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004314 private static String resolvePackageName(int uid, String packageName) {
Svet Ganov82f09bc2018-01-12 22:08:40 -08004315 if (uid == Process.ROOT_UID) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004316 return "root";
4317 } else if (uid == Process.SHELL_UID) {
4318 return "com.android.shell";
Svet Ganov82f09bc2018-01-12 22:08:40 -08004319 } else if (uid == Process.MEDIA_UID) {
4320 return "media";
4321 } else if (uid == Process.AUDIOSERVER_UID) {
4322 return "audioserver";
4323 } else if (uid == Process.CAMERASERVER_UID) {
4324 return "cameraserver";
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004325 } else if (uid == Process.SYSTEM_UID && packageName == null) {
4326 return "android";
4327 }
4328 return packageName;
4329 }
4330
Svet Ganov82f09bc2018-01-12 22:08:40 -08004331 private static int resolveUid(String packageName) {
4332 if (packageName == null) {
4333 return -1;
4334 }
4335 switch (packageName) {
4336 case "root":
4337 return Process.ROOT_UID;
4338 case "shell":
4339 return Process.SHELL_UID;
4340 case "media":
4341 return Process.MEDIA_UID;
4342 case "audioserver":
4343 return Process.AUDIOSERVER_UID;
4344 case "cameraserver":
4345 return Process.CAMERASERVER_UID;
4346 }
4347 return -1;
4348 }
4349
Svet Ganov2af57082015-07-30 08:44:20 -07004350 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07004351 String[] packageNames = null;
Philip P. Moltmann159d98b2018-12-20 08:30:53 -08004352
4353 // Very early during boot the package manager is not yet or not yet fully started. At this
4354 // time there are no packages yet.
4355 if (AppGlobals.getPackageManager() != null) {
4356 try {
4357 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
4358 } catch (RemoteException e) {
4359 /* ignore - local call */
4360 }
Svet Ganov2af57082015-07-30 08:44:20 -07004361 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07004362 if (packageNames == null) {
4363 return EmptyArray.STRING;
4364 }
4365 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07004366 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004367
4368 private final class ClientRestrictionState implements DeathRecipient {
4369 private final IBinder token;
4370 SparseArray<boolean[]> perUserRestrictions;
4371 SparseArray<String[]> perUserExcludedPackages;
4372
4373 public ClientRestrictionState(IBinder token)
4374 throws RemoteException {
4375 token.linkToDeath(this, 0);
4376 this.token = token;
4377 }
4378
4379 public boolean setRestriction(int code, boolean restricted,
4380 String[] excludedPackages, int userId) {
4381 boolean changed = false;
4382
4383 if (perUserRestrictions == null && restricted) {
4384 perUserRestrictions = new SparseArray<>();
4385 }
4386
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004387 int[] users;
4388 if (userId == UserHandle.USER_ALL) {
4389 List<UserInfo> liveUsers = UserManager.get(mContext).getUsers(false);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004390
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004391 users = new int[liveUsers.size()];
4392 for (int i = 0; i < liveUsers.size(); i++) {
4393 users[i] = liveUsers.get(i).id;
4394 }
4395 } else {
4396 users = new int[]{userId};
4397 }
4398
4399 if (perUserRestrictions != null) {
4400 int numUsers = users.length;
4401
4402 for (int i = 0; i < numUsers; i++) {
4403 int thisUserId = users[i];
4404
4405 boolean[] userRestrictions = perUserRestrictions.get(thisUserId);
4406 if (userRestrictions == null && restricted) {
4407 userRestrictions = new boolean[AppOpsManager._NUM_OP];
4408 perUserRestrictions.put(thisUserId, userRestrictions);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004409 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004410 if (userRestrictions != null && userRestrictions[code] != restricted) {
4411 userRestrictions[code] = restricted;
4412 if (!restricted && isDefault(userRestrictions)) {
4413 perUserRestrictions.remove(thisUserId);
4414 userRestrictions = null;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004415 }
4416 changed = true;
4417 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004418
4419 if (userRestrictions != null) {
4420 final boolean noExcludedPackages = ArrayUtils.isEmpty(excludedPackages);
4421 if (perUserExcludedPackages == null && !noExcludedPackages) {
4422 perUserExcludedPackages = new SparseArray<>();
4423 }
4424 if (perUserExcludedPackages != null && !Arrays.equals(excludedPackages,
4425 perUserExcludedPackages.get(thisUserId))) {
4426 if (noExcludedPackages) {
4427 perUserExcludedPackages.remove(thisUserId);
4428 if (perUserExcludedPackages.size() <= 0) {
4429 perUserExcludedPackages = null;
4430 }
4431 } else {
4432 perUserExcludedPackages.put(thisUserId, excludedPackages);
4433 }
4434 changed = true;
4435 }
4436 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004437 }
4438 }
4439
4440 return changed;
4441 }
4442
4443 public boolean hasRestriction(int restriction, String packageName, int userId) {
4444 if (perUserRestrictions == null) {
4445 return false;
4446 }
4447 boolean[] restrictions = perUserRestrictions.get(userId);
4448 if (restrictions == null) {
4449 return false;
4450 }
4451 if (!restrictions[restriction]) {
4452 return false;
4453 }
4454 if (perUserExcludedPackages == null) {
4455 return true;
4456 }
4457 String[] perUserExclusions = perUserExcludedPackages.get(userId);
4458 if (perUserExclusions == null) {
4459 return true;
4460 }
4461 return !ArrayUtils.contains(perUserExclusions, packageName);
4462 }
4463
4464 public void removeUser(int userId) {
4465 if (perUserExcludedPackages != null) {
4466 perUserExcludedPackages.remove(userId);
4467 if (perUserExcludedPackages.size() <= 0) {
4468 perUserExcludedPackages = null;
4469 }
4470 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07004471 if (perUserRestrictions != null) {
4472 perUserRestrictions.remove(userId);
4473 if (perUserRestrictions.size() <= 0) {
4474 perUserRestrictions = null;
4475 }
4476 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004477 }
4478
4479 public boolean isDefault() {
4480 return perUserRestrictions == null || perUserRestrictions.size() <= 0;
4481 }
4482
4483 @Override
4484 public void binderDied() {
4485 synchronized (AppOpsService.this) {
4486 mOpUserRestrictions.remove(token);
4487 if (perUserRestrictions == null) {
4488 return;
4489 }
4490 final int userCount = perUserRestrictions.size();
4491 for (int i = 0; i < userCount; i++) {
4492 final boolean[] restrictions = perUserRestrictions.valueAt(i);
4493 final int restrictionCount = restrictions.length;
4494 for (int j = 0; j < restrictionCount; j++) {
4495 if (restrictions[j]) {
4496 final int changedCode = j;
Svet Ganov3a95f832018-03-23 17:44:30 -07004497 mHandler.post(() -> notifyWatchersOfChange(changedCode, UID_ANY));
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004498 }
4499 }
4500 }
4501 destroy();
4502 }
4503 }
4504
4505 public void destroy() {
4506 token.unlinkToDeath(this, 0);
4507 }
4508
4509 private boolean isDefault(boolean[] array) {
4510 if (ArrayUtils.isEmpty(array)) {
4511 return true;
4512 }
4513 for (boolean value : array) {
4514 if (value) {
4515 return false;
4516 }
4517 }
4518 return true;
4519 }
4520 }
Dianne Hackbornd5254412018-05-11 18:02:58 -07004521
4522 private final class AppOpsManagerInternalImpl extends AppOpsManagerInternal {
4523 @Override public void setDeviceAndProfileOwners(SparseIntArray owners) {
4524 synchronized (AppOpsService.this) {
4525 mProfileOwners = owners;
4526 }
4527 }
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07004528
4529 @Override
Philip P. Moltmann159d98b2018-12-20 08:30:53 -08004530 public void setUidMode(int code, int uid, int mode) {
4531 AppOpsService.this.setUidMode(code, uid, mode);
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07004532 }
Philip P. Moltmanndde07852019-01-25 16:42:36 -08004533
4534 @Override
4535 public void setAllPkgModesToDefault(int code, int uid) {
4536 AppOpsService.this.setAllPkgModesToDefault(code, uid);
4537 }
Dianne Hackbornd5254412018-05-11 18:02:58 -07004538 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004539}