blob: a35d2ee38641e3274b7b276729830b1ad2ca8b35 [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
Amith Yamasanif235d0b2019-03-20 22:49:43 -0700156 UID_STATE_FOREGROUND, // ActivityManager.PROCESS_STATE_BOUND_TOP
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700157 UID_STATE_FOREGROUND_SERVICE, // ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
158 UID_STATE_FOREGROUND, // ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
159 UID_STATE_FOREGROUND, // ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND
160 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND
161 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_TRANSIENT_BACKGROUND
162 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_BACKUP
163 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_SERVICE
164 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_RECEIVER
165 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_TOP_SLEEPING
166 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_HEAVY_WEIGHT
167 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_HOME
168 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_LAST_ACTIVITY
169 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY
170 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT
171 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_RECENT
172 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_EMPTY
173 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_NONEXISTENT
174 };
175
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800176 Context mContext;
177 final AtomicFile mFile;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800178 final Handler mHandler;
179
Dianne Hackbornd5254412018-05-11 18:02:58 -0700180 private final AppOpsManagerInternalImpl mAppOpsManagerInternal
181 = new AppOpsManagerInternalImpl();
182
Dianne Hackborn35654b62013-01-14 17:38:02 -0800183 boolean mWriteScheduled;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800184 boolean mFastWriteScheduled;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800185 final Runnable mWriteRunner = new Runnable() {
186 public void run() {
187 synchronized (AppOpsService.this) {
188 mWriteScheduled = false;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800189 mFastWriteScheduled = false;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800190 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
191 @Override protected Void doInBackground(Void... params) {
192 writeState();
193 return null;
194 }
195 };
196 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
197 }
198 }
199 };
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800200
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700201 @VisibleForTesting
202 final SparseArray<UidState> mUidStates = new SparseArray<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800203
Svet Ganovdc0f4432019-06-04 14:16:51 -0700204 final HistoricalRegistry mHistoricalRegistry = new HistoricalRegistry(this);
Svet Ganov8455ba22019-01-02 13:05:56 -0800205
Dianne Hackborn9fb93502018-06-18 12:29:44 -0700206 long mLastRealtime;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700207
Ruben Brunk29931bc2016-03-11 00:24:26 -0800208 /*
209 * These are app op restrictions imposed per user from various parties.
Ruben Brunk29931bc2016-03-11 00:24:26 -0800210 */
Svetoslav Ganova8bbd762016-05-13 17:08:16 -0700211 private final ArrayMap<IBinder, ClientRestrictionState> mOpUserRestrictions = new ArrayMap<>();
Jason Monk62062992014-05-06 09:55:28 -0400212
Dianne Hackbornd5254412018-05-11 18:02:58 -0700213 SparseIntArray mProfileOwners;
214
Todd Kennedy556efba2018-11-15 07:43:55 -0800215 @GuardedBy("this")
Svet Ganovd873ae62018-06-25 16:39:23 -0700216 private CheckOpsDelegate mCheckOpsDelegate;
217
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700218 /**
219 * All times are in milliseconds. These constants are kept synchronized with the system
220 * global Settings. Any access to this class or its fields should be done while
221 * holding the AppOpsService lock.
222 */
Amith Yamasani23d4cd72019-04-10 17:57:00 -0700223 @VisibleForTesting
224 final class Constants extends ContentObserver {
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700225 // Key names stored in the settings value.
Dianne Hackborne93ab412018-05-14 17:52:30 -0700226 private static final String KEY_TOP_STATE_SETTLE_TIME = "top_state_settle_time";
227 private static final String KEY_FG_SERVICE_STATE_SETTLE_TIME
228 = "fg_service_state_settle_time";
229 private static final String KEY_BG_STATE_SETTLE_TIME = "bg_state_settle_time";
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700230
231 /**
Dianne Hackborne93ab412018-05-14 17:52:30 -0700232 * How long we want for a drop in uid state from top to settle before applying it.
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700233 * @see Settings.Global#APP_OPS_CONSTANTS
Dianne Hackborne93ab412018-05-14 17:52:30 -0700234 * @see #KEY_TOP_STATE_SETTLE_TIME
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700235 */
Dianne Hackborne93ab412018-05-14 17:52:30 -0700236 public long TOP_STATE_SETTLE_TIME;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700237
Dianne Hackborne93ab412018-05-14 17:52:30 -0700238 /**
239 * How long we want for a drop in uid state from foreground to settle before applying it.
240 * @see Settings.Global#APP_OPS_CONSTANTS
241 * @see #KEY_FG_SERVICE_STATE_SETTLE_TIME
242 */
243 public long FG_SERVICE_STATE_SETTLE_TIME;
244
245 /**
246 * How long we want for a drop in uid state from background to settle before applying it.
247 * @see Settings.Global#APP_OPS_CONSTANTS
248 * @see #KEY_BG_STATE_SETTLE_TIME
249 */
250 public long BG_STATE_SETTLE_TIME;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700251
252 private final KeyValueListParser mParser = new KeyValueListParser(',');
253 private ContentResolver mResolver;
254
255 public Constants(Handler handler) {
256 super(handler);
257 updateConstants();
258 }
259
260 public void startMonitoring(ContentResolver resolver) {
261 mResolver = resolver;
262 mResolver.registerContentObserver(
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700263 Settings.Global.getUriFor(Settings.Global.APP_OPS_CONSTANTS),
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700264 false, this);
265 updateConstants();
266 }
267
268 @Override
269 public void onChange(boolean selfChange, Uri uri) {
270 updateConstants();
271 }
272
273 private void updateConstants() {
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700274 String value = mResolver != null ? Settings.Global.getString(mResolver,
275 Settings.Global.APP_OPS_CONSTANTS) : "";
276
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700277 synchronized (AppOpsService.this) {
278 try {
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700279 mParser.setString(value);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700280 } catch (IllegalArgumentException e) {
281 // Failed to parse the settings string, log this and move on
282 // with defaults.
283 Slog.e(TAG, "Bad app ops settings", e);
284 }
Dianne Hackborne93ab412018-05-14 17:52:30 -0700285 TOP_STATE_SETTLE_TIME = mParser.getDurationMillis(
286 KEY_TOP_STATE_SETTLE_TIME, 30 * 1000L);
287 FG_SERVICE_STATE_SETTLE_TIME = mParser.getDurationMillis(
288 KEY_FG_SERVICE_STATE_SETTLE_TIME, 10 * 1000L);
289 BG_STATE_SETTLE_TIME = mParser.getDurationMillis(
290 KEY_BG_STATE_SETTLE_TIME, 1 * 1000L);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700291 }
292 }
293
294 void dump(PrintWriter pw) {
295 pw.println(" Settings:");
296
Dianne Hackborne93ab412018-05-14 17:52:30 -0700297 pw.print(" "); pw.print(KEY_TOP_STATE_SETTLE_TIME); pw.print("=");
298 TimeUtils.formatDuration(TOP_STATE_SETTLE_TIME, pw);
Dianne Hackbornb94d82f2018-05-16 17:03:01 -0700299 pw.println();
Dianne Hackborne93ab412018-05-14 17:52:30 -0700300 pw.print(" "); pw.print(KEY_FG_SERVICE_STATE_SETTLE_TIME); pw.print("=");
301 TimeUtils.formatDuration(FG_SERVICE_STATE_SETTLE_TIME, pw);
Dianne Hackbornb94d82f2018-05-16 17:03:01 -0700302 pw.println();
Dianne Hackborne93ab412018-05-14 17:52:30 -0700303 pw.print(" "); pw.print(KEY_BG_STATE_SETTLE_TIME); pw.print("=");
304 TimeUtils.formatDuration(BG_STATE_SETTLE_TIME, pw);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700305 pw.println();
306 }
307 }
308
Amith Yamasani23d4cd72019-04-10 17:57:00 -0700309 @VisibleForTesting
310 final Constants mConstants;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700311
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700312 @VisibleForTesting
313 static final class UidState {
Svet Ganov2af57082015-07-30 08:44:20 -0700314 public final int uid;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700315
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700316 public int state = UID_STATE_CACHED;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700317 public int pendingState = UID_STATE_CACHED;
318 public long pendingStateCommitTime;
319
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700320 public int startNesting;
Svet Ganov2af57082015-07-30 08:44:20 -0700321 public ArrayMap<String, Ops> pkgOps;
322 public SparseIntArray opModes;
323
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700324 // true indicates there is an interested observer, false there isn't but it has such an op
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700325 public SparseBooleanArray foregroundOps;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700326 public boolean hasForegroundWatchers;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700327
Svet Ganov2af57082015-07-30 08:44:20 -0700328 public UidState(int uid) {
329 this.uid = uid;
330 }
331
332 public void clear() {
333 pkgOps = null;
334 opModes = null;
335 }
336
337 public boolean isDefault() {
338 return (pkgOps == null || pkgOps.isEmpty())
Svet Ganovaf189e32019-02-15 18:45:29 -0800339 && (opModes == null || opModes.size() <= 0)
340 && (state == UID_STATE_CACHED
341 && (pendingState == UID_STATE_CACHED));
Svet Ganov2af57082015-07-30 08:44:20 -0700342 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700343
Svet Ganovaf189e32019-02-15 18:45:29 -0800344 int evalMode(int op, int mode) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700345 if (mode == AppOpsManager.MODE_FOREGROUND) {
Wei Wange1f864e2019-03-28 18:12:18 -0700346 return state <= AppOpsManager.resolveFirstUnrestrictedUidState(op)
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700347 ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED;
348 }
349 return mode;
350 }
351
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700352 private void evalForegroundWatchers(int op, SparseArray<ArraySet<ModeCallback>> watchers,
353 SparseBooleanArray which) {
354 boolean curValue = which.get(op, false);
355 ArraySet<ModeCallback> callbacks = watchers.get(op);
356 if (callbacks != null) {
357 for (int cbi = callbacks.size() - 1; !curValue && cbi >= 0; cbi--) {
358 if ((callbacks.valueAt(cbi).mFlags
359 & AppOpsManager.WATCH_FOREGROUND_CHANGES) != 0) {
360 hasForegroundWatchers = true;
361 curValue = true;
362 }
363 }
364 }
365 which.put(op, curValue);
366 }
367
368 public void evalForegroundOps(SparseArray<ArraySet<ModeCallback>> watchers) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700369 SparseBooleanArray which = null;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700370 hasForegroundWatchers = false;
371 if (opModes != null) {
372 for (int i = opModes.size() - 1; i >= 0; i--) {
373 if (opModes.valueAt(i) == AppOpsManager.MODE_FOREGROUND) {
374 if (which == null) {
375 which = new SparseBooleanArray();
376 }
377 evalForegroundWatchers(opModes.keyAt(i), watchers, which);
378 }
379 }
380 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700381 if (pkgOps != null) {
382 for (int i = pkgOps.size() - 1; i >= 0; i--) {
383 Ops ops = pkgOps.valueAt(i);
384 for (int j = ops.size() - 1; j >= 0; j--) {
385 if (ops.valueAt(j).mode == AppOpsManager.MODE_FOREGROUND) {
386 if (which == null) {
387 which = new SparseBooleanArray();
388 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700389 evalForegroundWatchers(ops.keyAt(j), watchers, which);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700390 }
391 }
392 }
393 }
394 foregroundOps = which;
395 }
Svet Ganov2af57082015-07-30 08:44:20 -0700396 }
397
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700398 final static class Ops extends SparseArray<Op> {
399 final String packageName;
400 final UidState uidState;
401 final boolean isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800402
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700403 Ops(String _packageName, UidState _uidState, boolean _isPrivileged) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800404 packageName = _packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700405 uidState = _uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400406 isPrivileged = _isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800407 }
408 }
409
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700410 final static class Op {
Svet Ganovaf189e32019-02-15 18:45:29 -0800411 int op;
412 boolean running;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700413 final UidState uidState;
Svet Ganovaf189e32019-02-15 18:45:29 -0800414 final @NonNull String packageName;
415
416 private @Mode int mode;
417 private @Nullable LongSparseLongArray mAccessTimes;
418 private @Nullable LongSparseLongArray mRejectTimes;
419 private @Nullable LongSparseLongArray mDurations;
420 private @Nullable LongSparseLongArray mProxyUids;
421 private @Nullable LongSparseArray<String> mProxyPackageNames;
422
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700423 int startNesting;
424 long startRealtime;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800425
Svet Ganovaf189e32019-02-15 18:45:29 -0800426 Op(UidState uidState, String packageName, int op) {
427 this.op = op;
428 this.uidState = uidState;
429 this.packageName = packageName;
430 this.mode = AppOpsManager.opToDefaultMode(op);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700431 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700432
433 int getMode() {
Svet Ganovaf189e32019-02-15 18:45:29 -0800434 return mode;
435 }
436
437 int evalMode() {
438 return uidState.evalMode(op, mode);
439 }
440
441 /** @hide */
442 public void accessed(long time, int proxyUid, @Nullable String proxyPackageName,
443 @AppOpsManager.UidState int uidState, @OpFlags int flags) {
444 final long key = AppOpsManager.makeKey(uidState, flags);
445 if (mAccessTimes == null) {
446 mAccessTimes = new LongSparseLongArray();
447 }
448 mAccessTimes.put(key, time);
449 updateProxyState(key, proxyUid, proxyPackageName);
450 if (mDurations != null) {
451 mDurations.delete(key);
452 }
453 }
454
455 /** @hide */
456 public void rejected(long time, int proxyUid, @Nullable String proxyPackageName,
457 @AppOpsManager.UidState int uidState, @OpFlags int flags) {
458 final long key = AppOpsManager.makeKey(uidState, flags);
459 if (mRejectTimes == null) {
460 mRejectTimes = new LongSparseLongArray();
461 }
462 mRejectTimes.put(key, time);
463 updateProxyState(key, proxyUid, proxyPackageName);
464 if (mDurations != null) {
465 mDurations.delete(key);
466 }
467 }
468
469 /** @hide */
470 public void started(long time, @AppOpsManager.UidState int uidState, @OpFlags int flags) {
471 updateAccessTimeAndDuration(time, -1 /*duration*/, uidState, flags);
472 running = true;
473 }
474
475 /** @hide */
476 public void finished(long time, long duration, @AppOpsManager.UidState int uidState,
477 @OpFlags int flags) {
478 updateAccessTimeAndDuration(time, duration, uidState, flags);
479 running = false;
480 }
481
482 /** @hide */
483 public void running(long time, long duration, @AppOpsManager.UidState int uidState,
484 @OpFlags int flags) {
485 updateAccessTimeAndDuration(time, duration, uidState, flags);
486 }
487
488 /** @hide */
489 public void continuing(long duration, @AppOpsManager.UidState int uidState,
490 @OpFlags int flags) {
491 final long key = AppOpsManager.makeKey(uidState, flags);
492 if (mDurations == null) {
493 mDurations = new LongSparseLongArray();
494 }
495 mDurations.put(key, duration);
496 }
497
498 private void updateAccessTimeAndDuration(long time, long duration,
499 @AppOpsManager.UidState int uidState, @OpFlags int flags) {
500 final long key = AppOpsManager.makeKey(uidState, flags);
501 if (mAccessTimes == null) {
502 mAccessTimes = new LongSparseLongArray();
503 }
504 mAccessTimes.put(key, time);
505 if (mDurations == null) {
506 mDurations = new LongSparseLongArray();
507 }
508 mDurations.put(key, duration);
509 }
510
511 private void updateProxyState(long key, int proxyUid,
512 @Nullable String proxyPackageName) {
513 if (mProxyUids == null) {
514 mProxyUids = new LongSparseLongArray();
515 }
516 mProxyUids.put(key, proxyUid);
517 if (mProxyPackageNames == null) {
518 mProxyPackageNames = new LongSparseArray<>();
519 }
520 mProxyPackageNames.put(key, proxyPackageName);
521 }
522
523 boolean hasAnyTime() {
524 return (mAccessTimes != null && mAccessTimes.size() > 0)
525 || (mRejectTimes != null && mRejectTimes.size() > 0);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700526 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800527 }
528
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800529 final SparseArray<ArraySet<ModeCallback>> mOpModeWatchers = new SparseArray<>();
530 final ArrayMap<String, ArraySet<ModeCallback>> mPackageModeWatchers = new ArrayMap<>();
531 final ArrayMap<IBinder, ModeCallback> mModeWatchers = new ArrayMap<>();
532 final ArrayMap<IBinder, SparseArray<ActiveCallback>> mActiveWatchers = new ArrayMap<>();
Svet Ganovb3d2ae22018-12-17 22:06:15 -0800533 final ArrayMap<IBinder, SparseArray<NotedCallback>> mNotedWatchers = new ArrayMap<>();
Dianne Hackborn68d76552017-02-27 15:32:03 -0800534 final SparseArray<SparseArray<Restriction>> mAudioRestrictions = new SparseArray<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800535
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700536 final class ModeCallback implements DeathRecipient {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800537 final IAppOpsCallback mCallback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700538 final int mWatchingUid;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700539 final int mFlags;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700540 final int mCallingUid;
541 final int mCallingPid;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800542
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700543 ModeCallback(IAppOpsCallback callback, int watchingUid, int flags, int callingUid,
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700544 int callingPid) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800545 mCallback = callback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700546 mWatchingUid = watchingUid;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700547 mFlags = flags;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700548 mCallingUid = callingUid;
549 mCallingPid = callingPid;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800550 try {
551 mCallback.asBinder().linkToDeath(this, 0);
552 } catch (RemoteException e) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -0800553 /*ignored*/
Dianne Hackbornc2293022013-02-06 23:14:49 -0800554 }
555 }
556
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700557 public boolean isWatchingUid(int uid) {
558 return uid == UID_ANY || mWatchingUid < 0 || mWatchingUid == uid;
559 }
560
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700561 @Override
562 public String toString() {
563 StringBuilder sb = new StringBuilder(128);
564 sb.append("ModeCallback{");
565 sb.append(Integer.toHexString(System.identityHashCode(this)));
566 sb.append(" watchinguid=");
567 UserHandle.formatUid(sb, mWatchingUid);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700568 sb.append(" flags=0x");
569 sb.append(Integer.toHexString(mFlags));
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700570 sb.append(" from uid=");
571 UserHandle.formatUid(sb, mCallingUid);
572 sb.append(" pid=");
573 sb.append(mCallingPid);
574 sb.append('}');
575 return sb.toString();
576 }
577
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700578 void unlinkToDeath() {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800579 mCallback.asBinder().unlinkToDeath(this, 0);
580 }
581
582 @Override
583 public void binderDied() {
584 stopWatchingMode(mCallback);
585 }
586 }
587
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700588 final class ActiveCallback implements DeathRecipient {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800589 final IAppOpsActiveCallback mCallback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700590 final int mWatchingUid;
591 final int mCallingUid;
592 final int mCallingPid;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800593
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700594 ActiveCallback(IAppOpsActiveCallback callback, int watchingUid, int callingUid,
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700595 int callingPid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800596 mCallback = callback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700597 mWatchingUid = watchingUid;
598 mCallingUid = callingUid;
599 mCallingPid = callingPid;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800600 try {
601 mCallback.asBinder().linkToDeath(this, 0);
602 } catch (RemoteException e) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -0800603 /*ignored*/
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800604 }
605 }
606
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700607 @Override
608 public String toString() {
609 StringBuilder sb = new StringBuilder(128);
610 sb.append("ActiveCallback{");
611 sb.append(Integer.toHexString(System.identityHashCode(this)));
612 sb.append(" watchinguid=");
613 UserHandle.formatUid(sb, mWatchingUid);
614 sb.append(" from uid=");
615 UserHandle.formatUid(sb, mCallingUid);
616 sb.append(" pid=");
617 sb.append(mCallingPid);
618 sb.append('}');
619 return sb.toString();
620 }
621
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700622 void destroy() {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800623 mCallback.asBinder().unlinkToDeath(this, 0);
624 }
625
626 @Override
627 public void binderDied() {
628 stopWatchingActive(mCallback);
629 }
630 }
631
Svet Ganovb3d2ae22018-12-17 22:06:15 -0800632 final class NotedCallback implements DeathRecipient {
633 final IAppOpsNotedCallback mCallback;
634 final int mWatchingUid;
635 final int mCallingUid;
636 final int mCallingPid;
637
638 NotedCallback(IAppOpsNotedCallback callback, int watchingUid, int callingUid,
639 int callingPid) {
640 mCallback = callback;
641 mWatchingUid = watchingUid;
642 mCallingUid = callingUid;
643 mCallingPid = callingPid;
644 try {
645 mCallback.asBinder().linkToDeath(this, 0);
646 } catch (RemoteException e) {
647 /*ignored*/
648 }
649 }
650
651 @Override
652 public String toString() {
653 StringBuilder sb = new StringBuilder(128);
654 sb.append("NotedCallback{");
655 sb.append(Integer.toHexString(System.identityHashCode(this)));
656 sb.append(" watchinguid=");
657 UserHandle.formatUid(sb, mWatchingUid);
658 sb.append(" from uid=");
659 UserHandle.formatUid(sb, mCallingUid);
660 sb.append(" pid=");
661 sb.append(mCallingPid);
662 sb.append('}');
663 return sb.toString();
664 }
665
666 void destroy() {
667 mCallback.asBinder().unlinkToDeath(this, 0);
668 }
669
670 @Override
671 public void binderDied() {
672 stopWatchingNoted(mCallback);
673 }
674 }
675
Svet Ganova7a0db62018-02-27 20:08:01 -0800676 final ArrayMap<IBinder, ClientState> mClients = new ArrayMap<>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700677
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700678 final class ClientState extends Binder implements DeathRecipient {
Svet Ganovf7b47252018-02-26 11:11:27 -0800679 final ArrayList<Op> mStartedOps = new ArrayList<>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700680 final IBinder mAppToken;
681 final int mPid;
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700682
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700683 ClientState(IBinder appToken) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700684 mAppToken = appToken;
685 mPid = Binder.getCallingPid();
Svet Ganovf7b47252018-02-26 11:11:27 -0800686 // Watch only for remote processes dying
687 if (!(appToken instanceof Binder)) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700688 try {
689 mAppToken.linkToDeath(this, 0);
690 } catch (RemoteException e) {
Svet Ganovf7b47252018-02-26 11:11:27 -0800691 /* do nothing */
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700692 }
693 }
694 }
695
696 @Override
697 public String toString() {
698 return "ClientState{" +
699 "mAppToken=" + mAppToken +
Svet Ganovf7b47252018-02-26 11:11:27 -0800700 ", " + "pid=" + mPid +
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700701 '}';
702 }
703
704 @Override
705 public void binderDied() {
706 synchronized (AppOpsService.this) {
707 for (int i=mStartedOps.size()-1; i>=0; i--) {
Bruno Martins8e0636d2018-12-30 16:02:59 +0000708 final Op op = mStartedOps.get(i);
709 finishOperationLocked(op, /*finishNested*/ true);
710 if (op.startNesting <= 0) {
711 scheduleOpActiveChangedIfNeededLocked(op.op, op.uidState.uid,
712 op.packageName, false);
713 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700714 }
715 mClients.remove(mAppToken);
716 }
717 }
718 }
719
Jeff Brown6f357d32014-01-15 20:40:55 -0800720 public AppOpsService(File storagePath, Handler handler) {
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600721 LockGuard.installLock(this, LockGuard.INDEX_APP_OPS);
Dianne Hackborne17b4452018-01-10 13:15:40 -0800722 mFile = new AtomicFile(storagePath, "appops");
Jeff Brown6f357d32014-01-15 20:40:55 -0800723 mHandler = handler;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700724 mConstants = new Constants(mHandler);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800725 readState();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800726 }
David Braunf5d83192013-09-16 13:43:51 -0700727
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800728 public void publish(Context context) {
729 mContext = context;
730 ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
Dianne Hackbornd5254412018-05-11 18:02:58 -0700731 LocalServices.addService(AppOpsManagerInternal.class, mAppOpsManagerInternal);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800732 }
733
Dianne Hackborn514074f2013-02-11 10:52:46 -0800734 public void systemReady() {
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700735 mConstants.startMonitoring(mContext.getContentResolver());
Svet Ganov8455ba22019-01-02 13:05:56 -0800736 mHistoricalRegistry.systemReady(mContext.getContentResolver());
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700737
Dianne Hackborn514074f2013-02-11 10:52:46 -0800738 synchronized (this) {
739 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700740 for (int i = mUidStates.size() - 1; i >= 0; i--) {
741 UidState uidState = mUidStates.valueAt(i);
742
743 String[] packageNames = getPackagesForUid(uidState.uid);
744 if (ArrayUtils.isEmpty(packageNames)) {
745 uidState.clear();
746 mUidStates.removeAt(i);
747 changed = true;
748 continue;
749 }
750
751 ArrayMap<String, Ops> pkgs = uidState.pkgOps;
752 if (pkgs == null) {
753 continue;
754 }
755
Dianne Hackborn514074f2013-02-11 10:52:46 -0800756 Iterator<Ops> it = pkgs.values().iterator();
757 while (it.hasNext()) {
758 Ops ops = it.next();
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700759 int curUid = -1;
Dianne Hackborn514074f2013-02-11 10:52:46 -0800760 try {
Jeff Sharkeycd654482016-01-08 17:42:11 -0700761 curUid = AppGlobals.getPackageManager().getPackageUid(ops.packageName,
762 PackageManager.MATCH_UNINSTALLED_PACKAGES,
Svet Ganov2af57082015-07-30 08:44:20 -0700763 UserHandle.getUserId(ops.uidState.uid));
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700764 } catch (RemoteException ignored) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800765 }
Svet Ganov2af57082015-07-30 08:44:20 -0700766 if (curUid != ops.uidState.uid) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800767 Slog.i(TAG, "Pruning old package " + ops.packageName
Svet Ganov2af57082015-07-30 08:44:20 -0700768 + "/" + ops.uidState + ": new uid=" + curUid);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800769 it.remove();
770 changed = true;
771 }
772 }
Svet Ganov2af57082015-07-30 08:44:20 -0700773
774 if (uidState.isDefault()) {
775 mUidStates.removeAt(i);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800776 }
777 }
778 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800779 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800780 }
781 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700782
Suprabh Shukla3017fe42018-11-08 19:00:01 -0800783 final IntentFilter packageSuspendFilter = new IntentFilter();
784 packageSuspendFilter.addAction(Intent.ACTION_PACKAGES_UNSUSPENDED);
785 packageSuspendFilter.addAction(Intent.ACTION_PACKAGES_SUSPENDED);
786 mContext.registerReceiver(new BroadcastReceiver() {
787 @Override
788 public void onReceive(Context context, Intent intent) {
789 final int[] changedUids = intent.getIntArrayExtra(Intent.EXTRA_CHANGED_UID_LIST);
790 final String[] changedPkgs = intent.getStringArrayExtra(
791 Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackbornb298b352019-04-04 11:01:41 -0700792 ArraySet<ModeCallback> callbacks;
793 synchronized (AppOpsService.this) {
794 callbacks = mOpModeWatchers.get(OP_PLAY_AUDIO);
795 if (callbacks == null) {
796 return;
797 }
798 callbacks = new ArraySet<>(callbacks);
799 }
Suprabh Shukla3017fe42018-11-08 19:00:01 -0800800 for (int i = 0; i < changedUids.length; i++) {
801 final int changedUid = changedUids[i];
802 final String changedPkg = changedPkgs[i];
Dianne Hackbornb298b352019-04-04 11:01:41 -0700803 // We trust packagemanager to insert matching uid and packageNames in the
804 // extras
805 notifyOpChanged(callbacks, OP_PLAY_AUDIO, changedUid, changedPkg);
Suprabh Shukla3017fe42018-11-08 19:00:01 -0800806 }
807 }
808 }, packageSuspendFilter);
809
Suprabh Shuklaaef25132017-01-23 18:09:03 -0800810 PackageManagerInternal packageManagerInternal = LocalServices.getService(
811 PackageManagerInternal.class);
812 packageManagerInternal.setExternalSourcesPolicy(
813 new PackageManagerInternal.ExternalSourcesPolicy() {
814 @Override
815 public int getPackageTrustedToInstallApps(String packageName, int uid) {
816 int appOpMode = checkOperation(AppOpsManager.OP_REQUEST_INSTALL_PACKAGES,
817 uid, packageName);
818 switch (appOpMode) {
819 case AppOpsManager.MODE_ALLOWED:
820 return PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
821 case AppOpsManager.MODE_ERRORED:
822 return PackageManagerInternal.ExternalSourcesPolicy.USER_BLOCKED;
823 default:
824 return PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT;
825 }
826 }
827 });
828
Jeff Sharkey10ec9d82018-11-28 14:52:45 -0700829 if (!StorageManager.hasIsolatedStorage()) {
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700830 StorageManagerInternal storageManagerInternal = LocalServices.getService(
831 StorageManagerInternal.class);
832 storageManagerInternal.addExternalStoragePolicy(
833 new StorageManagerInternal.ExternalStorageMountPolicy() {
834 @Override
835 public int getMountMode(int uid, String packageName) {
836 if (Process.isIsolated(uid)) {
837 return Zygote.MOUNT_EXTERNAL_NONE;
838 }
839 if (noteOperation(AppOpsManager.OP_READ_EXTERNAL_STORAGE, uid,
840 packageName) != AppOpsManager.MODE_ALLOWED) {
841 return Zygote.MOUNT_EXTERNAL_NONE;
842 }
843 if (noteOperation(AppOpsManager.OP_WRITE_EXTERNAL_STORAGE, uid,
844 packageName) != AppOpsManager.MODE_ALLOWED) {
845 return Zygote.MOUNT_EXTERNAL_READ;
846 }
847 return Zygote.MOUNT_EXTERNAL_WRITE;
Svet Ganov6ee871e2015-07-10 14:29:33 -0700848 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700849
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700850 @Override
851 public boolean hasExternalStorage(int uid, String packageName) {
852 final int mountMode = getMountMode(uid, packageName);
853 return mountMode == Zygote.MOUNT_EXTERNAL_READ
854 || mountMode == Zygote.MOUNT_EXTERNAL_WRITE;
855 }
856 });
857 }
Dianne Hackborn514074f2013-02-11 10:52:46 -0800858 }
859
860 public void packageRemoved(int uid, String packageName) {
861 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700862 UidState uidState = mUidStates.get(uid);
863 if (uidState == null) {
864 return;
865 }
866
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800867 Ops ops = null;
Svet Ganov2af57082015-07-30 08:44:20 -0700868
869 // Remove any package state if such.
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800870 if (uidState.pkgOps != null) {
871 ops = uidState.pkgOps.remove(packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700872 }
873
874 // If we just nuked the last package state check if the UID is valid.
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800875 if (ops != null && uidState.pkgOps.isEmpty()
Svet Ganov2af57082015-07-30 08:44:20 -0700876 && getPackagesForUid(uid).length <= 0) {
877 mUidStates.remove(uid);
878 }
879
Svet Ganova7a0db62018-02-27 20:08:01 -0800880 // Finish ops other packages started on behalf of the package.
881 final int clientCount = mClients.size();
882 for (int i = 0; i < clientCount; i++) {
883 final ClientState client = mClients.valueAt(i);
884 if (client.mStartedOps == null) {
885 continue;
886 }
887 final int opCount = client.mStartedOps.size();
888 for (int j = opCount - 1; j >= 0; j--) {
889 final Op op = client.mStartedOps.get(j);
Svet Ganovaf189e32019-02-15 18:45:29 -0800890 if (uid == op.uidState.uid && packageName.equals(op.packageName)) {
Svet Ganova7a0db62018-02-27 20:08:01 -0800891 finishOperationLocked(op, /*finishNested*/ true);
892 client.mStartedOps.remove(j);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700893 if (op.startNesting <= 0) {
Svet Ganova7a0db62018-02-27 20:08:01 -0800894 scheduleOpActiveChangedIfNeededLocked(op.op,
895 uid, packageName, false);
896 }
897 }
898 }
899 }
900
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800901 if (ops != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700902 scheduleFastWriteLocked();
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800903
904 final int opCount = ops.size();
905 for (int i = 0; i < opCount; i++) {
906 final Op op = ops.valueAt(i);
Svet Ganovaf189e32019-02-15 18:45:29 -0800907 if (op.running) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800908 scheduleOpActiveChangedIfNeededLocked(
Svet Ganovaf189e32019-02-15 18:45:29 -0800909 op.op, op.uidState.uid, op.packageName, false);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800910 }
911 }
Dianne Hackborn514074f2013-02-11 10:52:46 -0800912 }
Winson4e3b4352019-05-07 16:29:59 -0700913
914 mHistoricalRegistry.clearHistory(uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800915 }
916 }
917
918 public void uidRemoved(int uid) {
919 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700920 if (mUidStates.indexOfKey(uid) >= 0) {
921 mUidStates.remove(uid);
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800922 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800923 }
924 }
925 }
926
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700927 public void updateUidProcState(int uid, int procState) {
928 synchronized (this) {
929 final UidState uidState = getUidStateLocked(uid, true);
Amith Yamasania0a30a12019-01-22 11:38:06 -0800930 int newState = PROCESS_STATE_TO_UID_STATE[procState];
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700931 if (uidState != null && uidState.pendingState != newState) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700932 final int oldPendingState = uidState.pendingState;
933 uidState.pendingState = newState;
Wei Wange1f864e2019-03-28 18:12:18 -0700934 if (newState < uidState.state
935 || (newState <= UID_STATE_MAX_LAST_NON_RESTRICTED
936 && uidState.state > UID_STATE_MAX_LAST_NON_RESTRICTED)) {
937 // We are moving to a more important state, or the new state may be in the
938 // foreground and the old state is in the background, then always do it
939 // immediately.
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700940 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700941 } else if (uidState.pendingStateCommitTime == 0) {
942 // We are moving to a less important state for the first time,
943 // delay the application for a bit.
Dianne Hackborne93ab412018-05-14 17:52:30 -0700944 final long settleTime;
945 if (uidState.state <= UID_STATE_TOP) {
946 settleTime = mConstants.TOP_STATE_SETTLE_TIME;
947 } else if (uidState.state <= UID_STATE_FOREGROUND_SERVICE) {
948 settleTime = mConstants.FG_SERVICE_STATE_SETTLE_TIME;
949 } else {
950 settleTime = mConstants.BG_STATE_SETTLE_TIME;
951 }
Dianne Hackborn9fb93502018-06-18 12:29:44 -0700952 uidState.pendingStateCommitTime = SystemClock.elapsedRealtime() + settleTime;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700953 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700954 if (uidState.startNesting != 0) {
955 // There is some actively running operation... need to find it
956 // and appropriately update its state.
957 final long now = System.currentTimeMillis();
958 for (int i = uidState.pkgOps.size() - 1; i >= 0; i--) {
959 final Ops ops = uidState.pkgOps.valueAt(i);
960 for (int j = ops.size() - 1; j >= 0; j--) {
961 final Op op = ops.valueAt(j);
962 if (op.startNesting > 0) {
Svet Ganovaf189e32019-02-15 18:45:29 -0800963 final long duration = SystemClock.elapsedRealtime()
964 - op.startRealtime;
965 // We don't support proxy long running ops (start/stop)
966 mHistoricalRegistry.increaseOpAccessDuration(op.op,
967 op.uidState.uid, op.packageName, oldPendingState,
968 AppOpsManager.OP_FLAG_SELF, duration);
969 // Finish the op in the old state
970 op.finished(now, duration, oldPendingState,
971 AppOpsManager.OP_FLAG_SELF);
972 // Start the op in the new state
973 op.startRealtime = now;
974 op.started(now, newState, AppOpsManager.OP_FLAG_SELF);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700975 }
976 }
977 }
978 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700979 }
980 }
981 }
982
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800983 public void shutdown() {
984 Slog.w(TAG, "Writing app ops before shutdown...");
Dianne Hackborn35654b62013-01-14 17:38:02 -0800985 boolean doWrite = false;
986 synchronized (this) {
987 if (mWriteScheduled) {
988 mWriteScheduled = false;
989 doWrite = true;
990 }
991 }
992 if (doWrite) {
993 writeState();
994 }
995 }
996
Dianne Hackborn72e39832013-01-18 18:36:09 -0800997 private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
998 ArrayList<AppOpsManager.OpEntry> resOps = null;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700999 final long elapsedNow = SystemClock.elapsedRealtime();
Dianne Hackborn72e39832013-01-18 18:36:09 -08001000 if (ops == null) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001001 resOps = new ArrayList<>();
Dianne Hackborn72e39832013-01-18 18:36:09 -08001002 for (int j=0; j<pkgOps.size(); j++) {
1003 Op curOp = pkgOps.valueAt(j);
Svet Ganovaf189e32019-02-15 18:45:29 -08001004 resOps.add(getOpEntryForResult(curOp, elapsedNow));
Dianne Hackborn72e39832013-01-18 18:36:09 -08001005 }
1006 } else {
1007 for (int j=0; j<ops.length; j++) {
1008 Op curOp = pkgOps.get(ops[j]);
1009 if (curOp != null) {
1010 if (resOps == null) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001011 resOps = new ArrayList<>();
Dianne Hackborn72e39832013-01-18 18:36:09 -08001012 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001013 resOps.add(getOpEntryForResult(curOp, elapsedNow));
Dianne Hackborn72e39832013-01-18 18:36:09 -08001014 }
1015 }
1016 }
1017 return resOps;
1018 }
1019
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001020 private ArrayList<AppOpsManager.OpEntry> collectOps(SparseIntArray uidOps, int[] ops) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08001021 if (uidOps == null) {
1022 return null;
1023 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001024 ArrayList<AppOpsManager.OpEntry> resOps = null;
1025 if (ops == null) {
1026 resOps = new ArrayList<>();
1027 for (int j=0; j<uidOps.size(); j++) {
Svet Ganovaf189e32019-02-15 18:45:29 -08001028 resOps.add(new OpEntry(uidOps.keyAt(j), uidOps.valueAt(j)));
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001029 }
1030 } else {
1031 for (int j=0; j<ops.length; j++) {
1032 int index = uidOps.indexOfKey(ops[j]);
1033 if (index >= 0) {
1034 if (resOps == null) {
1035 resOps = new ArrayList<>();
1036 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001037 resOps.add(new OpEntry(uidOps.keyAt(j), uidOps.valueAt(j)));
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001038 }
1039 }
1040 }
1041 return resOps;
1042 }
1043
Svet Ganovaf189e32019-02-15 18:45:29 -08001044 private static @NonNull OpEntry getOpEntryForResult(@NonNull Op op, long elapsedNow) {
1045 if (op.running) {
1046 op.continuing(elapsedNow - op.startRealtime,
1047 op.uidState.state, AppOpsManager.OP_FLAG_SELF);
1048 }
1049 final OpEntry entry = new OpEntry(op.op, op.running, op.mode,
1050 op.mAccessTimes != null ? op.mAccessTimes.clone() : null,
1051 op.mRejectTimes != null ? op.mRejectTimes.clone() : null,
1052 op.mDurations != null ? op.mDurations.clone() : null,
1053 op.mProxyUids != null ? op.mProxyUids.clone() : null,
1054 op.mProxyPackageNames != null ? op.mProxyPackageNames.clone() : null);
1055 return entry;
1056 }
1057
Dianne Hackborn35654b62013-01-14 17:38:02 -08001058 @Override
1059 public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
1060 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
1061 Binder.getCallingPid(), Binder.getCallingUid(), null);
1062 ArrayList<AppOpsManager.PackageOps> res = null;
1063 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -07001064 final int uidStateCount = mUidStates.size();
1065 for (int i = 0; i < uidStateCount; i++) {
1066 UidState uidState = mUidStates.valueAt(i);
1067 if (uidState.pkgOps == null || uidState.pkgOps.isEmpty()) {
1068 continue;
1069 }
1070 ArrayMap<String, Ops> packages = uidState.pkgOps;
1071 final int packageCount = packages.size();
1072 for (int j = 0; j < packageCount; j++) {
1073 Ops pkgOps = packages.valueAt(j);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001074 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001075 if (resOps != null) {
1076 if (res == null) {
1077 res = new ArrayList<AppOpsManager.PackageOps>();
1078 }
1079 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -07001080 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001081 res.add(resPackage);
1082 }
1083 }
1084 }
1085 }
1086 return res;
1087 }
1088
1089 @Override
Dianne Hackborn72e39832013-01-18 18:36:09 -08001090 public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
1091 int[] ops) {
1092 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
1093 Binder.getCallingPid(), Binder.getCallingUid(), null);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001094 String resolvedPackageName = resolvePackageName(uid, packageName);
1095 if (resolvedPackageName == null) {
1096 return Collections.emptyList();
1097 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08001098 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001099 Ops pkgOps = getOpsRawLocked(uid, resolvedPackageName, false /* edit */,
1100 false /* uidMismatchExpected */);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001101 if (pkgOps == null) {
1102 return null;
1103 }
1104 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
1105 if (resOps == null) {
1106 return null;
1107 }
1108 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
1109 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -07001110 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001111 res.add(resPackage);
1112 return res;
1113 }
1114 }
1115
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001116 @Override
Svet Ganov8455ba22019-01-02 13:05:56 -08001117 public void getHistoricalOps(int uid, @NonNull String packageName,
Svet Ganov23c88db2019-01-22 20:38:11 -08001118 @Nullable List<String> opNames, long beginTimeMillis, long endTimeMillis,
Svet Ganovaf189e32019-02-15 18:45:29 -08001119 @OpFlags int flags, @NonNull RemoteCallback callback) {
Svet Ganov23c88db2019-01-22 20:38:11 -08001120 // Use the builder to validate arguments.
Svet Ganovaf189e32019-02-15 18:45:29 -08001121 new HistoricalOpsRequest.Builder(
Svet Ganov23c88db2019-01-22 20:38:11 -08001122 beginTimeMillis, endTimeMillis)
1123 .setUid(uid)
1124 .setPackageName(packageName)
1125 .setOpNames(opNames)
Svet Ganovaf189e32019-02-15 18:45:29 -08001126 .setFlags(flags)
Svet Ganov23c88db2019-01-22 20:38:11 -08001127 .build();
Svet Ganov8455ba22019-01-02 13:05:56 -08001128 Preconditions.checkNotNull(callback, "callback cannot be null");
Svet Ganovad0a49b2018-10-29 10:07:08 -07001129
1130 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
Svet Ganov8455ba22019-01-02 13:05:56 -08001131 Binder.getCallingPid(), Binder.getCallingUid(), "getHistoricalOps");
Svet Ganovad0a49b2018-10-29 10:07:08 -07001132
Svet Ganov23c88db2019-01-22 20:38:11 -08001133 final String[] opNamesArray = (opNames != null)
1134 ? opNames.toArray(new String[opNames.size()]) : null;
Svet Ganovad0a49b2018-10-29 10:07:08 -07001135
Svet Ganovaf189e32019-02-15 18:45:29 -08001136 // Must not hold the appops lock
1137 mHistoricalRegistry.getHistoricalOps(uid, packageName, opNamesArray,
1138 beginTimeMillis, endTimeMillis, flags, callback);
Svet Ganovad0a49b2018-10-29 10:07:08 -07001139 }
1140
1141 @Override
Svet Ganov8455ba22019-01-02 13:05:56 -08001142 public void getHistoricalOpsFromDiskRaw(int uid, @NonNull String packageName,
Svet Ganov23c88db2019-01-22 20:38:11 -08001143 @Nullable List<String> opNames, long beginTimeMillis, long endTimeMillis,
Svet Ganovaf189e32019-02-15 18:45:29 -08001144 @OpFlags int flags, @NonNull RemoteCallback callback) {
Svet Ganov23c88db2019-01-22 20:38:11 -08001145 // Use the builder to validate arguments.
Svet Ganovaf189e32019-02-15 18:45:29 -08001146 new HistoricalOpsRequest.Builder(
Svet Ganov23c88db2019-01-22 20:38:11 -08001147 beginTimeMillis, endTimeMillis)
1148 .setUid(uid)
1149 .setPackageName(packageName)
1150 .setOpNames(opNames)
Svet Ganovaf189e32019-02-15 18:45:29 -08001151 .setFlags(flags)
Svet Ganov23c88db2019-01-22 20:38:11 -08001152 .build();
Svet Ganov8455ba22019-01-02 13:05:56 -08001153 Preconditions.checkNotNull(callback, "callback cannot be null");
Svet Ganovad0a49b2018-10-29 10:07:08 -07001154
Svet Ganov8e5bf962019-03-19 23:59:03 -07001155 mContext.enforcePermission(Manifest.permission.MANAGE_APPOPS,
Svet Ganov8455ba22019-01-02 13:05:56 -08001156 Binder.getCallingPid(), Binder.getCallingUid(), "getHistoricalOps");
Svet Ganovad0a49b2018-10-29 10:07:08 -07001157
Svet Ganov23c88db2019-01-22 20:38:11 -08001158 final String[] opNamesArray = (opNames != null)
1159 ? opNames.toArray(new String[opNames.size()]) : null;
1160
Svet Ganov8455ba22019-01-02 13:05:56 -08001161 // Must not hold the appops lock
Svet Ganov23c88db2019-01-22 20:38:11 -08001162 mHistoricalRegistry.getHistoricalOpsFromDiskRaw(uid, packageName, opNamesArray,
Svet Ganovaf189e32019-02-15 18:45:29 -08001163 beginTimeMillis, endTimeMillis, flags, callback);
Svet Ganovad0a49b2018-10-29 10:07:08 -07001164 }
1165
1166 @Override
Svet Ganov8e5bf962019-03-19 23:59:03 -07001167 public void reloadNonHistoricalState() {
1168 mContext.enforcePermission(Manifest.permission.MANAGE_APPOPS,
1169 Binder.getCallingPid(), Binder.getCallingUid(), "reloadNonHistoricalState");
1170 writeState();
1171 readState();
1172 }
1173
1174 @Override
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001175 public List<AppOpsManager.PackageOps> getUidOps(int uid, int[] ops) {
1176 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
1177 Binder.getCallingPid(), Binder.getCallingUid(), null);
1178 synchronized (this) {
1179 UidState uidState = getUidStateLocked(uid, false);
1180 if (uidState == null) {
1181 return null;
1182 }
1183 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(uidState.opModes, ops);
1184 if (resOps == null) {
1185 return null;
1186 }
1187 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
1188 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
1189 null, uidState.uid, resOps);
1190 res.add(resPackage);
1191 return res;
1192 }
1193 }
1194
Dianne Hackborn607b4142013-08-02 18:10:10 -07001195 private void pruneOp(Op op, int uid, String packageName) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001196 if (!op.hasAnyTime()) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001197 Ops ops = getOpsRawLocked(uid, packageName, false /* edit */,
1198 false /* uidMismatchExpected */);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001199 if (ops != null) {
1200 ops.remove(op.op);
1201 if (ops.size() <= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -07001202 UidState uidState = ops.uidState;
1203 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
Dianne Hackborn607b4142013-08-02 18:10:10 -07001204 if (pkgOps != null) {
1205 pkgOps.remove(ops.packageName);
Svet Ganov2af57082015-07-30 08:44:20 -07001206 if (pkgOps.isEmpty()) {
1207 uidState.pkgOps = null;
1208 }
1209 if (uidState.isDefault()) {
1210 mUidStates.remove(uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001211 }
1212 }
1213 }
1214 }
1215 }
1216 }
1217
Svet Ganovaf189e32019-02-15 18:45:29 -08001218 private void enforceManageAppOpsModes(int callingPid, int callingUid, int targetUid) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07001219 if (callingPid == Process.myPid()) {
1220 return;
1221 }
1222 final int callingUser = UserHandle.getUserId(callingUid);
1223 synchronized (this) {
1224 if (mProfileOwners != null && mProfileOwners.get(callingUser, -1) == callingUid) {
1225 if (targetUid >= 0 && callingUser == UserHandle.getUserId(targetUid)) {
1226 // Profile owners are allowed to change modes but only for apps
1227 // within their user.
1228 return;
1229 }
1230 }
1231 }
1232 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
1233 Binder.getCallingPid(), Binder.getCallingUid(), null);
1234 }
1235
Dianne Hackborn72e39832013-01-18 18:36:09 -08001236 @Override
Svet Ganov2af57082015-07-30 08:44:20 -07001237 public void setUidMode(int code, int uid, int mode) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08001238 if (DEBUG) {
1239 Slog.i(TAG, "uid " + uid + " OP_" + opToName(code) + " := " + modeToName(mode)
1240 + " by uid " + Binder.getCallingUid());
1241 }
1242
Dianne Hackbornd5254412018-05-11 18:02:58 -07001243 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
Svet Ganov2af57082015-07-30 08:44:20 -07001244 verifyIncomingOp(code);
1245 code = AppOpsManager.opToSwitch(code);
1246
1247 synchronized (this) {
1248 final int defaultMode = AppOpsManager.opToDefaultMode(code);
1249
1250 UidState uidState = getUidStateLocked(uid, false);
1251 if (uidState == null) {
1252 if (mode == defaultMode) {
1253 return;
1254 }
1255 uidState = new UidState(uid);
1256 uidState.opModes = new SparseIntArray();
1257 uidState.opModes.put(code, mode);
1258 mUidStates.put(uid, uidState);
1259 scheduleWriteLocked();
1260 } else if (uidState.opModes == null) {
1261 if (mode != defaultMode) {
1262 uidState.opModes = new SparseIntArray();
1263 uidState.opModes.put(code, mode);
1264 scheduleWriteLocked();
1265 }
1266 } else {
Hai Zhang2b98fb32018-09-21 15:18:46 -07001267 if (uidState.opModes.indexOfKey(code) >= 0 && uidState.opModes.get(code) == mode) {
Svet Ganov2af57082015-07-30 08:44:20 -07001268 return;
1269 }
1270 if (mode == defaultMode) {
1271 uidState.opModes.delete(code);
1272 if (uidState.opModes.size() <= 0) {
1273 uidState.opModes = null;
1274 }
1275 } else {
1276 uidState.opModes.put(code, mode);
1277 }
1278 scheduleWriteLocked();
1279 }
Wei Wang711eb662019-03-21 18:24:17 -07001280 uidState.evalForegroundOps(mOpModeWatchers);
Svet Ganov2af57082015-07-30 08:44:20 -07001281 }
1282
Svetoslav215b44a2015-08-04 19:03:40 -07001283 String[] uidPackageNames = getPackagesForUid(uid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001284 ArrayMap<ModeCallback, ArraySet<String>> callbackSpecs = null;
Svet Ganov2af57082015-07-30 08:44:20 -07001285
riddle_hsu40b300f2015-11-23 13:22:03 +08001286 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001287 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001288 if (callbacks != null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001289 final int callbackCount = callbacks.size();
1290 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001291 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +08001292 ArraySet<String> changedPackages = new ArraySet<>();
1293 Collections.addAll(changedPackages, uidPackageNames);
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001294 if (callbackSpecs == null) {
1295 callbackSpecs = new ArrayMap<>();
1296 }
riddle_hsu40b300f2015-11-23 13:22:03 +08001297 callbackSpecs.put(callback, changedPackages);
1298 }
1299 }
1300
1301 for (String uidPackageName : uidPackageNames) {
1302 callbacks = mPackageModeWatchers.get(uidPackageName);
1303 if (callbacks != null) {
1304 if (callbackSpecs == null) {
1305 callbackSpecs = new ArrayMap<>();
Svet Ganov2af57082015-07-30 08:44:20 -07001306 }
riddle_hsu40b300f2015-11-23 13:22:03 +08001307 final int callbackCount = callbacks.size();
1308 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001309 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +08001310 ArraySet<String> changedPackages = callbackSpecs.get(callback);
1311 if (changedPackages == null) {
1312 changedPackages = new ArraySet<>();
1313 callbackSpecs.put(callback, changedPackages);
1314 }
1315 changedPackages.add(uidPackageName);
1316 }
Svet Ganov2af57082015-07-30 08:44:20 -07001317 }
1318 }
1319 }
1320
1321 if (callbackSpecs == null) {
Sudheer Shankab1613982019-05-16 16:55:50 -07001322 notifyOpChangedSync(code, uid, null, mode);
Svet Ganov2af57082015-07-30 08:44:20 -07001323 return;
1324 }
1325
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001326 for (int i = 0; i < callbackSpecs.size(); i++) {
1327 final ModeCallback callback = callbackSpecs.keyAt(i);
1328 final ArraySet<String> reportedPackageNames = callbackSpecs.valueAt(i);
1329 if (reportedPackageNames == null) {
1330 mHandler.sendMessage(PooledLambda.obtainMessage(
1331 AppOpsService::notifyOpChanged,
1332 this, callback, code, uid, (String) null));
1333
1334 } else {
1335 final int reportedPackageCount = reportedPackageNames.size();
1336 for (int j = 0; j < reportedPackageCount; j++) {
1337 final String reportedPackageName = reportedPackageNames.valueAt(j);
1338 mHandler.sendMessage(PooledLambda.obtainMessage(
1339 AppOpsService::notifyOpChanged,
1340 this, callback, code, uid, reportedPackageName));
Svet Ganov2af57082015-07-30 08:44:20 -07001341 }
1342 }
Svet Ganov2af57082015-07-30 08:44:20 -07001343 }
Sudheer Shankab1613982019-05-16 16:55:50 -07001344
1345 notifyOpChangedSync(code, uid, null, mode);
1346 }
1347
1348 private void notifyOpChangedSync(int code, int uid, @NonNull String packageName, int mode) {
1349 final StorageManagerInternal storageManagerInternal =
1350 LocalServices.getService(StorageManagerInternal.class);
1351 if (storageManagerInternal != null) {
1352 storageManagerInternal.onAppOpsChanged(code, uid, packageName, mode);
1353 }
Svet Ganov2af57082015-07-30 08:44:20 -07001354 }
1355
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001356 /**
1357 * Set all {@link #setMode (package) modes} for this uid to the default value.
1358 *
1359 * @param code The app-op
1360 * @param uid The uid
1361 */
1362 private void setAllPkgModesToDefault(int code, int uid) {
1363 synchronized (this) {
1364 UidState uidState = getUidStateLocked(uid, false);
1365 if (uidState == null) {
1366 return;
1367 }
1368
1369 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
1370 if (pkgOps == null) {
1371 return;
1372 }
1373
Svet Ganovaf189e32019-02-15 18:45:29 -08001374 boolean scheduleWrite = false;
1375
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001376 int numPkgs = pkgOps.size();
1377 for (int pkgNum = 0; pkgNum < numPkgs; pkgNum++) {
1378 Ops ops = pkgOps.valueAt(pkgNum);
1379
1380 Op op = ops.get(code);
1381 if (op == null) {
1382 continue;
1383 }
1384
1385 int defaultMode = AppOpsManager.opToDefaultMode(code);
1386 if (op.mode != defaultMode) {
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001387 op.mode = defaultMode;
Svet Ganovaf189e32019-02-15 18:45:29 -08001388 scheduleWrite = true;
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001389 }
1390 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001391
1392 if (scheduleWrite) {
1393 scheduleWriteLocked();
1394 }
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001395 }
1396 }
1397
Svet Ganov2af57082015-07-30 08:44:20 -07001398 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001399 public void setMode(int code, int uid, String packageName, int mode) {
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07001400 setMode(code, uid, packageName, mode, true, false);
1401 }
1402
1403 /**
1404 * Sets the mode for a certain op and uid.
1405 *
1406 * @param code The op code to set
1407 * @param uid The UID for which to set
1408 * @param packageName The package for which to set
1409 * @param mode The new mode to set
1410 * @param verifyUid Iff {@code true}, check that the package name belongs to the uid
1411 * @param isPrivileged Whether the package is privileged. (Only used if {@code verifyUid ==
1412 * false})
1413 */
1414 private void setMode(int code, int uid, @NonNull String packageName, int mode,
1415 boolean verifyUid, boolean isPrivileged) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07001416 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001417 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001418 ArraySet<ModeCallback> repCbs = null;
Dianne Hackbornc2293022013-02-06 23:14:49 -08001419 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001420 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -07001421 UidState uidState = getUidStateLocked(uid, false);
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07001422 Op op = getOpLocked(code, uid, packageName, true, verifyUid, isPrivileged);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001423 if (op != null) {
1424 if (op.mode != mode) {
1425 op.mode = mode;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001426 if (uidState != null) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001427 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001428 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001429 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001430 if (cbs != null) {
1431 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001432 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001433 }
1434 repCbs.addAll(cbs);
1435 }
1436 cbs = mPackageModeWatchers.get(packageName);
1437 if (cbs != null) {
1438 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001439 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001440 }
1441 repCbs.addAll(cbs);
1442 }
David Braunf5d83192013-09-16 13:43:51 -07001443 if (mode == AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001444 // If going into the default mode, prune this op
1445 // if there is nothing else interesting in it.
Dianne Hackborn607b4142013-08-02 18:10:10 -07001446 pruneOp(op, uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001447 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001448 scheduleFastWriteLocked();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001449 }
1450 }
1451 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001452 if (repCbs != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001453 mHandler.sendMessage(PooledLambda.obtainMessage(
1454 AppOpsService::notifyOpChanged,
1455 this, repCbs, code, uid, packageName));
Dianne Hackbornc2293022013-02-06 23:14:49 -08001456 }
Sudheer Shankab1613982019-05-16 16:55:50 -07001457
1458 notifyOpChangedSync(code, uid, packageName, mode);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001459 }
1460
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001461 private void notifyOpChanged(ArraySet<ModeCallback> callbacks, int code,
1462 int uid, String packageName) {
1463 for (int i = 0; i < callbacks.size(); i++) {
1464 final ModeCallback callback = callbacks.valueAt(i);
1465 notifyOpChanged(callback, code, uid, packageName);
1466 }
1467 }
1468
1469 private void notifyOpChanged(ModeCallback callback, int code,
1470 int uid, String packageName) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001471 if (uid != UID_ANY && callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001472 return;
1473 }
1474 // There are components watching for mode changes such as window manager
1475 // and location manager which are in our process. The callbacks in these
1476 // components may require permissions our remote caller does not have.
1477 final long identity = Binder.clearCallingIdentity();
1478 try {
1479 callback.mCallback.opChanged(code, uid, packageName);
1480 } catch (RemoteException e) {
1481 /* ignore */
1482 } finally {
1483 Binder.restoreCallingIdentity(identity);
1484 }
1485 }
1486
1487 private static HashMap<ModeCallback, ArrayList<ChangeRec>> addCallbacks(
1488 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks,
1489 int op, int uid, String packageName, ArraySet<ModeCallback> cbs) {
Dianne Hackborn607b4142013-08-02 18:10:10 -07001490 if (cbs == null) {
1491 return callbacks;
1492 }
1493 if (callbacks == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001494 callbacks = new HashMap<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001495 }
Svet Ganov2af57082015-07-30 08:44:20 -07001496 boolean duplicate = false;
Dianne Hackborn68d76552017-02-27 15:32:03 -08001497 final int N = cbs.size();
1498 for (int i=0; i<N; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001499 ModeCallback cb = cbs.valueAt(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001500 ArrayList<ChangeRec> reports = callbacks.get(cb);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001501 if (reports == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001502 reports = new ArrayList<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001503 callbacks.put(cb, reports);
Svet Ganov2af57082015-07-30 08:44:20 -07001504 } else {
1505 final int reportCount = reports.size();
1506 for (int j = 0; j < reportCount; j++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001507 ChangeRec report = reports.get(j);
1508 if (report.op == op && report.pkg.equals(packageName)) {
Svet Ganov2af57082015-07-30 08:44:20 -07001509 duplicate = true;
1510 break;
1511 }
1512 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001513 }
Svet Ganov2af57082015-07-30 08:44:20 -07001514 if (!duplicate) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001515 reports.add(new ChangeRec(op, uid, packageName));
Svet Ganov2af57082015-07-30 08:44:20 -07001516 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001517 }
1518 return callbacks;
1519 }
1520
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001521 static final class ChangeRec {
1522 final int op;
1523 final int uid;
1524 final String pkg;
1525
1526 ChangeRec(int _op, int _uid, String _pkg) {
1527 op = _op;
1528 uid = _uid;
1529 pkg = _pkg;
1530 }
1531 }
1532
Dianne Hackborn607b4142013-08-02 18:10:10 -07001533 @Override
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001534 public void resetAllModes(int reqUserId, String reqPackageName) {
1535 final int callingPid = Binder.getCallingPid();
1536 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001537 reqUserId = ActivityManager.handleIncomingUser(callingPid, callingUid, reqUserId,
1538 true, true, "resetAllModes", null);
Svet Ganov2af57082015-07-30 08:44:20 -07001539
1540 int reqUid = -1;
1541 if (reqPackageName != null) {
1542 try {
1543 reqUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -07001544 reqPackageName, PackageManager.MATCH_UNINSTALLED_PACKAGES, reqUserId);
Svet Ganov2af57082015-07-30 08:44:20 -07001545 } catch (RemoteException e) {
1546 /* ignore - local call */
1547 }
1548 }
1549
Dianne Hackbornd5254412018-05-11 18:02:58 -07001550 enforceManageAppOpsModes(callingPid, callingUid, reqUid);
1551
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001552 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks = null;
Dianne Hackborn607b4142013-08-02 18:10:10 -07001553 synchronized (this) {
1554 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -07001555 for (int i = mUidStates.size() - 1; i >= 0; i--) {
1556 UidState uidState = mUidStates.valueAt(i);
1557
1558 SparseIntArray opModes = uidState.opModes;
1559 if (opModes != null && (uidState.uid == reqUid || reqUid == -1)) {
1560 final int uidOpCount = opModes.size();
1561 for (int j = uidOpCount - 1; j >= 0; j--) {
1562 final int code = opModes.keyAt(j);
1563 if (AppOpsManager.opAllowsReset(code)) {
1564 opModes.removeAt(j);
1565 if (opModes.size() <= 0) {
1566 uidState.opModes = null;
1567 }
1568 for (String packageName : getPackagesForUid(uidState.uid)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001569 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -07001570 mOpModeWatchers.get(code));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001571 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -07001572 mPackageModeWatchers.get(packageName));
1573 }
1574 }
1575 }
1576 }
1577
1578 if (uidState.pkgOps == null) {
1579 continue;
1580 }
1581
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001582 if (reqUserId != UserHandle.USER_ALL
Svet Ganov2af57082015-07-30 08:44:20 -07001583 && reqUserId != UserHandle.getUserId(uidState.uid)) {
Alexandra Gherghinad6a98972014-08-04 17:05:34 +01001584 // Skip any ops for a different user
1585 continue;
1586 }
Svet Ganov2af57082015-07-30 08:44:20 -07001587
1588 Map<String, Ops> packages = uidState.pkgOps;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001589 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001590 boolean uidChanged = false;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001591 while (it.hasNext()) {
1592 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001593 String packageName = ent.getKey();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001594 if (reqPackageName != null && !reqPackageName.equals(packageName)) {
1595 // Skip any ops for a different package
1596 continue;
1597 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001598 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001599 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -07001600 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -07001601 if (AppOpsManager.opAllowsReset(curOp.op)
1602 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -07001603 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001604 changed = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001605 uidChanged = true;
Svet Ganovaf189e32019-02-15 18:45:29 -08001606 final int uid = curOp.uidState.uid;
1607 callbacks = addCallbacks(callbacks, curOp.op, uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -07001608 mOpModeWatchers.get(curOp.op));
Svet Ganovaf189e32019-02-15 18:45:29 -08001609 callbacks = addCallbacks(callbacks, curOp.op, uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -07001610 mPackageModeWatchers.get(packageName));
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001611 if (!curOp.hasAnyTime()) {
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001612 pkgOps.removeAt(j);
1613 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001614 }
1615 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001616 if (pkgOps.size() == 0) {
1617 it.remove();
1618 }
1619 }
Svet Ganov2af57082015-07-30 08:44:20 -07001620 if (uidState.isDefault()) {
1621 mUidStates.remove(uidState.uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001622 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001623 if (uidChanged) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001624 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001625 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001626 }
Svet Ganov2af57082015-07-30 08:44:20 -07001627
Dianne Hackborn607b4142013-08-02 18:10:10 -07001628 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001629 scheduleFastWriteLocked();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001630 }
1631 }
1632 if (callbacks != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001633 for (Map.Entry<ModeCallback, ArrayList<ChangeRec>> ent : callbacks.entrySet()) {
1634 ModeCallback cb = ent.getKey();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001635 ArrayList<ChangeRec> reports = ent.getValue();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001636 for (int i=0; i<reports.size(); i++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001637 ChangeRec rep = reports.get(i);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001638 mHandler.sendMessage(PooledLambda.obtainMessage(
1639 AppOpsService::notifyOpChanged,
1640 this, cb, rep.op, rep.uid, rep.pkg));
Dianne Hackborn607b4142013-08-02 18:10:10 -07001641 }
1642 }
1643 }
1644 }
1645
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001646 private void evalAllForegroundOpsLocked() {
1647 for (int uidi = mUidStates.size() - 1; uidi >= 0; uidi--) {
1648 final UidState uidState = mUidStates.valueAt(uidi);
1649 if (uidState.foregroundOps != null) {
1650 uidState.evalForegroundOps(mOpModeWatchers);
1651 }
1652 }
1653 }
1654
Dianne Hackbornc2293022013-02-06 23:14:49 -08001655 @Override
1656 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001657 startWatchingModeWithFlags(op, packageName, 0, callback);
1658 }
1659
1660 @Override
1661 public void startWatchingModeWithFlags(int op, String packageName, int flags,
1662 IAppOpsCallback callback) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001663 int watchedUid = -1;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001664 final int callingUid = Binder.getCallingUid();
1665 final int callingPid = Binder.getCallingPid();
Dianne Hackborn5376edd2018-06-05 13:21:16 -07001666 // TODO: should have a privileged permission to protect this.
1667 // Also, if the caller has requested WATCH_FOREGROUND_CHANGES, should we require
1668 // the USAGE_STATS permission since this can provide information about when an
1669 // app is in the foreground?
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001670 Preconditions.checkArgumentInRange(op, AppOpsManager.OP_NONE,
1671 AppOpsManager._NUM_OP - 1, "Invalid op code: " + op);
Svetoslav Ganov8de59712015-12-09 18:25:13 -08001672 if (callback == null) {
1673 return;
1674 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001675 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -07001676 op = (op != AppOpsManager.OP_NONE) ? AppOpsManager.opToSwitch(op) : op;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001677 ModeCallback cb = mModeWatchers.get(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -08001678 if (cb == null) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001679 cb = new ModeCallback(callback, watchedUid, flags, callingUid, callingPid);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001680 mModeWatchers.put(callback.asBinder(), cb);
1681 }
1682 if (op != AppOpsManager.OP_NONE) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001683 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(op);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001684 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08001685 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001686 mOpModeWatchers.put(op, cbs);
1687 }
1688 cbs.add(cb);
1689 }
1690 if (packageName != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001691 ArraySet<ModeCallback> cbs = mPackageModeWatchers.get(packageName);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001692 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08001693 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001694 mPackageModeWatchers.put(packageName, cbs);
1695 }
1696 cbs.add(cb);
1697 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001698 evalAllForegroundOpsLocked();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001699 }
1700 }
1701
1702 @Override
1703 public void stopWatchingMode(IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -08001704 if (callback == null) {
1705 return;
1706 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001707 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001708 ModeCallback cb = mModeWatchers.remove(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -08001709 if (cb != null) {
1710 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001711 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001712 ArraySet<ModeCallback> cbs = mOpModeWatchers.valueAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001713 cbs.remove(cb);
1714 if (cbs.size() <= 0) {
1715 mOpModeWatchers.removeAt(i);
1716 }
1717 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001718 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001719 ArraySet<ModeCallback> cbs = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001720 cbs.remove(cb);
1721 if (cbs.size() <= 0) {
1722 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001723 }
1724 }
1725 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001726 evalAllForegroundOpsLocked();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001727 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001728 }
1729
1730 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001731 public IBinder getToken(IBinder clientToken) {
1732 synchronized (this) {
1733 ClientState cs = mClients.get(clientToken);
1734 if (cs == null) {
1735 cs = new ClientState(clientToken);
1736 mClients.put(clientToken, cs);
1737 }
1738 return cs;
1739 }
1740 }
1741
Svet Ganovd873ae62018-06-25 16:39:23 -07001742 public CheckOpsDelegate getAppOpsServiceDelegate() {
1743 synchronized (this) {
1744 return mCheckOpsDelegate;
1745 }
1746 }
1747
1748 public void setAppOpsServiceDelegate(CheckOpsDelegate delegate) {
1749 synchronized (this) {
1750 mCheckOpsDelegate = delegate;
1751 }
1752 }
1753
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001754 @Override
Svet Ganov9d528a12018-12-19 17:23:11 -08001755 public int checkOperationRaw(int code, int uid, String packageName) {
1756 return checkOperationInternal(code, uid, packageName, true /*raw*/);
1757 }
1758
1759 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -08001760 public int checkOperation(int code, int uid, String packageName) {
Svet Ganov9d528a12018-12-19 17:23:11 -08001761 return checkOperationInternal(code, uid, packageName, false /*raw*/);
1762 }
1763
1764 private int checkOperationInternal(int code, int uid, String packageName, boolean raw) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001765 final CheckOpsDelegate delegate;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001766 synchronized (this) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001767 delegate = mCheckOpsDelegate;
1768 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001769 if (delegate == null) {
Svet Ganov9d528a12018-12-19 17:23:11 -08001770 return checkOperationImpl(code, uid, packageName, raw);
Todd Kennedy556efba2018-11-15 07:43:55 -08001771 }
Svet Ganov9d528a12018-12-19 17:23:11 -08001772 return delegate.checkOperation(code, uid, packageName, raw,
Svet Ganovd873ae62018-06-25 16:39:23 -07001773 AppOpsService.this::checkOperationImpl);
1774 }
1775
Svet Ganov9d528a12018-12-19 17:23:11 -08001776 private int checkOperationImpl(int code, int uid, String packageName,
1777 boolean raw) {
Todd Kennedy556efba2018-11-15 07:43:55 -08001778 verifyIncomingUid(uid);
1779 verifyIncomingOp(code);
1780 String resolvedPackageName = resolvePackageName(uid, packageName);
1781 if (resolvedPackageName == null) {
1782 return AppOpsManager.MODE_IGNORED;
1783 }
Svet Ganov9d528a12018-12-19 17:23:11 -08001784 return checkOperationUnchecked(code, uid, resolvedPackageName, raw);
Todd Kennedy556efba2018-11-15 07:43:55 -08001785 }
1786
Philip P. Moltmann724150d2019-03-11 17:01:05 -07001787 /**
1788 * @see #checkOperationUnchecked(int, int, String, boolean, boolean)
1789 */
1790 private @Mode int checkOperationUnchecked(int code, int uid, @NonNull String packageName,
1791 boolean raw) {
1792 return checkOperationUnchecked(code, uid, packageName, raw, true);
1793 }
1794
1795 /**
1796 * Get the mode of an app-op.
1797 *
1798 * @param code The code of the op
1799 * @param uid The uid of the package the op belongs to
1800 * @param packageName The package the op belongs to
1801 * @param raw If the raw state of eval-ed state should be checked.
1802 * @param verify If the code should check the package belongs to the uid
1803 *
1804 * @return The mode of the op
1805 */
1806 private @Mode int checkOperationUnchecked(int code, int uid, @NonNull String packageName,
1807 boolean raw, boolean verify) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001808 synchronized (this) {
Philip P. Moltmann724150d2019-03-11 17:01:05 -07001809 if (verify) {
1810 checkPackage(uid, packageName);
1811 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001812 if (isOpRestrictedLocked(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001813 return AppOpsManager.MODE_IGNORED;
1814 }
Svet Ganov2af57082015-07-30 08:44:20 -07001815 code = AppOpsManager.opToSwitch(code);
1816 UidState uidState = getUidStateLocked(uid, false);
Svet Ganovee438d42017-01-19 18:04:38 -08001817 if (uidState != null && uidState.opModes != null
1818 && uidState.opModes.indexOfKey(code) >= 0) {
Svet Ganov9d528a12018-12-19 17:23:11 -08001819 final int rawMode = uidState.opModes.get(code);
Svet Ganovaf189e32019-02-15 18:45:29 -08001820 return raw ? rawMode : uidState.evalMode(code, rawMode);
Svet Ganov2af57082015-07-30 08:44:20 -07001821 }
Philip P. Moltmann724150d2019-03-11 17:01:05 -07001822 Op op = getOpLocked(code, uid, packageName, false, verify, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001823 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -07001824 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001825 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001826 return raw ? op.mode : op.evalMode();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001827 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001828 }
1829
1830 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001831 public int checkAudioOperation(int code, int usage, int uid, String packageName) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001832 final CheckOpsDelegate delegate;
John Spurlock1af30c72014-03-10 08:33:35 -04001833 synchronized (this) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001834 delegate = mCheckOpsDelegate;
1835 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001836 if (delegate == null) {
1837 return checkAudioOperationImpl(code, usage, uid, packageName);
1838 }
Svet Ganovd873ae62018-06-25 16:39:23 -07001839 return delegate.checkAudioOperation(code, usage, uid, packageName,
1840 AppOpsService.this::checkAudioOperationImpl);
1841 }
1842
1843 private int checkAudioOperationImpl(int code, int usage, int uid, String packageName) {
Todd Kennedy556efba2018-11-15 07:43:55 -08001844 boolean suspended;
1845 try {
1846 suspended = isPackageSuspendedForUser(packageName, uid);
1847 } catch (IllegalArgumentException ex) {
1848 // Package not found.
1849 suspended = false;
1850 }
1851
1852 if (suspended) {
1853 Slog.i(TAG, "Audio disabled for suspended package=" + packageName
1854 + " for uid=" + uid);
1855 return AppOpsManager.MODE_IGNORED;
1856 }
1857
Svet Ganovd873ae62018-06-25 16:39:23 -07001858 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001859 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -04001860 if (mode != AppOpsManager.MODE_ALLOWED) {
1861 return mode;
1862 }
1863 }
1864 return checkOperation(code, uid, packageName);
1865 }
1866
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001867 private boolean isPackageSuspendedForUser(String pkg, int uid) {
Svet Ganov8d123f42019-04-09 17:11:12 -07001868 final long identity = Binder.clearCallingIdentity();
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001869 try {
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001870 return AppGlobals.getPackageManager().isPackageSuspendedForUser(
1871 pkg, UserHandle.getUserId(uid));
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001872 } catch (RemoteException re) {
1873 throw new SecurityException("Could not talk to package manager service");
Svet Ganov8d123f42019-04-09 17:11:12 -07001874 } finally {
1875 Binder.restoreCallingIdentity(identity);
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001876 }
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001877 }
1878
John Spurlock7b414672014-07-18 13:02:39 -04001879 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
1880 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1881 if (usageRestrictions != null) {
1882 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001883 if (r != null && !r.exceptionPackages.contains(packageName)) {
1884 return r.mode;
1885 }
1886 }
1887 return AppOpsManager.MODE_ALLOWED;
1888 }
1889
1890 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001891 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -04001892 String[] exceptionPackages) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07001893 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
John Spurlock1af30c72014-03-10 08:33:35 -04001894 verifyIncomingUid(uid);
1895 verifyIncomingOp(code);
1896 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001897 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1898 if (usageRestrictions == null) {
1899 usageRestrictions = new SparseArray<Restriction>();
1900 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -04001901 }
John Spurlock7b414672014-07-18 13:02:39 -04001902 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001903 if (mode != AppOpsManager.MODE_ALLOWED) {
1904 final Restriction r = new Restriction();
1905 r.mode = mode;
1906 if (exceptionPackages != null) {
1907 final int N = exceptionPackages.length;
1908 r.exceptionPackages = new ArraySet<String>(N);
1909 for (int i = 0; i < N; i++) {
1910 final String pkg = exceptionPackages[i];
1911 if (pkg != null) {
1912 r.exceptionPackages.add(pkg.trim());
1913 }
1914 }
1915 }
John Spurlock7b414672014-07-18 13:02:39 -04001916 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -04001917 }
1918 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001919
1920 mHandler.sendMessage(PooledLambda.obtainMessage(
Svet Ganov3a95f832018-03-23 17:44:30 -07001921 AppOpsService::notifyWatchersOfChange, this, code, UID_ANY));
John Spurlock1af30c72014-03-10 08:33:35 -04001922 }
1923
1924 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001925 public int checkPackage(int uid, String packageName) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001926 Preconditions.checkNotNull(packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001927 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001928 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1929 true /* uidMismatchExpected */);
1930 if (ops != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001931 return AppOpsManager.MODE_ALLOWED;
1932 } else {
1933 return AppOpsManager.MODE_ERRORED;
1934 }
1935 }
1936 }
1937
1938 @Override
Svet Ganovd873ae62018-06-25 16:39:23 -07001939 public int noteProxyOperation(int code, int proxyUid,
1940 String proxyPackageName, int proxiedUid, String proxiedPackageName) {
1941 verifyIncomingUid(proxyUid);
Svet Ganov99b60432015-06-27 13:15:22 -07001942 verifyIncomingOp(code);
Svet Ganovaf189e32019-02-15 18:45:29 -08001943
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001944 String resolveProxyPackageName = resolvePackageName(proxyUid, proxyPackageName);
1945 if (resolveProxyPackageName == null) {
1946 return AppOpsManager.MODE_IGNORED;
1947 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001948
1949 final boolean isProxyTrusted = mContext.checkPermission(
1950 Manifest.permission.UPDATE_APP_OPS_STATS, -1, proxyUid)
1951 == PackageManager.PERMISSION_GRANTED;
1952
1953 final int proxyFlags = isProxyTrusted ? AppOpsManager.OP_FLAG_TRUSTED_PROXY
1954 : AppOpsManager.OP_FLAG_UNTRUSTED_PROXY;
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001955 final int proxyMode = noteOperationUnchecked(code, proxyUid,
Svet Ganovaf189e32019-02-15 18:45:29 -08001956 resolveProxyPackageName, Process.INVALID_UID, null, proxyFlags);
Svet Ganov99b60432015-06-27 13:15:22 -07001957 if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
1958 return proxyMode;
1959 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001960
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001961 String resolveProxiedPackageName = resolvePackageName(proxiedUid, proxiedPackageName);
1962 if (resolveProxiedPackageName == null) {
1963 return AppOpsManager.MODE_IGNORED;
1964 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001965 final int proxiedFlags = isProxyTrusted ? AppOpsManager.OP_FLAG_TRUSTED_PROXIED
1966 : AppOpsManager.OP_FLAG_UNTRUSTED_PROXIED;
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001967 return noteOperationUnchecked(code, proxiedUid, resolveProxiedPackageName,
Svet Ganovaf189e32019-02-15 18:45:29 -08001968 proxyUid, resolveProxyPackageName, proxiedFlags);
Svet Ganov99b60432015-06-27 13:15:22 -07001969 }
1970
1971 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001972 public int noteOperation(int code, int uid, String packageName) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001973 final CheckOpsDelegate delegate;
1974 synchronized (this) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001975 delegate = mCheckOpsDelegate;
1976 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001977 if (delegate == null) {
1978 return noteOperationImpl(code, uid, packageName);
1979 }
Svet Ganovd873ae62018-06-25 16:39:23 -07001980 return delegate.noteOperation(code, uid, packageName,
1981 AppOpsService.this::noteOperationImpl);
1982 }
1983
1984 private int noteOperationImpl(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001985 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001986 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001987 String resolvedPackageName = resolvePackageName(uid, packageName);
1988 if (resolvedPackageName == null) {
1989 return AppOpsManager.MODE_IGNORED;
1990 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001991 return noteOperationUnchecked(code, uid, resolvedPackageName, Process.INVALID_UID, null,
1992 AppOpsManager.OP_FLAG_SELF);
Svet Ganov99b60432015-06-27 13:15:22 -07001993 }
1994
1995 private int noteOperationUnchecked(int code, int uid, String packageName,
Svet Ganovaf189e32019-02-15 18:45:29 -08001996 int proxyUid, String proxyPackageName, @OpFlags int flags) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001997 synchronized (this) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001998 final Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
Yohei Yukawaa965d652017-10-12 15:02:26 -07001999 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002000 if (ops == null) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002001 scheduleOpNotedIfNeededLocked(code, uid, packageName,
2002 AppOpsManager.MODE_IGNORED);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002003 if (DEBUG) Slog.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002004 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07002005 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002006 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002007 final Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07002008 if (isOpRestrictedLocked(uid, code, packageName)) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002009 scheduleOpNotedIfNeededLocked(code, uid, packageName,
2010 AppOpsManager.MODE_IGNORED);
Jason Monk62062992014-05-06 09:55:28 -04002011 return AppOpsManager.MODE_IGNORED;
2012 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002013 final UidState uidState = ops.uidState;
Svet Ganovaf189e32019-02-15 18:45:29 -08002014 if (op.running) {
2015 final OpEntry entry = new OpEntry(op.op, op.running, op.mode, op.mAccessTimes,
2016 op.mRejectTimes, op.mDurations, op.mProxyUids, op.mProxyPackageNames);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002017 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
Svet Ganovaf189e32019-02-15 18:45:29 -08002018 + " code " + code + " time=" + entry.getLastAccessTime(uidState.state,
2019 uidState.state, flags) + " duration=" + entry.getLastDuration(
2020 uidState.state, uidState.state, flags));
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002021 }
Svet Ganovaf189e32019-02-15 18:45:29 -08002022
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002023 final int switchCode = AppOpsManager.opToSwitch(code);
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07002024 // If there is a non-default per UID policy (we set UID op mode only if
2025 // non-default) it takes over, otherwise use the per package policy.
2026 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002027 final int uidMode = uidState.evalMode(code, uidState.opModes.get(switchCode));
Svet Ganov2af57082015-07-30 08:44:20 -07002028 if (uidMode != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002029 if (DEBUG) Slog.d(TAG, "noteOperation: uid reject #" + uidMode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07002030 + switchCode + " (" + code + ") uid " + uid + " package "
2031 + packageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08002032 op.rejected(System.currentTimeMillis(), proxyUid, proxyPackageName,
2033 uidState.state, flags);
2034 mHistoricalRegistry.incrementOpRejected(code, uid, packageName,
2035 uidState.state, flags);
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002036 scheduleOpNotedIfNeededLocked(code, uid, packageName, uidMode);
Svet Ganov2af57082015-07-30 08:44:20 -07002037 return uidMode;
2038 }
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07002039 } else {
2040 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
Svet Ganovaf189e32019-02-15 18:45:29 -08002041 final int mode = switchOp.evalMode();
2042 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002043 if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + mode + " for code "
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07002044 + switchCode + " (" + code + ") uid " + uid + " package "
2045 + packageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08002046 op.rejected(System.currentTimeMillis(), proxyUid, proxyPackageName,
2047 uidState.state, flags);
2048 mHistoricalRegistry.incrementOpRejected(code, uid, packageName,
2049 uidState.state, flags);
2050 scheduleOpNotedIfNeededLocked(code, uid, packageName, mode);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002051 return mode;
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07002052 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002053 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002054 if (DEBUG) Slog.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002055 + " package " + packageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08002056 op.accessed(System.currentTimeMillis(), proxyUid, proxyPackageName,
2057 uidState.state, flags);
Svet Ganov8455ba22019-01-02 13:05:56 -08002058 mHistoricalRegistry.incrementOpAccessedCount(op.op, uid, packageName,
Svet Ganovaf189e32019-02-15 18:45:29 -08002059 uidState.state, flags);
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002060 scheduleOpNotedIfNeededLocked(code, uid, packageName,
2061 AppOpsManager.MODE_ALLOWED);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002062 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002063 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002064 }
2065
2066 @Override
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002067 public void startWatchingActive(int[] ops, IAppOpsActiveCallback callback) {
Svet Ganovf7b47252018-02-26 11:11:27 -08002068 int watchedUid = -1;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002069 final int callingUid = Binder.getCallingUid();
2070 final int callingPid = Binder.getCallingPid();
Svet Ganovf7b47252018-02-26 11:11:27 -08002071 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
2072 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002073 watchedUid = callingUid;
Svet Ganovf7b47252018-02-26 11:11:27 -08002074 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002075 if (ops != null) {
2076 Preconditions.checkArrayElementsInRange(ops, 0,
2077 AppOpsManager._NUM_OP - 1, "Invalid op code in: " + Arrays.toString(ops));
2078 }
2079 if (callback == null) {
2080 return;
2081 }
2082 synchronized (this) {
2083 SparseArray<ActiveCallback> callbacks = mActiveWatchers.get(callback.asBinder());
2084 if (callbacks == null) {
2085 callbacks = new SparseArray<>();
2086 mActiveWatchers.put(callback.asBinder(), callbacks);
2087 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002088 final ActiveCallback activeCallback = new ActiveCallback(callback, watchedUid,
2089 callingUid, callingPid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002090 for (int op : ops) {
2091 callbacks.put(op, activeCallback);
2092 }
2093 }
2094 }
2095
2096 @Override
2097 public void stopWatchingActive(IAppOpsActiveCallback callback) {
2098 if (callback == null) {
2099 return;
2100 }
2101 synchronized (this) {
2102 final SparseArray<ActiveCallback> activeCallbacks =
2103 mActiveWatchers.remove(callback.asBinder());
2104 if (activeCallbacks == null) {
2105 return;
2106 }
2107 final int callbackCount = activeCallbacks.size();
2108 for (int i = 0; i < callbackCount; i++) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002109 activeCallbacks.valueAt(i).destroy();
2110 }
2111 }
2112 }
2113
2114 @Override
2115 public void startWatchingNoted(@NonNull int[] ops, @NonNull IAppOpsNotedCallback callback) {
2116 int watchedUid = Process.INVALID_UID;
2117 final int callingUid = Binder.getCallingUid();
2118 final int callingPid = Binder.getCallingPid();
2119 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
2120 != PackageManager.PERMISSION_GRANTED) {
2121 watchedUid = callingUid;
2122 }
2123 Preconditions.checkArgument(!ArrayUtils.isEmpty(ops), "Ops cannot be null or empty");
2124 Preconditions.checkArrayElementsInRange(ops, 0, AppOpsManager._NUM_OP - 1,
2125 "Invalid op code in: " + Arrays.toString(ops));
2126 Preconditions.checkNotNull(callback, "Callback cannot be null");
2127 synchronized (this) {
2128 SparseArray<NotedCallback> callbacks = mNotedWatchers.get(callback.asBinder());
2129 if (callbacks == null) {
2130 callbacks = new SparseArray<>();
2131 mNotedWatchers.put(callback.asBinder(), callbacks);
2132 }
2133 final NotedCallback notedCallback = new NotedCallback(callback, watchedUid,
2134 callingUid, callingPid);
2135 for (int op : ops) {
2136 callbacks.put(op, notedCallback);
2137 }
2138 }
2139 }
2140
2141 @Override
2142 public void stopWatchingNoted(IAppOpsNotedCallback callback) {
2143 Preconditions.checkNotNull(callback, "Callback cannot be null");
2144 synchronized (this) {
2145 final SparseArray<NotedCallback> notedCallbacks =
2146 mNotedWatchers.remove(callback.asBinder());
2147 if (notedCallbacks == null) {
2148 return;
2149 }
2150 final int callbackCount = notedCallbacks.size();
2151 for (int i = 0; i < callbackCount; i++) {
2152 notedCallbacks.valueAt(i).destroy();
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002153 }
2154 }
2155 }
2156
2157 @Override
Svet Ganovf7b47252018-02-26 11:11:27 -08002158 public int startOperation(IBinder token, int code, int uid, String packageName,
2159 boolean startIfModeDefault) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002160 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08002161 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002162 String resolvedPackageName = resolvePackageName(uid, packageName);
2163 if (resolvedPackageName == null) {
2164 return AppOpsManager.MODE_IGNORED;
2165 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002166 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002167 synchronized (this) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002168 final Ops ops = getOpsRawLocked(uid, resolvedPackageName, true /* edit */,
Yohei Yukawaa965d652017-10-12 15:02:26 -07002169 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002170 if (ops == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002171 if (DEBUG) Slog.d(TAG, "startOperation: no op for code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002172 + " package " + resolvedPackageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07002173 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002174 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002175 final Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07002176 if (isOpRestrictedLocked(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -04002177 return AppOpsManager.MODE_IGNORED;
2178 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002179 final int switchCode = AppOpsManager.opToSwitch(code);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002180 final UidState uidState = ops.uidState;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002181 // If there is a non-default per UID policy (we set UID op mode only if
2182 // non-default) it takes over, otherwise use the per package policy.
Svet Ganovaf189e32019-02-15 18:45:29 -08002183 final int opCode = op.op;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002184 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002185 final int uidMode = uidState.evalMode(code, uidState.opModes.get(switchCode));
Svet Ganovf7b47252018-02-26 11:11:27 -08002186 if (uidMode != AppOpsManager.MODE_ALLOWED
2187 && (!startIfModeDefault || uidMode != AppOpsManager.MODE_DEFAULT)) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002188 if (DEBUG) Slog.d(TAG, "noteOperation: uid reject #" + uidMode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07002189 + switchCode + " (" + code + ") uid " + uid + " package "
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002190 + resolvedPackageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08002191 // We don't support proxy long running ops (start/stop)
2192 op.rejected(System.currentTimeMillis(), -1 /*proxyUid*/,
2193 null /*proxyPackage*/, uidState.state, AppOpsManager.OP_FLAG_SELF);
2194 mHistoricalRegistry.incrementOpRejected(opCode, uid, packageName,
2195 uidState.state, AppOpsManager.OP_FLAG_SELF);
Svet Ganov2af57082015-07-30 08:44:20 -07002196 return uidMode;
2197 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002198 } else {
2199 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
Svet Ganovaf189e32019-02-15 18:45:29 -08002200 final int mode = switchOp.evalMode();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002201 if (mode != AppOpsManager.MODE_ALLOWED
2202 && (!startIfModeDefault || mode != AppOpsManager.MODE_DEFAULT)) {
2203 if (DEBUG) Slog.d(TAG, "startOperation: reject #" + mode + " for code "
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002204 + switchCode + " (" + code + ") uid " + uid + " package "
2205 + resolvedPackageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08002206 // We don't support proxy long running ops (start/stop)
2207 op.rejected(System.currentTimeMillis(), -1 /*proxyUid*/,
2208 null /*proxyPackage*/, uidState.state, AppOpsManager.OP_FLAG_SELF);
2209 mHistoricalRegistry.incrementOpRejected(opCode, uid, packageName,
2210 uidState.state, AppOpsManager.OP_FLAG_SELF);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002211 return mode;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002212 }
Svet Ganov2af57082015-07-30 08:44:20 -07002213 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002214 if (DEBUG) Slog.d(TAG, "startOperation: allowing code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002215 + " package " + resolvedPackageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002216 if (op.startNesting == 0) {
2217 op.startRealtime = SystemClock.elapsedRealtime();
Svet Ganovaf189e32019-02-15 18:45:29 -08002218 // We don't support proxy long running ops (start/stop)
2219 op.started(System.currentTimeMillis(), uidState.state,
2220 AppOpsManager.OP_FLAG_SELF);
2221 mHistoricalRegistry.incrementOpAccessedCount(opCode, uid, packageName,
2222 uidState.state, AppOpsManager.OP_FLAG_SELF);
2223
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002224 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002225 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002226 op.startNesting++;
2227 uidState.startNesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002228 if (client.mStartedOps != null) {
2229 client.mStartedOps.add(op);
2230 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002231 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002232
2233 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002234 }
2235
2236 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002237 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002238 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08002239 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002240 String resolvedPackageName = resolvePackageName(uid, packageName);
2241 if (resolvedPackageName == null) {
2242 return;
2243 }
2244 if (!(token instanceof ClientState)) {
2245 return;
2246 }
2247 ClientState client = (ClientState) token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002248 synchronized (this) {
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07002249 Op op = getOpLocked(code, uid, resolvedPackageName, true, true, false);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002250 if (op == null) {
2251 return;
2252 }
Svet Ganovf7b47252018-02-26 11:11:27 -08002253 if (!client.mStartedOps.remove(op)) {
Svet Ganovf5d5af12018-03-18 11:51:17 -07002254 // We finish ops when packages get removed to guarantee no dangling
2255 // started ops. However, some part of the system may asynchronously
2256 // finish ops for an already gone package. Hence, finishing an op
2257 // for a non existing package is fine and we don't log as a wtf.
2258 final long identity = Binder.clearCallingIdentity();
2259 try {
2260 if (LocalServices.getService(PackageManagerInternal.class).getPackageUid(
2261 resolvedPackageName, 0, UserHandle.getUserId(uid)) < 0) {
2262 Slog.i(TAG, "Finishing op=" + AppOpsManager.opToName(code)
2263 + " for non-existing package=" + resolvedPackageName
2264 + " in uid=" + uid);
2265 return;
2266 }
2267 } finally {
2268 Binder.restoreCallingIdentity(identity);
2269 }
Svet Ganovaf189e32019-02-15 18:45:29 -08002270 Slog.wtf(TAG, "Operation not started: uid=" + op.uidState.uid + " pkg="
Svet Ganovf5d5af12018-03-18 11:51:17 -07002271 + op.packageName + " op=" + AppOpsManager.opToName(op.op));
Svet Ganov31d83ae2018-03-15 10:45:56 -07002272 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002273 }
Svet Ganova7a0db62018-02-27 20:08:01 -08002274 finishOperationLocked(op, /*finishNested*/ false);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002275 if (op.startNesting <= 0) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002276 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, false);
2277 }
2278 }
2279 }
2280
2281 private void scheduleOpActiveChangedIfNeededLocked(int code, int uid, String packageName,
2282 boolean active) {
2283 ArraySet<ActiveCallback> dispatchedCallbacks = null;
2284 final int callbackListCount = mActiveWatchers.size();
2285 for (int i = 0; i < callbackListCount; i++) {
2286 final SparseArray<ActiveCallback> callbacks = mActiveWatchers.valueAt(i);
2287 ActiveCallback callback = callbacks.get(code);
2288 if (callback != null) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002289 if (callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
Svet Ganovf7b47252018-02-26 11:11:27 -08002290 continue;
2291 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002292 if (dispatchedCallbacks == null) {
2293 dispatchedCallbacks = new ArraySet<>();
2294 }
2295 dispatchedCallbacks.add(callback);
2296 }
2297 }
2298 if (dispatchedCallbacks == null) {
2299 return;
2300 }
2301 mHandler.sendMessage(PooledLambda.obtainMessage(
2302 AppOpsService::notifyOpActiveChanged,
2303 this, dispatchedCallbacks, code, uid, packageName, active));
2304 }
2305
2306 private void notifyOpActiveChanged(ArraySet<ActiveCallback> callbacks,
2307 int code, int uid, String packageName, boolean active) {
2308 // There are components watching for mode changes such as window manager
2309 // and location manager which are in our process. The callbacks in these
2310 // components may require permissions our remote caller does not have.
2311 final long identity = Binder.clearCallingIdentity();
2312 try {
2313 final int callbackCount = callbacks.size();
2314 for (int i = 0; i < callbackCount; i++) {
2315 final ActiveCallback callback = callbacks.valueAt(i);
2316 try {
2317 callback.mCallback.opActiveChanged(code, uid, packageName, active);
2318 } catch (RemoteException e) {
2319 /* do nothing */
2320 }
2321 }
2322 } finally {
2323 Binder.restoreCallingIdentity(identity);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002324 }
2325 }
2326
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002327 private void scheduleOpNotedIfNeededLocked(int code, int uid, String packageName,
2328 int result) {
2329 ArraySet<NotedCallback> dispatchedCallbacks = null;
2330 final int callbackListCount = mNotedWatchers.size();
2331 for (int i = 0; i < callbackListCount; i++) {
2332 final SparseArray<NotedCallback> callbacks = mNotedWatchers.valueAt(i);
2333 final NotedCallback callback = callbacks.get(code);
2334 if (callback != null) {
2335 if (callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
2336 continue;
2337 }
2338 if (dispatchedCallbacks == null) {
2339 dispatchedCallbacks = new ArraySet<>();
2340 }
2341 dispatchedCallbacks.add(callback);
2342 }
2343 }
2344 if (dispatchedCallbacks == null) {
2345 return;
2346 }
2347 mHandler.sendMessage(PooledLambda.obtainMessage(
2348 AppOpsService::notifyOpChecked,
2349 this, dispatchedCallbacks, code, uid, packageName, result));
2350 }
2351
2352 private void notifyOpChecked(ArraySet<NotedCallback> callbacks,
2353 int code, int uid, String packageName, int result) {
2354 // There are components watching for checks in our process. The callbacks in
2355 // these components may require permissions our remote caller does not have.
2356 final long identity = Binder.clearCallingIdentity();
2357 try {
2358 final int callbackCount = callbacks.size();
2359 for (int i = 0; i < callbackCount; i++) {
2360 final NotedCallback callback = callbacks.valueAt(i);
2361 try {
2362 callback.mCallback.opNoted(code, uid, packageName, result);
2363 } catch (RemoteException e) {
2364 /* do nothing */
2365 }
2366 }
2367 } finally {
2368 Binder.restoreCallingIdentity(identity);
2369 }
2370 }
2371
Svet Ganovb9d71a62015-04-30 10:38:13 -07002372 @Override
2373 public int permissionToOpCode(String permission) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002374 if (permission == null) {
2375 return AppOpsManager.OP_NONE;
2376 }
Svet Ganovb9d71a62015-04-30 10:38:13 -07002377 return AppOpsManager.permissionToOpCode(permission);
2378 }
2379
Svet Ganova7a0db62018-02-27 20:08:01 -08002380 void finishOperationLocked(Op op, boolean finishNested) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002381 final int opCode = op.op;
2382 final int uid = op.uidState.uid;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002383 if (op.startNesting <= 1 || finishNested) {
2384 if (op.startNesting == 1 || finishNested) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002385 // We don't support proxy long running ops (start/stop)
2386 final long duration = SystemClock.elapsedRealtime() - op.startRealtime;
2387 op.finished(System.currentTimeMillis(), duration, op.uidState.state,
2388 AppOpsManager.OP_FLAG_SELF);
2389 mHistoricalRegistry.increaseOpAccessDuration(opCode, uid, op.packageName,
2390 op.uidState.state, AppOpsManager.OP_FLAG_SELF, duration);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002391 } else {
Svet Ganovaf189e32019-02-15 18:45:29 -08002392 final OpEntry entry = new OpEntry(op.op, op.running, op.mode, op.mAccessTimes,
2393 op.mRejectTimes, op.mDurations, op.mProxyUids, op.mProxyPackageNames);
2394 Slog.w(TAG, "Finishing op nesting under-run: uid " + uid + " pkg "
2395 + op.packageName + " code " + opCode + " time="
2396 + entry.getLastAccessTime(OP_FLAGS_ALL)
2397 + " duration=" + entry.getLastDuration(MAX_PRIORITY_UID_STATE,
2398 MIN_PRIORITY_UID_STATE, OP_FLAGS_ALL) + " nesting=" + op.startNesting);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002399 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002400 if (op.startNesting >= 1) {
2401 op.uidState.startNesting -= op.startNesting;
2402 }
2403 op.startNesting = 0;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002404 } else {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002405 op.startNesting--;
2406 op.uidState.startNesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002407 }
2408 }
2409
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002410 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002411 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002412 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002413 }
2414 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002415 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002416 }
2417 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
2418 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002419 }
2420
Dianne Hackborn961321f2013-02-05 17:22:41 -08002421 private void verifyIncomingOp(int op) {
2422 if (op >= 0 && op < AppOpsManager._NUM_OP) {
2423 return;
2424 }
2425 throw new IllegalArgumentException("Bad operation #" + op);
2426 }
2427
Philip P. Moltmann724150d2019-03-11 17:01:05 -07002428 private @Nullable UidState getUidStateLocked(int uid, boolean edit) {
Svet Ganov2af57082015-07-30 08:44:20 -07002429 UidState uidState = mUidStates.get(uid);
2430 if (uidState == null) {
2431 if (!edit) {
2432 return null;
2433 }
2434 uidState = new UidState(uid);
2435 mUidStates.put(uid, uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002436 } else {
2437 if (uidState.pendingStateCommitTime != 0) {
Dianne Hackborn9fb93502018-06-18 12:29:44 -07002438 if (uidState.pendingStateCommitTime < mLastRealtime) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002439 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002440 } else {
Dianne Hackborn9fb93502018-06-18 12:29:44 -07002441 mLastRealtime = SystemClock.elapsedRealtime();
2442 if (uidState.pendingStateCommitTime < mLastRealtime) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002443 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002444 }
2445 }
2446 }
Svet Ganov2af57082015-07-30 08:44:20 -07002447 }
2448 return uidState;
2449 }
2450
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002451 private void commitUidPendingStateLocked(UidState uidState) {
Wei Wange1f864e2019-03-28 18:12:18 -07002452 if (uidState.hasForegroundWatchers) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002453 for (int fgi = uidState.foregroundOps.size() - 1; fgi >= 0; fgi--) {
2454 if (!uidState.foregroundOps.valueAt(fgi)) {
2455 continue;
2456 }
2457 final int code = uidState.foregroundOps.keyAt(fgi);
Svet Ganovaf189e32019-02-15 18:45:29 -08002458 // For location ops we consider fg state only if the fg service
2459 // is of location type, for all other ops any fg service will do.
Wei Wang711eb662019-03-21 18:24:17 -07002460 final long firstUnrestrictedUidState = resolveFirstUnrestrictedUidState(code);
2461 final boolean resolvedLastFg = uidState.state <= firstUnrestrictedUidState;
2462 final boolean resolvedNowFg = uidState.pendingState <= firstUnrestrictedUidState;
2463 if (resolvedLastFg == resolvedNowFg) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002464 continue;
2465 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002466 final ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
2467 if (callbacks != null) {
2468 for (int cbi = callbacks.size() - 1; cbi >= 0; cbi--) {
2469 final ModeCallback callback = callbacks.valueAt(cbi);
2470 if ((callback.mFlags & AppOpsManager.WATCH_FOREGROUND_CHANGES) == 0
2471 || !callback.isWatchingUid(uidState.uid)) {
2472 continue;
2473 }
2474 boolean doAllPackages = uidState.opModes != null
Hai Zhang2b98fb32018-09-21 15:18:46 -07002475 && uidState.opModes.indexOfKey(code) >= 0
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002476 && uidState.opModes.get(code) == AppOpsManager.MODE_FOREGROUND;
2477 if (uidState.pkgOps != null) {
2478 for (int pkgi = uidState.pkgOps.size() - 1; pkgi >= 0; pkgi--) {
2479 final Op op = uidState.pkgOps.valueAt(pkgi).get(code);
Svet Ganovaf189e32019-02-15 18:45:29 -08002480 if (op == null) {
2481 continue;
2482 }
2483 if (doAllPackages || op.mode == AppOpsManager.MODE_FOREGROUND) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002484 mHandler.sendMessage(PooledLambda.obtainMessage(
2485 AppOpsService::notifyOpChanged,
2486 this, callback, code, uidState.uid,
2487 uidState.pkgOps.keyAt(pkgi)));
2488 }
2489 }
2490 }
2491 }
2492 }
2493 }
2494 }
Wei Wang711eb662019-03-21 18:24:17 -07002495 uidState.state = uidState.pendingState;
2496 uidState.pendingStateCommitTime = 0;
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002497 }
2498
Yohei Yukawaa965d652017-10-12 15:02:26 -07002499 private Ops getOpsRawLocked(int uid, String packageName, boolean edit,
2500 boolean uidMismatchExpected) {
Svet Ganov2af57082015-07-30 08:44:20 -07002501 UidState uidState = getUidStateLocked(uid, edit);
2502 if (uidState == null) {
2503 return null;
2504 }
2505
2506 if (uidState.pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002507 if (!edit) {
2508 return null;
2509 }
Svet Ganov2af57082015-07-30 08:44:20 -07002510 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002511 }
Svet Ganov2af57082015-07-30 08:44:20 -07002512
2513 Ops ops = uidState.pkgOps.get(packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002514 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002515 if (!edit) {
2516 return null;
2517 }
Jason Monk1c7c3192014-06-26 12:52:18 -04002518 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002519 // This is the first time we have seen this package name under this uid,
2520 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -08002521 if (uid != 0) {
2522 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002523 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -08002524 int pkgUid = -1;
2525 try {
Jason Monk1c7c3192014-06-26 12:52:18 -04002526 ApplicationInfo appInfo = ActivityThread.getPackageManager()
Jeff Sharkeycd654482016-01-08 17:42:11 -07002527 .getApplicationInfo(packageName,
Svet Ganovad0a49b2018-10-29 10:07:08 -07002528 PackageManager.MATCH_DIRECT_BOOT_AWARE
Svet Ganov8455ba22019-01-02 13:05:56 -08002529 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkeycd654482016-01-08 17:42:11 -07002530 UserHandle.getUserId(uid));
Jason Monk1c7c3192014-06-26 12:52:18 -04002531 if (appInfo != null) {
2532 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002533 isPrivileged = (appInfo.privateFlags
2534 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04002535 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08002536 pkgUid = resolveUid(packageName);
2537 if (pkgUid >= 0) {
Chien-Yu Chen75cade02016-01-11 10:56:21 -08002538 isPrivileged = false;
Jason Monk1c7c3192014-06-26 12:52:18 -04002539 }
Dianne Hackborn713df152013-05-17 11:27:57 -07002540 }
Jason Monk1c7c3192014-06-26 12:52:18 -04002541 } catch (RemoteException e) {
2542 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08002543 }
2544 if (pkgUid != uid) {
2545 // Oops! The package name is not valid for the uid they are calling
2546 // under. Abort.
Yohei Yukawaa965d652017-10-12 15:02:26 -07002547 if (!uidMismatchExpected) {
2548 RuntimeException ex = new RuntimeException("here");
2549 ex.fillInStackTrace();
2550 Slog.w(TAG, "Bad call: specified package " + packageName
2551 + " under uid " + uid + " but it is really " + pkgUid, ex);
2552 }
Dianne Hackborn514074f2013-02-11 10:52:46 -08002553 return null;
2554 }
2555 } finally {
2556 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002557 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002558 }
Svet Ganov2af57082015-07-30 08:44:20 -07002559 ops = new Ops(packageName, uidState, isPrivileged);
2560 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002561 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08002562 return ops;
2563 }
2564
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07002565 /**
2566 * Get the state of all ops for a package, <b>don't verify that package belongs to uid</b>.
2567 *
2568 * <p>Usually callers should use {@link #getOpLocked} and not call this directly.
2569 *
2570 * @param uid The uid the of the package
2571 * @param packageName The package name for which to get the state for
2572 * @param edit Iff {@code true} create the {@link Ops} object if not yet created
2573 * @param isPrivileged Whether the package is privileged or not
2574 *
2575 * @return The {@link Ops state} of all ops for the package
2576 */
2577 private @Nullable Ops getOpsRawNoVerifyLocked(int uid, @NonNull String packageName,
2578 boolean edit, boolean isPrivileged) {
2579 UidState uidState = getUidStateLocked(uid, edit);
2580 if (uidState == null) {
2581 return null;
2582 }
2583
2584 if (uidState.pkgOps == null) {
2585 if (!edit) {
2586 return null;
2587 }
2588 uidState.pkgOps = new ArrayMap<>();
2589 }
2590
2591 Ops ops = uidState.pkgOps.get(packageName);
2592 if (ops == null) {
2593 if (!edit) {
2594 return null;
2595 }
2596 ops = new Ops(packageName, uidState, isPrivileged);
2597 uidState.pkgOps.put(packageName, ops);
2598 }
2599 return ops;
2600 }
2601
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002602 private void scheduleWriteLocked() {
2603 if (!mWriteScheduled) {
2604 mWriteScheduled = true;
2605 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
2606 }
2607 }
2608
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002609 private void scheduleFastWriteLocked() {
2610 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002611 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002612 mFastWriteScheduled = true;
2613 mHandler.removeCallbacks(mWriteRunner);
2614 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002615 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002616 }
2617
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07002618 /**
2619 * Get the state of an op for a uid.
2620 *
2621 * @param code The code of the op
2622 * @param uid The uid the of the package
2623 * @param packageName The package name for which to get the state for
2624 * @param edit Iff {@code true} create the {@link Op} object if not yet created
2625 * @param verifyUid Iff {@code true} check that the package belongs to the uid
2626 * @param isPrivileged Whether the package is privileged or not (only used if {@code verifyUid
2627 * == false})
2628 *
2629 * @return The {@link Op state} of the op
2630 */
2631 private @Nullable Op getOpLocked(int code, int uid, @NonNull String packageName, boolean edit,
2632 boolean verifyUid, boolean isPrivileged) {
2633 Ops ops;
2634
2635 if (verifyUid) {
2636 ops = getOpsRawLocked(uid, packageName, edit, false /* uidMismatchExpected */);
2637 } else {
2638 ops = getOpsRawNoVerifyLocked(uid, packageName, edit, isPrivileged);
2639 }
2640
Dianne Hackborn72e39832013-01-18 18:36:09 -08002641 if (ops == null) {
2642 return null;
2643 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002644 return getOpLocked(ops, code, edit);
2645 }
2646
2647 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002648 Op op = ops.get(code);
2649 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002650 if (!edit) {
2651 return null;
2652 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002653 op = new Op(ops.uidState, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002654 ops.put(code, op);
2655 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002656 if (edit) {
2657 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002658 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002659 return op;
2660 }
2661
Svet Ganov442ed572016-08-17 17:29:43 -07002662 private boolean isOpRestrictedLocked(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04002663 int userHandle = UserHandle.getUserId(uid);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002664 final int restrictionSetCount = mOpUserRestrictions.size();
Ruben Brunk29931bc2016-03-11 00:24:26 -08002665
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002666 for (int i = 0; i < restrictionSetCount; i++) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002667 // For each client, check that the given op is not restricted, or that the given
2668 // package is exempt from the restriction.
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002669 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07002670 if (restrictionState.hasRestriction(code, packageName, userHandle)) {
2671 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
2672 // If we are the system, bypass user restrictions for certain codes
2673 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07002674 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
2675 false /* uidMismatchExpected */);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07002676 if ((ops != null) && ops.isPrivileged) {
2677 return false;
2678 }
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002679 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002680 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002681 return true;
Jason Monk1c7c3192014-06-26 12:52:18 -04002682 }
Jason Monk62062992014-05-06 09:55:28 -04002683 }
2684 return false;
2685 }
2686
Dianne Hackborn35654b62013-01-14 17:38:02 -08002687 void readState() {
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002688 int oldVersion = NO_VERSION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08002689 synchronized (mFile) {
2690 synchronized (this) {
2691 FileInputStream stream;
2692 try {
2693 stream = mFile.openRead();
2694 } catch (FileNotFoundException e) {
2695 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
2696 return;
2697 }
2698 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002699 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002700 try {
2701 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002702 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08002703 int type;
2704 while ((type = parser.next()) != XmlPullParser.START_TAG
2705 && type != XmlPullParser.END_DOCUMENT) {
2706 ;
2707 }
2708
2709 if (type != XmlPullParser.START_TAG) {
2710 throw new IllegalStateException("no start tag found");
2711 }
2712
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002713 final String versionString = parser.getAttributeValue(null, "v");
2714 if (versionString != null) {
2715 oldVersion = Integer.parseInt(versionString);
2716 }
2717
Dianne Hackborn35654b62013-01-14 17:38:02 -08002718 int outerDepth = parser.getDepth();
2719 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2720 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2721 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2722 continue;
2723 }
2724
2725 String tagName = parser.getName();
2726 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00002727 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07002728 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07002729 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002730 } else {
2731 Slog.w(TAG, "Unknown element under <app-ops>: "
2732 + parser.getName());
2733 XmlUtils.skipCurrentTag(parser);
2734 }
2735 }
2736 success = true;
2737 } catch (IllegalStateException e) {
2738 Slog.w(TAG, "Failed parsing " + e);
2739 } catch (NullPointerException e) {
2740 Slog.w(TAG, "Failed parsing " + e);
2741 } catch (NumberFormatException e) {
2742 Slog.w(TAG, "Failed parsing " + e);
2743 } catch (XmlPullParserException e) {
2744 Slog.w(TAG, "Failed parsing " + e);
2745 } catch (IOException e) {
2746 Slog.w(TAG, "Failed parsing " + e);
2747 } catch (IndexOutOfBoundsException e) {
2748 Slog.w(TAG, "Failed parsing " + e);
2749 } finally {
2750 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07002751 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002752 }
2753 try {
2754 stream.close();
2755 } catch (IOException e) {
2756 }
2757 }
2758 }
2759 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002760 synchronized (this) {
2761 upgradeLocked(oldVersion);
2762 }
2763 }
2764
2765 private void upgradeRunAnyInBackgroundLocked() {
2766 for (int i = 0; i < mUidStates.size(); i++) {
2767 final UidState uidState = mUidStates.valueAt(i);
2768 if (uidState == null) {
2769 continue;
2770 }
2771 if (uidState.opModes != null) {
2772 final int idx = uidState.opModes.indexOfKey(AppOpsManager.OP_RUN_IN_BACKGROUND);
2773 if (idx >= 0) {
2774 uidState.opModes.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND,
Svet Ganovaf189e32019-02-15 18:45:29 -08002775 uidState.opModes.valueAt(idx));
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002776 }
2777 }
2778 if (uidState.pkgOps == null) {
2779 continue;
2780 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002781 boolean changed = false;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002782 for (int j = 0; j < uidState.pkgOps.size(); j++) {
2783 Ops ops = uidState.pkgOps.valueAt(j);
2784 if (ops != null) {
2785 final Op op = ops.get(AppOpsManager.OP_RUN_IN_BACKGROUND);
2786 if (op != null && op.mode != AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002787 final Op copy = new Op(op.uidState, op.packageName,
Svet Ganovaf189e32019-02-15 18:45:29 -08002788 AppOpsManager.OP_RUN_ANY_IN_BACKGROUND);
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002789 copy.mode = op.mode;
2790 ops.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, copy);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002791 changed = true;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002792 }
2793 }
2794 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002795 if (changed) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002796 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002797 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002798 }
2799 }
2800
2801 private void upgradeLocked(int oldVersion) {
2802 if (oldVersion >= CURRENT_VERSION) {
2803 return;
2804 }
2805 Slog.d(TAG, "Upgrading app-ops xml from version " + oldVersion + " to " + CURRENT_VERSION);
2806 switch (oldVersion) {
2807 case NO_VERSION:
2808 upgradeRunAnyInBackgroundLocked();
2809 // fall through
2810 case 1:
2811 // for future upgrades
2812 }
2813 scheduleFastWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002814 }
2815
Svet Ganovaf189e32019-02-15 18:45:29 -08002816 private void readUidOps(XmlPullParser parser) throws NumberFormatException,
Svet Ganov2af57082015-07-30 08:44:20 -07002817 XmlPullParserException, IOException {
2818 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
2819 int outerDepth = parser.getDepth();
2820 int type;
2821 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2822 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2823 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2824 continue;
2825 }
2826
2827 String tagName = parser.getName();
2828 if (tagName.equals("op")) {
2829 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
2830 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
2831 UidState uidState = getUidStateLocked(uid, true);
2832 if (uidState.opModes == null) {
2833 uidState.opModes = new SparseIntArray();
2834 }
2835 uidState.opModes.put(code, mode);
2836 } else {
2837 Slog.w(TAG, "Unknown element under <uid-ops>: "
2838 + parser.getName());
2839 XmlUtils.skipCurrentTag(parser);
2840 }
2841 }
2842 }
2843
Svet Ganovaf189e32019-02-15 18:45:29 -08002844 private void readPackage(XmlPullParser parser)
2845 throws NumberFormatException, XmlPullParserException, IOException {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002846 String pkgName = parser.getAttributeValue(null, "n");
2847 int outerDepth = parser.getDepth();
2848 int type;
2849 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2850 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2851 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2852 continue;
2853 }
2854
2855 String tagName = parser.getName();
2856 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00002857 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002858 } else {
2859 Slog.w(TAG, "Unknown element under <pkg>: "
2860 + parser.getName());
2861 XmlUtils.skipCurrentTag(parser);
2862 }
2863 }
2864 }
2865
Svet Ganovaf189e32019-02-15 18:45:29 -08002866 private void readUid(XmlPullParser parser, String pkgName)
2867 throws NumberFormatException, XmlPullParserException, IOException {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002868 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Svet Ganovaf189e32019-02-15 18:45:29 -08002869 final UidState uidState = getUidStateLocked(uid, true);
Jason Monk1c7c3192014-06-26 12:52:18 -04002870 String isPrivilegedString = parser.getAttributeValue(null, "p");
2871 boolean isPrivileged = false;
2872 if (isPrivilegedString == null) {
2873 try {
2874 IPackageManager packageManager = ActivityThread.getPackageManager();
2875 if (packageManager != null) {
2876 ApplicationInfo appInfo = ActivityThread.getPackageManager()
2877 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
2878 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002879 isPrivileged = (appInfo.privateFlags
2880 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04002881 }
2882 } else {
2883 // Could not load data, don't add to cache so it will be loaded later.
2884 return;
2885 }
2886 } catch (RemoteException e) {
2887 Slog.w(TAG, "Could not contact PackageManager", e);
2888 }
2889 } else {
2890 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
2891 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002892 int outerDepth = parser.getDepth();
2893 int type;
2894 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2895 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2896 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2897 continue;
2898 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002899 String tagName = parser.getName();
2900 if (tagName.equals("op")) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002901 readOp(parser, uidState, pkgName, isPrivileged);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002902 } else {
2903 Slog.w(TAG, "Unknown element under <pkg>: "
2904 + parser.getName());
2905 XmlUtils.skipCurrentTag(parser);
2906 }
2907 }
Svet Ganovaf189e32019-02-15 18:45:29 -08002908 uidState.evalForegroundOps(mOpModeWatchers);
2909 }
2910
2911 private void readOp(XmlPullParser parser, @NonNull UidState uidState,
2912 @NonNull String pkgName, boolean isPrivileged) throws NumberFormatException,
2913 XmlPullParserException, IOException {
2914 Op op = new Op(uidState, pkgName,
2915 Integer.parseInt(parser.getAttributeValue(null, "n")));
2916
2917 final int mode = XmlUtils.readIntAttribute(parser, "m",
2918 AppOpsManager.opToDefaultMode(op.op));
2919 op.mode = mode;
2920
2921 int outerDepth = parser.getDepth();
2922 int type;
2923 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2924 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2925 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2926 continue;
2927 }
2928 String tagName = parser.getName();
2929 if (tagName.equals("st")) {
2930 final long key = XmlUtils.readLongAttribute(parser, "n");
2931
2932 final int flags = AppOpsManager.extractFlagsFromKey(key);
2933 final int state = AppOpsManager.extractUidStateFromKey(key);
2934
2935 final long accessTime = XmlUtils.readLongAttribute(parser, "t", 0);
2936 final long rejectTime = XmlUtils.readLongAttribute(parser, "r", 0);
2937 final long accessDuration = XmlUtils.readLongAttribute(parser, "d", 0);
2938 final String proxyPkg = XmlUtils.readStringAttribute(parser, "pp");
2939 final int proxyUid = XmlUtils.readIntAttribute(parser, "pu", 0);
2940
2941 if (accessTime > 0) {
2942 op.accessed(accessTime, proxyUid, proxyPkg, state, flags);
2943 }
2944 if (rejectTime > 0) {
2945 op.rejected(rejectTime, proxyUid, proxyPkg, state, flags);
2946 }
2947 if (accessDuration > 0) {
2948 op.running(accessTime, accessDuration, state, flags);
2949 }
2950 } else {
2951 Slog.w(TAG, "Unknown element under <op>: "
2952 + parser.getName());
2953 XmlUtils.skipCurrentTag(parser);
2954 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002955 }
Svet Ganovaf189e32019-02-15 18:45:29 -08002956
2957 if (uidState.pkgOps == null) {
2958 uidState.pkgOps = new ArrayMap<>();
2959 }
2960 Ops ops = uidState.pkgOps.get(pkgName);
2961 if (ops == null) {
2962 ops = new Ops(pkgName, uidState, isPrivileged);
2963 uidState.pkgOps.put(pkgName, ops);
2964 }
2965 ops.put(op.op, op);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002966 }
2967
2968 void writeState() {
2969 synchronized (mFile) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002970 FileOutputStream stream;
2971 try {
2972 stream = mFile.startWrite();
2973 } catch (IOException e) {
2974 Slog.w(TAG, "Failed to write state: " + e);
2975 return;
2976 }
2977
Dianne Hackborne17b4452018-01-10 13:15:40 -08002978 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
2979
Dianne Hackborn35654b62013-01-14 17:38:02 -08002980 try {
2981 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002982 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08002983 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002984 out.startTag(null, "app-ops");
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002985 out.attribute(null, "v", String.valueOf(CURRENT_VERSION));
Svet Ganov2af57082015-07-30 08:44:20 -07002986
2987 final int uidStateCount = mUidStates.size();
2988 for (int i = 0; i < uidStateCount; i++) {
2989 UidState uidState = mUidStates.valueAt(i);
2990 if (uidState.opModes != null && uidState.opModes.size() > 0) {
2991 out.startTag(null, "uid");
2992 out.attribute(null, "n", Integer.toString(uidState.uid));
2993 SparseIntArray uidOpModes = uidState.opModes;
2994 final int opCount = uidOpModes.size();
2995 for (int j = 0; j < opCount; j++) {
2996 final int op = uidOpModes.keyAt(j);
2997 final int mode = uidOpModes.valueAt(j);
2998 out.startTag(null, "op");
2999 out.attribute(null, "n", Integer.toString(op));
3000 out.attribute(null, "m", Integer.toString(mode));
3001 out.endTag(null, "op");
3002 }
3003 out.endTag(null, "uid");
3004 }
3005 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08003006
3007 if (allOps != null) {
3008 String lastPkg = null;
3009 for (int i=0; i<allOps.size(); i++) {
3010 AppOpsManager.PackageOps pkg = allOps.get(i);
3011 if (!pkg.getPackageName().equals(lastPkg)) {
3012 if (lastPkg != null) {
3013 out.endTag(null, "pkg");
3014 }
3015 lastPkg = pkg.getPackageName();
3016 out.startTag(null, "pkg");
3017 out.attribute(null, "n", lastPkg);
3018 }
3019 out.startTag(null, "uid");
3020 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04003021 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07003022 Ops ops = getOpsRawLocked(pkg.getUid(), pkg.getPackageName(),
3023 false /* edit */, false /* uidMismatchExpected */);
Jason Monk1c7c3192014-06-26 12:52:18 -04003024 // Should always be present as the list of PackageOps is generated
3025 // from Ops.
3026 if (ops != null) {
3027 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
3028 } else {
3029 out.attribute(null, "p", Boolean.toString(false));
3030 }
3031 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08003032 List<AppOpsManager.OpEntry> ops = pkg.getOps();
3033 for (int j=0; j<ops.size(); j++) {
3034 AppOpsManager.OpEntry op = ops.get(j);
3035 out.startTag(null, "op");
3036 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07003037 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003038 out.attribute(null, "m", Integer.toString(op.getMode()));
3039 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003040
3041 final LongSparseArray keys = op.collectKeys();
3042 if (keys == null || keys.size() <= 0) {
Svet Ganov8e5bf962019-03-19 23:59:03 -07003043 out.endTag(null, "op");
Svet Ganovaf189e32019-02-15 18:45:29 -08003044 continue;
3045 }
3046
3047 final int keyCount = keys.size();
3048 for (int k = 0; k < keyCount; k++) {
3049 final long key = keys.keyAt(k);
3050
3051 final int uidState = AppOpsManager.extractUidStateFromKey(key);
3052 final int flags = AppOpsManager.extractFlagsFromKey(key);
3053
3054 final long accessTime = op.getLastAccessTime(
3055 uidState, uidState, flags);
3056 final long rejectTime = op.getLastRejectTime(
3057 uidState, uidState, flags);
3058 final long accessDuration = op.getLastDuration(
3059 uidState, uidState, flags);
3060 final String proxyPkg = op.getProxyPackageName(uidState, flags);
3061 final int proxyUid = op.getProxyUid(uidState, flags);
3062
3063 if (accessTime <= 0 && rejectTime <= 0 && accessDuration <= 0
3064 && proxyPkg == null && proxyUid < 0) {
3065 continue;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003066 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003067
3068 out.startTag(null, "st");
3069 out.attribute(null, "n", Long.toString(key));
3070 if (accessTime > 0) {
3071 out.attribute(null, "t", Long.toString(accessTime));
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003072 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003073 if (rejectTime > 0) {
3074 out.attribute(null, "r", Long.toString(rejectTime));
3075 }
3076 if (accessDuration > 0) {
3077 out.attribute(null, "d", Long.toString(accessDuration));
3078 }
3079 if (proxyPkg != null) {
3080 out.attribute(null, "pp", proxyPkg);
3081 }
3082 if (proxyUid >= 0) {
3083 out.attribute(null, "pu", Integer.toString(proxyUid));
3084 }
3085 out.endTag(null, "st");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003086 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003087
Dianne Hackborn35654b62013-01-14 17:38:02 -08003088 out.endTag(null, "op");
3089 }
3090 out.endTag(null, "uid");
3091 }
3092 if (lastPkg != null) {
3093 out.endTag(null, "pkg");
3094 }
3095 }
3096
3097 out.endTag(null, "app-ops");
3098 out.endDocument();
3099 mFile.finishWrite(stream);
3100 } catch (IOException e) {
3101 Slog.w(TAG, "Failed to write state, restoring backup.", e);
3102 mFile.failWrite(stream);
3103 }
3104 }
3105 }
3106
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003107 static class Shell extends ShellCommand {
3108 final IAppOpsService mInterface;
3109 final AppOpsService mInternal;
3110
3111 int userId = UserHandle.USER_SYSTEM;
3112 String packageName;
3113 String opStr;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003114 String modeStr;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003115 int op;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003116 int mode;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003117 int packageUid;
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003118 int nonpackageUid;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003119 final static Binder sBinder = new Binder();
3120 IBinder mToken;
Svet Ganovd563e932019-04-14 13:07:41 -07003121 boolean targetsUid;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003122
3123 Shell(IAppOpsService iface, AppOpsService internal) {
3124 mInterface = iface;
3125 mInternal = internal;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003126 try {
3127 mToken = mInterface.getToken(sBinder);
3128 } catch (RemoteException e) {
3129 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003130 }
3131
3132 @Override
3133 public int onCommand(String cmd) {
3134 return onShellCommand(this, cmd);
3135 }
3136
3137 @Override
3138 public void onHelp() {
3139 PrintWriter pw = getOutPrintWriter();
3140 dumpCommandHelp(pw);
3141 }
3142
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003143 static private int strOpToOp(String op, PrintWriter err) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003144 try {
3145 return AppOpsManager.strOpToOp(op);
3146 } catch (IllegalArgumentException e) {
3147 }
3148 try {
3149 return Integer.parseInt(op);
3150 } catch (NumberFormatException e) {
3151 }
3152 try {
3153 return AppOpsManager.strDebugOpToOp(op);
3154 } catch (IllegalArgumentException e) {
3155 err.println("Error: " + e.getMessage());
3156 return -1;
3157 }
3158 }
3159
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003160 static int strModeToMode(String modeStr, PrintWriter err) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003161 for (int i = AppOpsManager.MODE_NAMES.length - 1; i >= 0; i--) {
3162 if (AppOpsManager.MODE_NAMES[i].equals(modeStr)) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003163 return i;
3164 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003165 }
3166 try {
3167 return Integer.parseInt(modeStr);
3168 } catch (NumberFormatException e) {
3169 }
3170 err.println("Error: Mode " + modeStr + " is not valid");
3171 return -1;
3172 }
3173
3174 int parseUserOpMode(int defMode, PrintWriter err) throws RemoteException {
3175 userId = UserHandle.USER_CURRENT;
3176 opStr = null;
3177 modeStr = null;
3178 for (String argument; (argument = getNextArg()) != null;) {
3179 if ("--user".equals(argument)) {
3180 userId = UserHandle.parseUserArg(getNextArgRequired());
3181 } else {
3182 if (opStr == null) {
3183 opStr = argument;
3184 } else if (modeStr == null) {
3185 modeStr = argument;
3186 break;
3187 }
3188 }
3189 }
3190 if (opStr == null) {
3191 err.println("Error: Operation not specified.");
3192 return -1;
3193 }
3194 op = strOpToOp(opStr, err);
3195 if (op < 0) {
3196 return -1;
3197 }
3198 if (modeStr != null) {
3199 if ((mode=strModeToMode(modeStr, err)) < 0) {
3200 return -1;
3201 }
3202 } else {
3203 mode = defMode;
3204 }
3205 return 0;
3206 }
3207
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003208 int parseUserPackageOp(boolean reqOp, PrintWriter err) throws RemoteException {
3209 userId = UserHandle.USER_CURRENT;
3210 packageName = null;
3211 opStr = null;
3212 for (String argument; (argument = getNextArg()) != null;) {
3213 if ("--user".equals(argument)) {
3214 userId = UserHandle.parseUserArg(getNextArgRequired());
Svet Ganovd563e932019-04-14 13:07:41 -07003215 } else if ("--uid".equals(argument)) {
3216 targetsUid = true;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003217 } else {
3218 if (packageName == null) {
3219 packageName = argument;
3220 } else if (opStr == null) {
3221 opStr = argument;
3222 break;
3223 }
3224 }
3225 }
3226 if (packageName == null) {
3227 err.println("Error: Package name not specified.");
3228 return -1;
3229 } else if (opStr == null && reqOp) {
3230 err.println("Error: Operation not specified.");
3231 return -1;
3232 }
3233 if (opStr != null) {
3234 op = strOpToOp(opStr, err);
3235 if (op < 0) {
3236 return -1;
3237 }
3238 } else {
3239 op = AppOpsManager.OP_NONE;
3240 }
3241 if (userId == UserHandle.USER_CURRENT) {
3242 userId = ActivityManager.getCurrentUser();
3243 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003244 nonpackageUid = -1;
3245 try {
3246 nonpackageUid = Integer.parseInt(packageName);
3247 } catch (NumberFormatException e) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003248 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003249 if (nonpackageUid == -1 && packageName.length() > 1 && packageName.charAt(0) == 'u'
3250 && packageName.indexOf('.') < 0) {
3251 int i = 1;
3252 while (i < packageName.length() && packageName.charAt(i) >= '0'
3253 && packageName.charAt(i) <= '9') {
3254 i++;
3255 }
3256 if (i > 1 && i < packageName.length()) {
3257 String userStr = packageName.substring(1, i);
3258 try {
3259 int user = Integer.parseInt(userStr);
3260 char type = packageName.charAt(i);
3261 i++;
3262 int startTypeVal = i;
3263 while (i < packageName.length() && packageName.charAt(i) >= '0'
3264 && packageName.charAt(i) <= '9') {
3265 i++;
3266 }
3267 if (i > startTypeVal) {
3268 String typeValStr = packageName.substring(startTypeVal, i);
3269 try {
3270 int typeVal = Integer.parseInt(typeValStr);
3271 if (type == 'a') {
3272 nonpackageUid = UserHandle.getUid(user,
3273 typeVal + Process.FIRST_APPLICATION_UID);
3274 } else if (type == 's') {
3275 nonpackageUid = UserHandle.getUid(user, typeVal);
3276 }
3277 } catch (NumberFormatException e) {
3278 }
3279 }
3280 } catch (NumberFormatException e) {
3281 }
3282 }
3283 }
3284 if (nonpackageUid != -1) {
3285 packageName = null;
3286 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08003287 packageUid = resolveUid(packageName);
3288 if (packageUid < 0) {
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003289 packageUid = AppGlobals.getPackageManager().getPackageUid(packageName,
3290 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
3291 }
3292 if (packageUid < 0) {
3293 err.println("Error: No UID for " + packageName + " in user " + userId);
3294 return -1;
3295 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003296 }
3297 return 0;
3298 }
3299 }
3300
3301 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003302 FileDescriptor err, String[] args, ShellCallback callback,
3303 ResultReceiver resultReceiver) {
3304 (new Shell(this, this)).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003305 }
3306
3307 static void dumpCommandHelp(PrintWriter pw) {
3308 pw.println("AppOps service (appops) commands:");
3309 pw.println(" help");
3310 pw.println(" Print this help text.");
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003311 pw.println(" start [--user <USER_ID>] <PACKAGE | UID> <OP> ");
3312 pw.println(" Starts a given operation for a particular application.");
3313 pw.println(" stop [--user <USER_ID>] <PACKAGE | UID> <OP> ");
3314 pw.println(" Stops a given operation for a particular application.");
Svet Ganovb687fad2019-04-30 17:32:44 -07003315 pw.println(" set [--user <USER_ID>] <[--uid] PACKAGE | UID> <OP> <MODE>");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003316 pw.println(" Set the mode for a particular application and operation.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003317 pw.println(" get [--user <USER_ID>] <PACKAGE | UID> [<OP>]");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003318 pw.println(" Return the mode for a particular application and optional operation.");
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003319 pw.println(" query-op [--user <USER_ID>] <OP> [<MODE>]");
3320 pw.println(" Print all packages that currently have the given op in the given mode.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003321 pw.println(" reset [--user <USER_ID>] [<PACKAGE>]");
3322 pw.println(" Reset the given application or all applications to default modes.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003323 pw.println(" write-settings");
3324 pw.println(" Immediately write pending changes to storage.");
3325 pw.println(" read-settings");
3326 pw.println(" Read the last written settings, replacing current state in RAM.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003327 pw.println(" options:");
Svet Ganovb687fad2019-04-30 17:32:44 -07003328 pw.println(" <PACKAGE> an Android package name or its UID if prefixed by --uid");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003329 pw.println(" <OP> an AppOps operation.");
3330 pw.println(" <MODE> one of allow, ignore, deny, or default");
3331 pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
3332 pw.println(" specified, the current user is assumed.");
3333 }
3334
3335 static int onShellCommand(Shell shell, String cmd) {
3336 if (cmd == null) {
3337 return shell.handleDefaultCommands(cmd);
3338 }
3339 PrintWriter pw = shell.getOutPrintWriter();
3340 PrintWriter err = shell.getErrPrintWriter();
3341 try {
3342 switch (cmd) {
3343 case "set": {
3344 int res = shell.parseUserPackageOp(true, err);
3345 if (res < 0) {
3346 return res;
3347 }
3348 String modeStr = shell.getNextArg();
3349 if (modeStr == null) {
3350 err.println("Error: Mode not specified.");
3351 return -1;
3352 }
3353
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003354 final int mode = shell.strModeToMode(modeStr, err);
3355 if (mode < 0) {
3356 return -1;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003357 }
3358
Svet Ganovd563e932019-04-14 13:07:41 -07003359 if (!shell.targetsUid && shell.packageName != null) {
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003360 shell.mInterface.setMode(shell.op, shell.packageUid, shell.packageName,
3361 mode);
Svet Ganovd563e932019-04-14 13:07:41 -07003362 } else if (shell.targetsUid && shell.packageName != null) {
3363 try {
3364 final int uid = shell.mInternal.mContext.getPackageManager()
3365 .getPackageUid(shell.packageName, shell.userId);
3366 shell.mInterface.setUidMode(shell.op, uid, mode);
3367 } catch (PackageManager.NameNotFoundException e) {
3368 return -1;
3369 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003370 } else {
3371 shell.mInterface.setUidMode(shell.op, shell.nonpackageUid, mode);
3372 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003373 return 0;
3374 }
3375 case "get": {
3376 int res = shell.parseUserPackageOp(false, err);
3377 if (res < 0) {
3378 return res;
3379 }
3380
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003381 List<AppOpsManager.PackageOps> ops = new ArrayList<>();
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003382 if (shell.packageName != null) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003383 // Uid mode overrides package mode, so make sure it's also reported
3384 List<AppOpsManager.PackageOps> r = shell.mInterface.getUidOps(
3385 shell.packageUid,
3386 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
3387 if (r != null) {
3388 ops.addAll(r);
3389 }
3390 r = shell.mInterface.getOpsForPackage(
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003391 shell.packageUid, shell.packageName,
3392 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003393 if (r != null) {
3394 ops.addAll(r);
3395 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003396 } else {
3397 ops = shell.mInterface.getUidOps(
3398 shell.nonpackageUid,
3399 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
3400 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003401 if (ops == null || ops.size() <= 0) {
3402 pw.println("No operations.");
Svet Ganov82f09bc2018-01-12 22:08:40 -08003403 if (shell.op > AppOpsManager.OP_NONE && shell.op < AppOpsManager._NUM_OP) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003404 pw.println("Default mode: " + AppOpsManager.modeToName(
Svet Ganov82f09bc2018-01-12 22:08:40 -08003405 AppOpsManager.opToDefaultMode(shell.op)));
3406 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003407 return 0;
3408 }
3409 final long now = System.currentTimeMillis();
3410 for (int i=0; i<ops.size(); i++) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003411 AppOpsManager.PackageOps packageOps = ops.get(i);
3412 if (packageOps.getPackageName() == null) {
3413 pw.print("Uid mode: ");
3414 }
3415 List<AppOpsManager.OpEntry> entries = packageOps.getOps();
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003416 for (int j=0; j<entries.size(); j++) {
3417 AppOpsManager.OpEntry ent = entries.get(j);
3418 pw.print(AppOpsManager.opToName(ent.getOp()));
3419 pw.print(": ");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003420 pw.print(AppOpsManager.modeToName(ent.getMode()));
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003421 if (ent.getTime() != 0) {
3422 pw.print("; time=");
3423 TimeUtils.formatDuration(now - ent.getTime(), pw);
3424 pw.print(" ago");
3425 }
3426 if (ent.getRejectTime() != 0) {
3427 pw.print("; rejectTime=");
3428 TimeUtils.formatDuration(now - ent.getRejectTime(), pw);
3429 pw.print(" ago");
3430 }
3431 if (ent.getDuration() == -1) {
3432 pw.print(" (running)");
3433 } else if (ent.getDuration() != 0) {
3434 pw.print("; duration=");
3435 TimeUtils.formatDuration(ent.getDuration(), pw);
3436 }
3437 pw.println();
3438 }
3439 }
3440 return 0;
3441 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003442 case "query-op": {
3443 int res = shell.parseUserOpMode(AppOpsManager.MODE_IGNORED, err);
3444 if (res < 0) {
3445 return res;
3446 }
3447 List<AppOpsManager.PackageOps> ops = shell.mInterface.getPackagesForOps(
3448 new int[] {shell.op});
3449 if (ops == null || ops.size() <= 0) {
3450 pw.println("No operations.");
3451 return 0;
3452 }
3453 for (int i=0; i<ops.size(); i++) {
3454 final AppOpsManager.PackageOps pkg = ops.get(i);
3455 boolean hasMatch = false;
3456 final List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
3457 for (int j=0; j<entries.size(); j++) {
3458 AppOpsManager.OpEntry ent = entries.get(j);
3459 if (ent.getOp() == shell.op && ent.getMode() == shell.mode) {
3460 hasMatch = true;
3461 break;
3462 }
3463 }
3464 if (hasMatch) {
3465 pw.println(pkg.getPackageName());
3466 }
3467 }
3468 return 0;
3469 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003470 case "reset": {
3471 String packageName = null;
3472 int userId = UserHandle.USER_CURRENT;
3473 for (String argument; (argument = shell.getNextArg()) != null;) {
3474 if ("--user".equals(argument)) {
3475 String userStr = shell.getNextArgRequired();
3476 userId = UserHandle.parseUserArg(userStr);
3477 } else {
3478 if (packageName == null) {
3479 packageName = argument;
3480 } else {
3481 err.println("Error: Unsupported argument: " + argument);
3482 return -1;
3483 }
3484 }
3485 }
3486
3487 if (userId == UserHandle.USER_CURRENT) {
3488 userId = ActivityManager.getCurrentUser();
3489 }
3490
3491 shell.mInterface.resetAllModes(userId, packageName);
3492 pw.print("Reset all modes for: ");
3493 if (userId == UserHandle.USER_ALL) {
3494 pw.print("all users");
3495 } else {
3496 pw.print("user "); pw.print(userId);
3497 }
3498 pw.print(", ");
3499 if (packageName == null) {
3500 pw.println("all packages");
3501 } else {
3502 pw.print("package "); pw.println(packageName);
3503 }
3504 return 0;
3505 }
3506 case "write-settings": {
Dianne Hackbornd5254412018-05-11 18:02:58 -07003507 shell.mInternal.enforceManageAppOpsModes(Binder.getCallingPid(),
3508 Binder.getCallingUid(), -1);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003509 long token = Binder.clearCallingIdentity();
3510 try {
3511 synchronized (shell.mInternal) {
3512 shell.mInternal.mHandler.removeCallbacks(shell.mInternal.mWriteRunner);
3513 }
3514 shell.mInternal.writeState();
3515 pw.println("Current settings written.");
3516 } finally {
3517 Binder.restoreCallingIdentity(token);
3518 }
3519 return 0;
3520 }
3521 case "read-settings": {
Dianne Hackbornd5254412018-05-11 18:02:58 -07003522 shell.mInternal.enforceManageAppOpsModes(Binder.getCallingPid(),
3523 Binder.getCallingUid(), -1);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003524 long token = Binder.clearCallingIdentity();
3525 try {
3526 shell.mInternal.readState();
3527 pw.println("Last settings read.");
3528 } finally {
3529 Binder.restoreCallingIdentity(token);
3530 }
3531 return 0;
3532 }
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003533 case "start": {
3534 int res = shell.parseUserPackageOp(true, err);
3535 if (res < 0) {
3536 return res;
3537 }
3538
3539 if (shell.packageName != null) {
3540 shell.mInterface.startOperation(shell.mToken,
3541 shell.op, shell.packageUid, shell.packageName, true);
3542 } else {
3543 return -1;
3544 }
3545 return 0;
3546 }
3547 case "stop": {
3548 int res = shell.parseUserPackageOp(true, err);
3549 if (res < 0) {
3550 return res;
3551 }
3552
3553 if (shell.packageName != null) {
3554 shell.mInterface.finishOperation(shell.mToken,
3555 shell.op, shell.packageUid, shell.packageName);
3556 } else {
3557 return -1;
3558 }
3559 return 0;
3560 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003561 default:
3562 return shell.handleDefaultCommands(cmd);
3563 }
3564 } catch (RemoteException e) {
3565 pw.println("Remote exception: " + e);
3566 }
3567 return -1;
3568 }
3569
3570 private void dumpHelp(PrintWriter pw) {
3571 pw.println("AppOps service (appops) dump options:");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003572 pw.println(" -h");
3573 pw.println(" Print this help text.");
3574 pw.println(" --op [OP]");
3575 pw.println(" Limit output to data associated with the given app op code.");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003576 pw.println(" --mode [MODE]");
3577 pw.println(" Limit output to data associated with the given app op mode.");
3578 pw.println(" --package [PACKAGE]");
3579 pw.println(" Limit output to data associated with the given package name.");
Dianne Hackborn125dc532019-01-09 13:31:48 -08003580 pw.println(" --watchers");
3581 pw.println(" Only output the watcher sections.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003582 }
3583
Svet Ganovaf189e32019-02-15 18:45:29 -08003584 private void dumpStatesLocked(@NonNull PrintWriter pw, @NonNull Op op,
3585 long now, @NonNull SimpleDateFormat sdf, @NonNull Date date, @NonNull String prefix) {
3586
3587 final OpEntry entry = new OpEntry(op.op, op.running, op.mode, op.mAccessTimes,
3588 op.mRejectTimes, op.mDurations, op.mProxyUids, op.mProxyPackageNames);
3589
3590 final LongSparseArray keys = entry.collectKeys();
3591 if (keys == null || keys.size() <= 0) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003592 return;
3593 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003594
3595 final int keyCount = keys.size();
3596 for (int k = 0; k < keyCount; k++) {
3597 final long key = keys.keyAt(k);
3598
3599 final int uidState = AppOpsManager.extractUidStateFromKey(key);
3600 final int flags = AppOpsManager.extractFlagsFromKey(key);
3601
3602 final long accessTime = entry.getLastAccessTime(
3603 uidState, uidState, flags);
3604 final long rejectTime = entry.getLastRejectTime(
3605 uidState, uidState, flags);
3606 final long accessDuration = entry.getLastDuration(
3607 uidState, uidState, flags);
3608 final String proxyPkg = entry.getProxyPackageName(uidState, flags);
3609 final int proxyUid = entry.getProxyUid(uidState, flags);
3610
3611 if (accessTime > 0) {
3612 pw.print(prefix);
3613 pw.print("Access: ");
3614 pw.print(AppOpsManager.keyToString(key));
3615 pw.print(" ");
3616 date.setTime(accessTime);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003617 pw.print(sdf.format(date));
3618 pw.print(" (");
Svet Ganovaf189e32019-02-15 18:45:29 -08003619 TimeUtils.formatDuration(accessTime - now, pw);
3620 pw.print(")");
3621 if (accessDuration > 0) {
3622 pw.print(" duration=");
3623 TimeUtils.formatDuration(accessDuration, pw);
3624 }
3625 if (proxyUid >= 0) {
3626 pw.print(" proxy[");
3627 pw.print("uid=");
3628 pw.print(proxyUid);
3629 pw.print(", pkg=");
3630 pw.print(proxyPkg);
3631 pw.print("]");
3632 }
3633 pw.println();
3634 }
3635
3636 if (rejectTime > 0) {
3637 pw.print(prefix);
3638 pw.print("Reject: ");
3639 pw.print(AppOpsManager.keyToString(key));
3640 date.setTime(rejectTime);
3641 pw.print(sdf.format(date));
3642 pw.print(" (");
3643 TimeUtils.formatDuration(rejectTime - now, pw);
3644 pw.print(")");
3645 if (proxyUid >= 0) {
3646 pw.print(" proxy[");
3647 pw.print("uid=");
3648 pw.print(proxyUid);
3649 pw.print(", pkg=");
3650 pw.print(proxyPkg);
3651 pw.print("]");
3652 }
3653 pw.println();
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003654 }
3655 }
3656 }
3657
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003658 @Override
3659 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06003660 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003661
Svet Ganov8455ba22019-01-02 13:05:56 -08003662 int dumpOp = OP_NONE;
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003663 String dumpPackage = null;
Svet Ganov8455ba22019-01-02 13:05:56 -08003664 int dumpUid = Process.INVALID_UID;
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003665 int dumpMode = -1;
Dianne Hackborn125dc532019-01-09 13:31:48 -08003666 boolean dumpWatchers = false;
Svet Ganovaf189e32019-02-15 18:45:29 -08003667 boolean dumpHistory = false;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003668
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003669 if (args != null) {
3670 for (int i=0; i<args.length; i++) {
3671 String arg = args[i];
3672 if ("-h".equals(arg)) {
3673 dumpHelp(pw);
3674 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07003675 } else if ("-a".equals(arg)) {
3676 // dump all data
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003677 } else if ("--op".equals(arg)) {
3678 i++;
3679 if (i >= args.length) {
3680 pw.println("No argument for --op option");
3681 return;
3682 }
3683 dumpOp = Shell.strOpToOp(args[i], pw);
3684 if (dumpOp < 0) {
3685 return;
3686 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003687 } else if ("--package".equals(arg)) {
3688 i++;
3689 if (i >= args.length) {
3690 pw.println("No argument for --package option");
3691 return;
3692 }
3693 dumpPackage = args[i];
3694 try {
3695 dumpUid = AppGlobals.getPackageManager().getPackageUid(dumpPackage,
3696 PackageManager.MATCH_KNOWN_PACKAGES | PackageManager.MATCH_INSTANT,
3697 0);
3698 } catch (RemoteException e) {
3699 }
3700 if (dumpUid < 0) {
3701 pw.println("Unknown package: " + dumpPackage);
3702 return;
3703 }
3704 dumpUid = UserHandle.getAppId(dumpUid);
3705 } else if ("--mode".equals(arg)) {
3706 i++;
3707 if (i >= args.length) {
3708 pw.println("No argument for --mode option");
3709 return;
3710 }
3711 dumpMode = Shell.strModeToMode(args[i], pw);
3712 if (dumpMode < 0) {
3713 return;
3714 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08003715 } else if ("--watchers".equals(arg)) {
3716 dumpWatchers = true;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003717 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
3718 pw.println("Unknown option: " + arg);
3719 return;
3720 } else {
3721 pw.println("Unknown command: " + arg);
3722 return;
3723 }
3724 }
3725 }
3726
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003727 synchronized (this) {
3728 pw.println("Current AppOps Service state:");
Svet Ganovaf189e32019-02-15 18:45:29 -08003729 if (!dumpHistory && !dumpWatchers) {
3730 mConstants.dump(pw);
3731 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003732 pw.println();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003733 final long now = System.currentTimeMillis();
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003734 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003735 final long nowUptime = SystemClock.uptimeMillis();
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003736 final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
3737 final Date date = new Date();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003738 boolean needSep = false;
Dianne Hackborn125dc532019-01-09 13:31:48 -08003739 if (dumpOp < 0 && dumpMode < 0 && dumpPackage == null && mProfileOwners != null
Svet Ganovaf189e32019-02-15 18:45:29 -08003740 && !dumpWatchers && !dumpHistory) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07003741 pw.println(" Profile owners:");
3742 for (int poi = 0; poi < mProfileOwners.size(); poi++) {
3743 pw.print(" User #");
3744 pw.print(mProfileOwners.keyAt(poi));
3745 pw.print(": ");
3746 UserHandle.formatUid(pw, mProfileOwners.valueAt(poi));
3747 pw.println();
3748 }
3749 pw.println();
3750 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003751 if (mOpModeWatchers.size() > 0 && !dumpHistory) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003752 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003753 for (int i=0; i<mOpModeWatchers.size(); i++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003754 if (dumpOp >= 0 && dumpOp != mOpModeWatchers.keyAt(i)) {
3755 continue;
3756 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003757 boolean printedOpHeader = false;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003758 ArraySet<ModeCallback> callbacks = mOpModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003759 for (int j=0; j<callbacks.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003760 final ModeCallback cb = callbacks.valueAt(j);
Dianne Hackborn125dc532019-01-09 13:31:48 -08003761 if (dumpPackage != null
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003762 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3763 continue;
3764 }
3765 needSep = true;
3766 if (!printedHeader) {
3767 pw.println(" Op mode watchers:");
3768 printedHeader = true;
3769 }
3770 if (!printedOpHeader) {
3771 pw.print(" Op ");
3772 pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
3773 pw.println(":");
3774 printedOpHeader = true;
3775 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003776 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003777 pw.println(cb);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003778 }
3779 }
3780 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003781 if (mPackageModeWatchers.size() > 0 && dumpOp < 0 && !dumpHistory) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003782 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003783 for (int i=0; i<mPackageModeWatchers.size(); i++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003784 if (dumpPackage != null && !dumpPackage.equals(mPackageModeWatchers.keyAt(i))) {
3785 continue;
3786 }
3787 needSep = true;
3788 if (!printedHeader) {
3789 pw.println(" Package mode watchers:");
3790 printedHeader = true;
3791 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003792 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
3793 pw.println(":");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003794 ArraySet<ModeCallback> callbacks = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003795 for (int j=0; j<callbacks.size(); j++) {
3796 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08003797 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003798 }
3799 }
3800 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003801 if (mModeWatchers.size() > 0 && dumpOp < 0 && !dumpHistory) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003802 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003803 for (int i=0; i<mModeWatchers.size(); i++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003804 final ModeCallback cb = mModeWatchers.valueAt(i);
Dianne Hackborn125dc532019-01-09 13:31:48 -08003805 if (dumpPackage != null
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003806 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3807 continue;
3808 }
3809 needSep = true;
3810 if (!printedHeader) {
3811 pw.println(" All op mode watchers:");
3812 printedHeader = true;
3813 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003814 pw.print(" ");
3815 pw.print(Integer.toHexString(System.identityHashCode(mModeWatchers.keyAt(i))));
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003816 pw.print(": "); pw.println(cb);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003817 }
3818 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003819 if (mActiveWatchers.size() > 0 && dumpMode < 0) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003820 needSep = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003821 boolean printedHeader = false;
Philip P. Moltmannba136462019-05-21 10:20:38 -07003822 for (int watcherNum = 0; watcherNum < mActiveWatchers.size(); watcherNum++) {
3823 final SparseArray<ActiveCallback> activeWatchers =
3824 mActiveWatchers.valueAt(watcherNum);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003825 if (activeWatchers.size() <= 0) {
3826 continue;
3827 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003828 final ActiveCallback cb = activeWatchers.valueAt(0);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003829 if (dumpOp >= 0 && activeWatchers.indexOfKey(dumpOp) < 0) {
3830 continue;
3831 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08003832 if (dumpPackage != null
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003833 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3834 continue;
3835 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003836 if (!printedHeader) {
3837 pw.println(" All op active watchers:");
3838 printedHeader = true;
3839 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003840 pw.print(" ");
3841 pw.print(Integer.toHexString(System.identityHashCode(
Philip P. Moltmannba136462019-05-21 10:20:38 -07003842 mActiveWatchers.keyAt(watcherNum))));
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003843 pw.println(" ->");
3844 pw.print(" [");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003845 final int opCount = activeWatchers.size();
Philip P. Moltmannba136462019-05-21 10:20:38 -07003846 for (int opNum = 0; opNum < opCount; opNum++) {
3847 if (opNum > 0) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003848 pw.print(' ');
3849 }
Philip P. Moltmannba136462019-05-21 10:20:38 -07003850 pw.print(AppOpsManager.opToName(activeWatchers.keyAt(opNum)));
3851 if (opNum < opCount - 1) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003852 pw.print(',');
3853 }
3854 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003855 pw.println("]");
3856 pw.print(" ");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003857 pw.println(cb);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003858 }
3859 }
Svet Ganovb3d2ae22018-12-17 22:06:15 -08003860 if (mNotedWatchers.size() > 0 && dumpMode < 0) {
3861 needSep = true;
3862 boolean printedHeader = false;
3863 for (int i = 0; i < mNotedWatchers.size(); i++) {
3864 final SparseArray<NotedCallback> notedWatchers = mNotedWatchers.valueAt(i);
3865 if (notedWatchers.size() <= 0) {
3866 continue;
3867 }
3868 final NotedCallback cb = notedWatchers.valueAt(0);
3869 if (dumpOp >= 0 && notedWatchers.indexOfKey(dumpOp) < 0) {
3870 continue;
3871 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08003872 if (dumpPackage != null
Svet Ganovb3d2ae22018-12-17 22:06:15 -08003873 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3874 continue;
3875 }
3876 if (!printedHeader) {
3877 pw.println(" All op noted watchers:");
3878 printedHeader = true;
3879 }
3880 pw.print(" ");
3881 pw.print(Integer.toHexString(System.identityHashCode(
3882 mNotedWatchers.keyAt(i))));
3883 pw.println(" ->");
3884 pw.print(" [");
3885 final int opCount = notedWatchers.size();
3886 for (i = 0; i < opCount; i++) {
3887 if (i > 0) {
3888 pw.print(' ');
3889 }
3890 pw.print(AppOpsManager.opToName(notedWatchers.keyAt(i)));
3891 if (i < opCount - 1) {
3892 pw.print(',');
3893 }
3894 }
3895 pw.println("]");
3896 pw.print(" ");
3897 pw.println(cb);
3898 }
3899 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003900 if (mClients.size() > 0 && dumpMode < 0 && !dumpWatchers && !dumpHistory) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003901 needSep = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003902 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003903 for (int i=0; i<mClients.size(); i++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003904 boolean printedClient = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003905 ClientState cs = mClients.valueAt(i);
Svet Ganovf7b47252018-02-26 11:11:27 -08003906 if (cs.mStartedOps.size() > 0) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003907 boolean printedStarted = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003908 for (int j=0; j<cs.mStartedOps.size(); j++) {
3909 Op op = cs.mStartedOps.get(j);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003910 if (dumpOp >= 0 && op.op != dumpOp) {
3911 continue;
3912 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003913 if (dumpPackage != null && !dumpPackage.equals(op.packageName)) {
3914 continue;
3915 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003916 if (!printedHeader) {
3917 pw.println(" Clients:");
3918 printedHeader = true;
3919 }
3920 if (!printedClient) {
3921 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
3922 pw.print(" "); pw.println(cs);
3923 printedClient = true;
3924 }
3925 if (!printedStarted) {
3926 pw.println(" Started ops:");
3927 printedStarted = true;
3928 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003929 pw.print(" "); pw.print("uid="); pw.print(op.uidState.uid);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003930 pw.print(" pkg="); pw.print(op.packageName);
3931 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
3932 }
3933 }
3934 }
3935 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003936 if (mAudioRestrictions.size() > 0 && dumpOp < 0 && dumpPackage != null
Svet Ganovaf189e32019-02-15 18:45:29 -08003937 && dumpMode < 0 && !dumpWatchers && !dumpWatchers) {
John Spurlock1af30c72014-03-10 08:33:35 -04003938 boolean printedHeader = false;
3939 for (int o=0; o<mAudioRestrictions.size(); o++) {
3940 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
3941 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
3942 for (int i=0; i<restrictions.size(); i++) {
3943 if (!printedHeader){
3944 pw.println(" Audio Restrictions:");
3945 printedHeader = true;
3946 needSep = true;
3947 }
John Spurlock7b414672014-07-18 13:02:39 -04003948 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04003949 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04003950 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04003951 Restriction r = restrictions.valueAt(i);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003952 pw.print(": mode="); pw.println(AppOpsManager.modeToName(r.mode));
John Spurlock1af30c72014-03-10 08:33:35 -04003953 if (!r.exceptionPackages.isEmpty()) {
3954 pw.println(" Exceptions:");
3955 for (int j=0; j<r.exceptionPackages.size(); j++) {
3956 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
3957 }
3958 }
3959 }
3960 }
3961 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003962 if (needSep) {
3963 pw.println();
3964 }
Svet Ganov2af57082015-07-30 08:44:20 -07003965 for (int i=0; i<mUidStates.size(); i++) {
3966 UidState uidState = mUidStates.valueAt(i);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003967 final SparseIntArray opModes = uidState.opModes;
3968 final ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
3969
Svet Ganovaf189e32019-02-15 18:45:29 -08003970 if (dumpWatchers || dumpHistory) {
Dianne Hackborn125dc532019-01-09 13:31:48 -08003971 continue;
3972 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003973 if (dumpOp >= 0 || dumpPackage != null || dumpMode >= 0) {
3974 boolean hasOp = dumpOp < 0 || (uidState.opModes != null
3975 && uidState.opModes.indexOfKey(dumpOp) >= 0);
3976 boolean hasPackage = dumpPackage == null;
3977 boolean hasMode = dumpMode < 0;
3978 if (!hasMode && opModes != null) {
3979 for (int opi = 0; !hasMode && opi < opModes.size(); opi++) {
3980 if (opModes.valueAt(opi) == dumpMode) {
3981 hasMode = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003982 }
3983 }
3984 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003985 if (pkgOps != null) {
3986 for (int pkgi = 0;
Svet Ganov8455ba22019-01-02 13:05:56 -08003987 (!hasOp || !hasPackage || !hasMode) && pkgi < pkgOps.size();
3988 pkgi++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003989 Ops ops = pkgOps.valueAt(pkgi);
3990 if (!hasOp && ops != null && ops.indexOfKey(dumpOp) >= 0) {
3991 hasOp = true;
3992 }
3993 if (!hasMode) {
3994 for (int opi = 0; !hasMode && opi < ops.size(); opi++) {
3995 if (ops.valueAt(opi).mode == dumpMode) {
3996 hasMode = true;
3997 }
3998 }
3999 }
4000 if (!hasPackage && dumpPackage.equals(ops.packageName)) {
4001 hasPackage = true;
4002 }
4003 }
4004 }
4005 if (uidState.foregroundOps != null && !hasOp) {
4006 if (uidState.foregroundOps.indexOfKey(dumpOp) > 0) {
4007 hasOp = true;
4008 }
4009 }
4010 if (!hasOp || !hasPackage || !hasMode) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004011 continue;
4012 }
4013 }
Svet Ganov2af57082015-07-30 08:44:20 -07004014
4015 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07004016 pw.print(" state=");
Svet Ganovaf189e32019-02-15 18:45:29 -08004017 pw.println(AppOpsManager.getUidStateName(uidState.state));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004018 if (uidState.state != uidState.pendingState) {
4019 pw.print(" pendingState=");
Svet Ganovaf189e32019-02-15 18:45:29 -08004020 pw.println(AppOpsManager.getUidStateName(uidState.pendingState));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004021 }
4022 if (uidState.pendingStateCommitTime != 0) {
4023 pw.print(" pendingStateCommitTime=");
Dianne Hackborn9fb93502018-06-18 12:29:44 -07004024 TimeUtils.formatDuration(uidState.pendingStateCommitTime, nowElapsed, pw);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004025 pw.println();
4026 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07004027 if (uidState.startNesting != 0) {
4028 pw.print(" startNesting=");
4029 pw.println(uidState.startNesting);
4030 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004031 if (uidState.foregroundOps != null && (dumpMode < 0
4032 || dumpMode == AppOpsManager.MODE_FOREGROUND)) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004033 pw.println(" foregroundOps:");
4034 for (int j = 0; j < uidState.foregroundOps.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004035 if (dumpOp >= 0 && dumpOp != uidState.foregroundOps.keyAt(j)) {
4036 continue;
4037 }
4038 pw.print(" ");
4039 pw.print(AppOpsManager.opToName(uidState.foregroundOps.keyAt(j)));
4040 pw.print(": ");
4041 pw.println(uidState.foregroundOps.valueAt(j) ? "WATCHER" : "SILENT");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004042 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004043 pw.print(" hasForegroundWatchers=");
4044 pw.println(uidState.hasForegroundWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004045 }
Svet Ganovee438d42017-01-19 18:04:38 -08004046 needSep = true;
Svet Ganov2af57082015-07-30 08:44:20 -07004047
Svet Ganov2af57082015-07-30 08:44:20 -07004048 if (opModes != null) {
4049 final int opModeCount = opModes.size();
4050 for (int j = 0; j < opModeCount; j++) {
4051 final int code = opModes.keyAt(j);
4052 final int mode = opModes.valueAt(j);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004053 if (dumpOp >= 0 && dumpOp != code) {
4054 continue;
4055 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004056 if (dumpMode >= 0 && dumpMode != mode) {
4057 continue;
4058 }
Svet Ganov2af57082015-07-30 08:44:20 -07004059 pw.print(" "); pw.print(AppOpsManager.opToName(code));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004060 pw.print(": mode="); pw.println(AppOpsManager.modeToName(mode));
Svet Ganov2af57082015-07-30 08:44:20 -07004061 }
4062 }
4063
Svet Ganov2af57082015-07-30 08:44:20 -07004064 if (pkgOps == null) {
4065 continue;
4066 }
4067
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004068 for (int pkgi = 0; pkgi < pkgOps.size(); pkgi++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004069 final Ops ops = pkgOps.valueAt(pkgi);
4070 if (dumpPackage != null && !dumpPackage.equals(ops.packageName)) {
4071 continue;
4072 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004073 boolean printedPackage = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004074 for (int j=0; j<ops.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004075 final Op op = ops.valueAt(j);
Svet Ganovaf189e32019-02-15 18:45:29 -08004076 final int opCode = op.op;
4077 if (dumpOp >= 0 && dumpOp != opCode) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004078 continue;
4079 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004080 if (dumpMode >= 0 && dumpMode != op.mode) {
4081 continue;
4082 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004083 if (!printedPackage) {
4084 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
4085 printedPackage = true;
4086 }
Svet Ganovaf189e32019-02-15 18:45:29 -08004087 pw.print(" "); pw.print(AppOpsManager.opToName(opCode));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004088 pw.print(" ("); pw.print(AppOpsManager.modeToName(op.mode));
Svet Ganovaf189e32019-02-15 18:45:29 -08004089 final int switchOp = AppOpsManager.opToSwitch(opCode);
4090 if (switchOp != opCode) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004091 pw.print(" / switch ");
4092 pw.print(AppOpsManager.opToName(switchOp));
4093 final Op switchObj = ops.get(switchOp);
Svet Ganovaf189e32019-02-15 18:45:29 -08004094 int mode = switchObj != null ? switchObj.mode
4095 : AppOpsManager.opToDefaultMode(switchOp);
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004096 pw.print("="); pw.print(AppOpsManager.modeToName(mode));
4097 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004098 pw.println("): ");
Svet Ganovaf189e32019-02-15 18:45:29 -08004099 dumpStatesLocked(pw, op, now, sdf, date, " ");
4100 if (op.running) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07004101 pw.print(" Running start at: ");
4102 TimeUtils.formatDuration(nowElapsed-op.startRealtime, pw);
4103 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004104 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07004105 if (op.startNesting != 0) {
4106 pw.print(" startNesting=");
4107 pw.println(op.startNesting);
4108 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004109 }
4110 }
4111 }
Svet Ganovee438d42017-01-19 18:04:38 -08004112 if (needSep) {
4113 pw.println();
4114 }
4115
4116 final int userRestrictionCount = mOpUserRestrictions.size();
4117 for (int i = 0; i < userRestrictionCount; i++) {
4118 IBinder token = mOpUserRestrictions.keyAt(i);
4119 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
Dianne Hackborn125dc532019-01-09 13:31:48 -08004120 boolean printedTokenHeader = false;
4121
Svet Ganovaf189e32019-02-15 18:45:29 -08004122 if (dumpMode >= 0 || dumpWatchers || dumpHistory) {
Dianne Hackborn125dc532019-01-09 13:31:48 -08004123 continue;
4124 }
Svet Ganovee438d42017-01-19 18:04:38 -08004125
4126 final int restrictionCount = restrictionState.perUserRestrictions != null
4127 ? restrictionState.perUserRestrictions.size() : 0;
Dianne Hackborn125dc532019-01-09 13:31:48 -08004128 if (restrictionCount > 0 && dumpPackage == null) {
4129 boolean printedOpsHeader = false;
Svet Ganovee438d42017-01-19 18:04:38 -08004130 for (int j = 0; j < restrictionCount; j++) {
4131 int userId = restrictionState.perUserRestrictions.keyAt(j);
4132 boolean[] restrictedOps = restrictionState.perUserRestrictions.valueAt(j);
4133 if (restrictedOps == null) {
4134 continue;
4135 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08004136 if (dumpOp >= 0 && (dumpOp >= restrictedOps.length
4137 || !restrictedOps[dumpOp])) {
4138 continue;
4139 }
4140 if (!printedTokenHeader) {
4141 pw.println(" User restrictions for token " + token + ":");
4142 printedTokenHeader = true;
4143 }
4144 if (!printedOpsHeader) {
4145 pw.println(" Restricted ops:");
4146 printedOpsHeader = true;
4147 }
Svet Ganovee438d42017-01-19 18:04:38 -08004148 StringBuilder restrictedOpsValue = new StringBuilder();
4149 restrictedOpsValue.append("[");
4150 final int restrictedOpCount = restrictedOps.length;
4151 for (int k = 0; k < restrictedOpCount; k++) {
4152 if (restrictedOps[k]) {
4153 if (restrictedOpsValue.length() > 1) {
4154 restrictedOpsValue.append(", ");
4155 }
4156 restrictedOpsValue.append(AppOpsManager.opToName(k));
4157 }
4158 }
4159 restrictedOpsValue.append("]");
4160 pw.print(" "); pw.print("user: "); pw.print(userId);
4161 pw.print(" restricted ops: "); pw.println(restrictedOpsValue);
4162 }
4163 }
4164
4165 final int excludedPackageCount = restrictionState.perUserExcludedPackages != null
4166 ? restrictionState.perUserExcludedPackages.size() : 0;
Dianne Hackborn125dc532019-01-09 13:31:48 -08004167 if (excludedPackageCount > 0 && dumpOp < 0) {
4168 boolean printedPackagesHeader = false;
Svet Ganovee438d42017-01-19 18:04:38 -08004169 for (int j = 0; j < excludedPackageCount; j++) {
4170 int userId = restrictionState.perUserExcludedPackages.keyAt(j);
4171 String[] packageNames = restrictionState.perUserExcludedPackages.valueAt(j);
Dianne Hackborn125dc532019-01-09 13:31:48 -08004172 if (packageNames == null) {
4173 continue;
4174 }
4175 boolean hasPackage;
4176 if (dumpPackage != null) {
4177 hasPackage = false;
4178 for (String pkg : packageNames) {
4179 if (dumpPackage.equals(pkg)) {
4180 hasPackage = true;
4181 break;
4182 }
4183 }
4184 } else {
4185 hasPackage = true;
4186 }
4187 if (!hasPackage) {
4188 continue;
4189 }
4190 if (!printedTokenHeader) {
4191 pw.println(" User restrictions for token " + token + ":");
4192 printedTokenHeader = true;
4193 }
4194 if (!printedPackagesHeader) {
4195 pw.println(" Excluded packages:");
4196 printedPackagesHeader = true;
4197 }
Svet Ganovee438d42017-01-19 18:04:38 -08004198 pw.print(" "); pw.print("user: "); pw.print(userId);
4199 pw.print(" packages: "); pw.println(Arrays.toString(packageNames));
4200 }
4201 }
4202 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004203 }
Svet Ganov8455ba22019-01-02 13:05:56 -08004204
4205 // Must not hold the appops lock
Svet Ganovaf189e32019-02-15 18:45:29 -08004206 if (dumpHistory && !dumpWatchers) {
4207 mHistoricalRegistry.dump(" ", pw, dumpUid, dumpPackage, dumpOp);
4208 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004209 }
John Spurlock1af30c72014-03-10 08:33:35 -04004210
4211 private static final class Restriction {
4212 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
4213 int mode;
4214 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
4215 }
Jason Monk62062992014-05-06 09:55:28 -04004216
4217 @Override
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004218 public void setUserRestrictions(Bundle restrictions, IBinder token, int userHandle) {
Jason Monk62062992014-05-06 09:55:28 -04004219 checkSystemUid("setUserRestrictions");
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004220 Preconditions.checkNotNull(restrictions);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004221 Preconditions.checkNotNull(token);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004222 for (int i = 0; i < AppOpsManager._NUM_OP; i++) {
Jason Monk62062992014-05-06 09:55:28 -04004223 String restriction = AppOpsManager.opToRestriction(i);
Suprabh Shukla64e0dcb2016-05-24 16:23:11 -07004224 if (restriction != null) {
4225 setUserRestrictionNoCheck(i, restrictions.getBoolean(restriction, false), token,
4226 userHandle, null);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004227 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004228 }
4229 }
4230
4231 @Override
Ruben Brunk29931bc2016-03-11 00:24:26 -08004232 public void setUserRestriction(int code, boolean restricted, IBinder token, int userHandle,
4233 String[] exceptionPackages) {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004234 if (Binder.getCallingPid() != Process.myPid()) {
4235 mContext.enforcePermission(Manifest.permission.MANAGE_APP_OPS_RESTRICTIONS,
4236 Binder.getCallingPid(), Binder.getCallingUid(), null);
4237 }
4238 if (userHandle != UserHandle.getCallingUserId()) {
4239 if (mContext.checkCallingOrSelfPermission(Manifest.permission
4240 .INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
4241 && mContext.checkCallingOrSelfPermission(Manifest.permission
4242 .INTERACT_ACROSS_USERS) != PackageManager.PERMISSION_GRANTED) {
4243 throw new SecurityException("Need INTERACT_ACROSS_USERS_FULL or"
4244 + " INTERACT_ACROSS_USERS to interact cross user ");
Jason Monk62062992014-05-06 09:55:28 -04004245 }
4246 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004247 verifyIncomingOp(code);
4248 Preconditions.checkNotNull(token);
Ruben Brunk29931bc2016-03-11 00:24:26 -08004249 setUserRestrictionNoCheck(code, restricted, token, userHandle, exceptionPackages);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004250 }
4251
4252 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
Ruben Brunk29931bc2016-03-11 00:24:26 -08004253 int userHandle, String[] exceptionPackages) {
Svet Ganov442ed572016-08-17 17:29:43 -07004254 synchronized (AppOpsService.this) {
4255 ClientRestrictionState restrictionState = mOpUserRestrictions.get(token);
4256
4257 if (restrictionState == null) {
4258 try {
4259 restrictionState = new ClientRestrictionState(token);
4260 } catch (RemoteException e) {
4261 return;
4262 }
4263 mOpUserRestrictions.put(token, restrictionState);
Ruben Brunk29931bc2016-03-11 00:24:26 -08004264 }
Svet Ganov442ed572016-08-17 17:29:43 -07004265
4266 if (restrictionState.setRestriction(code, restricted, exceptionPackages, userHandle)) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004267 mHandler.sendMessage(PooledLambda.obtainMessage(
Svet Ganov3a95f832018-03-23 17:44:30 -07004268 AppOpsService::notifyWatchersOfChange, this, code, UID_ANY));
Svet Ganov442ed572016-08-17 17:29:43 -07004269 }
4270
4271 if (restrictionState.isDefault()) {
4272 mOpUserRestrictions.remove(token);
4273 restrictionState.destroy();
4274 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08004275 }
Julia Reynoldsbb21c252016-04-05 16:01:49 -04004276 }
4277
Svet Ganov3a95f832018-03-23 17:44:30 -07004278 private void notifyWatchersOfChange(int code, int uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004279 final ArraySet<ModeCallback> clonedCallbacks;
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004280 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004281 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004282 if (callbacks == null) {
4283 return;
4284 }
Dianne Hackborn68d76552017-02-27 15:32:03 -08004285 clonedCallbacks = new ArraySet<>(callbacks);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004286 }
4287
Svet Ganov3a95f832018-03-23 17:44:30 -07004288 notifyOpChanged(clonedCallbacks, code, uid, null);
Jason Monk62062992014-05-06 09:55:28 -04004289 }
4290
4291 @Override
4292 public void removeUser(int userHandle) throws RemoteException {
4293 checkSystemUid("removeUser");
Svet Ganov442ed572016-08-17 17:29:43 -07004294 synchronized (AppOpsService.this) {
4295 final int tokenCount = mOpUserRestrictions.size();
4296 for (int i = tokenCount - 1; i >= 0; i--) {
4297 ClientRestrictionState opRestrictions = mOpUserRestrictions.valueAt(i);
4298 opRestrictions.removeUser(userHandle);
4299 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07004300 removeUidsForUserLocked(userHandle);
4301 }
4302 }
4303
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004304 @Override
4305 public boolean isOperationActive(int code, int uid, String packageName) {
Svet Ganovf7b47252018-02-26 11:11:27 -08004306 if (Binder.getCallingUid() != uid) {
4307 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
4308 != PackageManager.PERMISSION_GRANTED) {
4309 return false;
4310 }
4311 }
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004312 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004313 final String resolvedPackageName = resolvePackageName(uid, packageName);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004314 if (resolvedPackageName == null) {
4315 return false;
4316 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004317 synchronized (AppOpsService.this) {
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004318 for (int i = mClients.size() - 1; i >= 0; i--) {
4319 final ClientState client = mClients.valueAt(i);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004320 for (int j = client.mStartedOps.size() - 1; j >= 0; j--) {
4321 final Op op = client.mStartedOps.get(j);
Svet Ganovaf189e32019-02-15 18:45:29 -08004322 if (op.op == code && op.uidState.uid == uid) return true;
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004323 }
4324 }
4325 }
4326 return false;
4327 }
4328
Svet Ganov8455ba22019-01-02 13:05:56 -08004329 @Override
4330 public void setHistoryParameters(@AppOpsManager.HistoricalMode int mode,
4331 long baseSnapshotInterval, int compressionStep) {
4332 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4333 "setHistoryParameters");
4334 // Must not hold the appops lock
4335 mHistoricalRegistry.setHistoryParameters(mode, baseSnapshotInterval, compressionStep);
4336 }
4337
4338 @Override
4339 public void offsetHistory(long offsetMillis) {
4340 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4341 "offsetHistory");
4342 // Must not hold the appops lock
4343 mHistoricalRegistry.offsetHistory(offsetMillis);
4344 }
4345
4346 @Override
4347 public void addHistoricalOps(HistoricalOps ops) {
4348 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4349 "addHistoricalOps");
4350 // Must not hold the appops lock
4351 mHistoricalRegistry.addHistoricalOps(ops);
4352 }
4353
4354 @Override
4355 public void resetHistoryParameters() {
4356 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4357 "resetHistoryParameters");
4358 // Must not hold the appops lock
4359 mHistoricalRegistry.resetHistoryParameters();
4360 }
4361
4362 @Override
4363 public void clearHistory() {
4364 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4365 "clearHistory");
4366 // Must not hold the appops lock
4367 mHistoricalRegistry.clearHistory();
4368 }
4369
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07004370 private void removeUidsForUserLocked(int userHandle) {
4371 for (int i = mUidStates.size() - 1; i >= 0; --i) {
4372 final int uid = mUidStates.keyAt(i);
4373 if (UserHandle.getUserId(uid) == userHandle) {
4374 mUidStates.removeAt(i);
4375 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004376 }
4377 }
4378
Jason Monk62062992014-05-06 09:55:28 -04004379 private void checkSystemUid(String function) {
4380 int uid = Binder.getCallingUid();
4381 if (uid != Process.SYSTEM_UID) {
4382 throw new SecurityException(function + " must by called by the system");
4383 }
4384 }
4385
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004386 private static String resolvePackageName(int uid, String packageName) {
Svet Ganov82f09bc2018-01-12 22:08:40 -08004387 if (uid == Process.ROOT_UID) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004388 return "root";
4389 } else if (uid == Process.SHELL_UID) {
4390 return "com.android.shell";
Svet Ganov82f09bc2018-01-12 22:08:40 -08004391 } else if (uid == Process.MEDIA_UID) {
4392 return "media";
4393 } else if (uid == Process.AUDIOSERVER_UID) {
4394 return "audioserver";
4395 } else if (uid == Process.CAMERASERVER_UID) {
4396 return "cameraserver";
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004397 } else if (uid == Process.SYSTEM_UID && packageName == null) {
4398 return "android";
4399 }
4400 return packageName;
4401 }
4402
Svet Ganov82f09bc2018-01-12 22:08:40 -08004403 private static int resolveUid(String packageName) {
4404 if (packageName == null) {
4405 return -1;
4406 }
4407 switch (packageName) {
4408 case "root":
4409 return Process.ROOT_UID;
4410 case "shell":
4411 return Process.SHELL_UID;
4412 case "media":
4413 return Process.MEDIA_UID;
4414 case "audioserver":
4415 return Process.AUDIOSERVER_UID;
4416 case "cameraserver":
4417 return Process.CAMERASERVER_UID;
4418 }
4419 return -1;
4420 }
4421
Svet Ganov2af57082015-07-30 08:44:20 -07004422 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07004423 String[] packageNames = null;
Philip P. Moltmann159d98b2018-12-20 08:30:53 -08004424
4425 // Very early during boot the package manager is not yet or not yet fully started. At this
4426 // time there are no packages yet.
4427 if (AppGlobals.getPackageManager() != null) {
4428 try {
4429 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
4430 } catch (RemoteException e) {
4431 /* ignore - local call */
4432 }
Svet Ganov2af57082015-07-30 08:44:20 -07004433 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07004434 if (packageNames == null) {
4435 return EmptyArray.STRING;
4436 }
4437 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07004438 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004439
4440 private final class ClientRestrictionState implements DeathRecipient {
4441 private final IBinder token;
4442 SparseArray<boolean[]> perUserRestrictions;
4443 SparseArray<String[]> perUserExcludedPackages;
4444
4445 public ClientRestrictionState(IBinder token)
4446 throws RemoteException {
4447 token.linkToDeath(this, 0);
4448 this.token = token;
4449 }
4450
4451 public boolean setRestriction(int code, boolean restricted,
4452 String[] excludedPackages, int userId) {
4453 boolean changed = false;
4454
4455 if (perUserRestrictions == null && restricted) {
4456 perUserRestrictions = new SparseArray<>();
4457 }
4458
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004459 int[] users;
4460 if (userId == UserHandle.USER_ALL) {
4461 List<UserInfo> liveUsers = UserManager.get(mContext).getUsers(false);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004462
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004463 users = new int[liveUsers.size()];
4464 for (int i = 0; i < liveUsers.size(); i++) {
4465 users[i] = liveUsers.get(i).id;
4466 }
4467 } else {
4468 users = new int[]{userId};
4469 }
4470
4471 if (perUserRestrictions != null) {
4472 int numUsers = users.length;
4473
4474 for (int i = 0; i < numUsers; i++) {
4475 int thisUserId = users[i];
4476
4477 boolean[] userRestrictions = perUserRestrictions.get(thisUserId);
4478 if (userRestrictions == null && restricted) {
4479 userRestrictions = new boolean[AppOpsManager._NUM_OP];
4480 perUserRestrictions.put(thisUserId, userRestrictions);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004481 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004482 if (userRestrictions != null && userRestrictions[code] != restricted) {
4483 userRestrictions[code] = restricted;
4484 if (!restricted && isDefault(userRestrictions)) {
4485 perUserRestrictions.remove(thisUserId);
4486 userRestrictions = null;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004487 }
4488 changed = true;
4489 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004490
4491 if (userRestrictions != null) {
4492 final boolean noExcludedPackages = ArrayUtils.isEmpty(excludedPackages);
4493 if (perUserExcludedPackages == null && !noExcludedPackages) {
4494 perUserExcludedPackages = new SparseArray<>();
4495 }
4496 if (perUserExcludedPackages != null && !Arrays.equals(excludedPackages,
4497 perUserExcludedPackages.get(thisUserId))) {
4498 if (noExcludedPackages) {
4499 perUserExcludedPackages.remove(thisUserId);
4500 if (perUserExcludedPackages.size() <= 0) {
4501 perUserExcludedPackages = null;
4502 }
4503 } else {
4504 perUserExcludedPackages.put(thisUserId, excludedPackages);
4505 }
4506 changed = true;
4507 }
4508 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004509 }
4510 }
4511
4512 return changed;
4513 }
4514
4515 public boolean hasRestriction(int restriction, String packageName, int userId) {
4516 if (perUserRestrictions == null) {
4517 return false;
4518 }
4519 boolean[] restrictions = perUserRestrictions.get(userId);
4520 if (restrictions == null) {
4521 return false;
4522 }
4523 if (!restrictions[restriction]) {
4524 return false;
4525 }
4526 if (perUserExcludedPackages == null) {
4527 return true;
4528 }
4529 String[] perUserExclusions = perUserExcludedPackages.get(userId);
4530 if (perUserExclusions == null) {
4531 return true;
4532 }
4533 return !ArrayUtils.contains(perUserExclusions, packageName);
4534 }
4535
4536 public void removeUser(int userId) {
4537 if (perUserExcludedPackages != null) {
4538 perUserExcludedPackages.remove(userId);
4539 if (perUserExcludedPackages.size() <= 0) {
4540 perUserExcludedPackages = null;
4541 }
4542 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07004543 if (perUserRestrictions != null) {
4544 perUserRestrictions.remove(userId);
4545 if (perUserRestrictions.size() <= 0) {
4546 perUserRestrictions = null;
4547 }
4548 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004549 }
4550
4551 public boolean isDefault() {
4552 return perUserRestrictions == null || perUserRestrictions.size() <= 0;
4553 }
4554
4555 @Override
4556 public void binderDied() {
4557 synchronized (AppOpsService.this) {
4558 mOpUserRestrictions.remove(token);
4559 if (perUserRestrictions == null) {
4560 return;
4561 }
4562 final int userCount = perUserRestrictions.size();
4563 for (int i = 0; i < userCount; i++) {
4564 final boolean[] restrictions = perUserRestrictions.valueAt(i);
4565 final int restrictionCount = restrictions.length;
4566 for (int j = 0; j < restrictionCount; j++) {
4567 if (restrictions[j]) {
4568 final int changedCode = j;
Svet Ganov3a95f832018-03-23 17:44:30 -07004569 mHandler.post(() -> notifyWatchersOfChange(changedCode, UID_ANY));
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004570 }
4571 }
4572 }
4573 destroy();
4574 }
4575 }
4576
4577 public void destroy() {
4578 token.unlinkToDeath(this, 0);
4579 }
4580
4581 private boolean isDefault(boolean[] array) {
4582 if (ArrayUtils.isEmpty(array)) {
4583 return true;
4584 }
4585 for (boolean value : array) {
4586 if (value) {
4587 return false;
4588 }
4589 }
4590 return true;
4591 }
4592 }
Dianne Hackbornd5254412018-05-11 18:02:58 -07004593
4594 private final class AppOpsManagerInternalImpl extends AppOpsManagerInternal {
4595 @Override public void setDeviceAndProfileOwners(SparseIntArray owners) {
4596 synchronized (AppOpsService.this) {
4597 mProfileOwners = owners;
4598 }
4599 }
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07004600
4601 @Override
Philip P. Moltmann159d98b2018-12-20 08:30:53 -08004602 public void setUidMode(int code, int uid, int mode) {
4603 AppOpsService.this.setUidMode(code, uid, mode);
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07004604 }
Philip P. Moltmanndde07852019-01-25 16:42:36 -08004605
4606 @Override
4607 public void setAllPkgModesToDefault(int code, int uid) {
4608 AppOpsService.this.setAllPkgModesToDefault(code, uid);
4609 }
Philip P. Moltmann724150d2019-03-11 17:01:05 -07004610
4611 @Override
4612 public @Mode int checkOperationUnchecked(int code, int uid, @NonNull String packageName) {
4613 return AppOpsService.this.checkOperationUnchecked(code, uid, packageName, true, false);
4614 }
Dianne Hackbornd5254412018-05-11 18:02:58 -07004615 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004616}