blob: d04aa8931dca7103c065bece67176bf225203895 [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 Ganov8455ba22019-01-02 13:05:56 -0800204 private final HistoricalRegistry mHistoricalRegistry = new HistoricalRegistry(this);
205
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--) {
Svet Ganova7a0db62018-02-27 20:08:01 -0800708 finishOperationLocked(mStartedOps.get(i), /*finishNested*/ true);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700709 }
710 mClients.remove(mAppToken);
711 }
712 }
713 }
714
Jeff Brown6f357d32014-01-15 20:40:55 -0800715 public AppOpsService(File storagePath, Handler handler) {
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600716 LockGuard.installLock(this, LockGuard.INDEX_APP_OPS);
Dianne Hackborne17b4452018-01-10 13:15:40 -0800717 mFile = new AtomicFile(storagePath, "appops");
Jeff Brown6f357d32014-01-15 20:40:55 -0800718 mHandler = handler;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700719 mConstants = new Constants(mHandler);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800720 readState();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800721 }
David Braunf5d83192013-09-16 13:43:51 -0700722
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800723 public void publish(Context context) {
724 mContext = context;
725 ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
Dianne Hackbornd5254412018-05-11 18:02:58 -0700726 LocalServices.addService(AppOpsManagerInternal.class, mAppOpsManagerInternal);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800727 }
728
Dianne Hackborn514074f2013-02-11 10:52:46 -0800729 public void systemReady() {
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700730 mConstants.startMonitoring(mContext.getContentResolver());
Svet Ganov8455ba22019-01-02 13:05:56 -0800731 mHistoricalRegistry.systemReady(mContext.getContentResolver());
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700732
Dianne Hackborn514074f2013-02-11 10:52:46 -0800733 synchronized (this) {
734 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700735 for (int i = mUidStates.size() - 1; i >= 0; i--) {
736 UidState uidState = mUidStates.valueAt(i);
737
738 String[] packageNames = getPackagesForUid(uidState.uid);
739 if (ArrayUtils.isEmpty(packageNames)) {
740 uidState.clear();
741 mUidStates.removeAt(i);
742 changed = true;
743 continue;
744 }
745
746 ArrayMap<String, Ops> pkgs = uidState.pkgOps;
747 if (pkgs == null) {
748 continue;
749 }
750
Dianne Hackborn514074f2013-02-11 10:52:46 -0800751 Iterator<Ops> it = pkgs.values().iterator();
752 while (it.hasNext()) {
753 Ops ops = it.next();
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700754 int curUid = -1;
Dianne Hackborn514074f2013-02-11 10:52:46 -0800755 try {
Jeff Sharkeycd654482016-01-08 17:42:11 -0700756 curUid = AppGlobals.getPackageManager().getPackageUid(ops.packageName,
757 PackageManager.MATCH_UNINSTALLED_PACKAGES,
Svet Ganov2af57082015-07-30 08:44:20 -0700758 UserHandle.getUserId(ops.uidState.uid));
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700759 } catch (RemoteException ignored) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800760 }
Svet Ganov2af57082015-07-30 08:44:20 -0700761 if (curUid != ops.uidState.uid) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800762 Slog.i(TAG, "Pruning old package " + ops.packageName
Svet Ganov2af57082015-07-30 08:44:20 -0700763 + "/" + ops.uidState + ": new uid=" + curUid);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800764 it.remove();
765 changed = true;
766 }
767 }
Svet Ganov2af57082015-07-30 08:44:20 -0700768
769 if (uidState.isDefault()) {
770 mUidStates.removeAt(i);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800771 }
772 }
773 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800774 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800775 }
776 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700777
Suprabh Shukla3017fe42018-11-08 19:00:01 -0800778 final IntentFilter packageSuspendFilter = new IntentFilter();
779 packageSuspendFilter.addAction(Intent.ACTION_PACKAGES_UNSUSPENDED);
780 packageSuspendFilter.addAction(Intent.ACTION_PACKAGES_SUSPENDED);
781 mContext.registerReceiver(new BroadcastReceiver() {
782 @Override
783 public void onReceive(Context context, Intent intent) {
784 final int[] changedUids = intent.getIntArrayExtra(Intent.EXTRA_CHANGED_UID_LIST);
785 final String[] changedPkgs = intent.getStringArrayExtra(
786 Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackbornb298b352019-04-04 11:01:41 -0700787 ArraySet<ModeCallback> callbacks;
788 synchronized (AppOpsService.this) {
789 callbacks = mOpModeWatchers.get(OP_PLAY_AUDIO);
790 if (callbacks == null) {
791 return;
792 }
793 callbacks = new ArraySet<>(callbacks);
794 }
Suprabh Shukla3017fe42018-11-08 19:00:01 -0800795 for (int i = 0; i < changedUids.length; i++) {
796 final int changedUid = changedUids[i];
797 final String changedPkg = changedPkgs[i];
Dianne Hackbornb298b352019-04-04 11:01:41 -0700798 // We trust packagemanager to insert matching uid and packageNames in the
799 // extras
800 notifyOpChanged(callbacks, OP_PLAY_AUDIO, changedUid, changedPkg);
Suprabh Shukla3017fe42018-11-08 19:00:01 -0800801 }
802 }
803 }, packageSuspendFilter);
804
Suprabh Shuklaaef25132017-01-23 18:09:03 -0800805 PackageManagerInternal packageManagerInternal = LocalServices.getService(
806 PackageManagerInternal.class);
807 packageManagerInternal.setExternalSourcesPolicy(
808 new PackageManagerInternal.ExternalSourcesPolicy() {
809 @Override
810 public int getPackageTrustedToInstallApps(String packageName, int uid) {
811 int appOpMode = checkOperation(AppOpsManager.OP_REQUEST_INSTALL_PACKAGES,
812 uid, packageName);
813 switch (appOpMode) {
814 case AppOpsManager.MODE_ALLOWED:
815 return PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
816 case AppOpsManager.MODE_ERRORED:
817 return PackageManagerInternal.ExternalSourcesPolicy.USER_BLOCKED;
818 default:
819 return PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT;
820 }
821 }
822 });
823
Jeff Sharkey10ec9d82018-11-28 14:52:45 -0700824 if (!StorageManager.hasIsolatedStorage()) {
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700825 StorageManagerInternal storageManagerInternal = LocalServices.getService(
826 StorageManagerInternal.class);
827 storageManagerInternal.addExternalStoragePolicy(
828 new StorageManagerInternal.ExternalStorageMountPolicy() {
829 @Override
830 public int getMountMode(int uid, String packageName) {
831 if (Process.isIsolated(uid)) {
832 return Zygote.MOUNT_EXTERNAL_NONE;
833 }
834 if (noteOperation(AppOpsManager.OP_READ_EXTERNAL_STORAGE, uid,
835 packageName) != AppOpsManager.MODE_ALLOWED) {
836 return Zygote.MOUNT_EXTERNAL_NONE;
837 }
838 if (noteOperation(AppOpsManager.OP_WRITE_EXTERNAL_STORAGE, uid,
839 packageName) != AppOpsManager.MODE_ALLOWED) {
840 return Zygote.MOUNT_EXTERNAL_READ;
841 }
842 return Zygote.MOUNT_EXTERNAL_WRITE;
Svet Ganov6ee871e2015-07-10 14:29:33 -0700843 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700844
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700845 @Override
846 public boolean hasExternalStorage(int uid, String packageName) {
847 final int mountMode = getMountMode(uid, packageName);
848 return mountMode == Zygote.MOUNT_EXTERNAL_READ
849 || mountMode == Zygote.MOUNT_EXTERNAL_WRITE;
850 }
851 });
852 }
Dianne Hackborn514074f2013-02-11 10:52:46 -0800853 }
854
855 public void packageRemoved(int uid, String packageName) {
856 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700857 UidState uidState = mUidStates.get(uid);
858 if (uidState == null) {
859 return;
860 }
861
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800862 Ops ops = null;
Svet Ganov2af57082015-07-30 08:44:20 -0700863
864 // Remove any package state if such.
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800865 if (uidState.pkgOps != null) {
866 ops = uidState.pkgOps.remove(packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700867 }
868
869 // If we just nuked the last package state check if the UID is valid.
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800870 if (ops != null && uidState.pkgOps.isEmpty()
Svet Ganov2af57082015-07-30 08:44:20 -0700871 && getPackagesForUid(uid).length <= 0) {
872 mUidStates.remove(uid);
873 }
874
Svet Ganova7a0db62018-02-27 20:08:01 -0800875 // Finish ops other packages started on behalf of the package.
876 final int clientCount = mClients.size();
877 for (int i = 0; i < clientCount; i++) {
878 final ClientState client = mClients.valueAt(i);
879 if (client.mStartedOps == null) {
880 continue;
881 }
882 final int opCount = client.mStartedOps.size();
883 for (int j = opCount - 1; j >= 0; j--) {
884 final Op op = client.mStartedOps.get(j);
Svet Ganovaf189e32019-02-15 18:45:29 -0800885 if (uid == op.uidState.uid && packageName.equals(op.packageName)) {
Svet Ganova7a0db62018-02-27 20:08:01 -0800886 finishOperationLocked(op, /*finishNested*/ true);
887 client.mStartedOps.remove(j);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700888 if (op.startNesting <= 0) {
Svet Ganova7a0db62018-02-27 20:08:01 -0800889 scheduleOpActiveChangedIfNeededLocked(op.op,
890 uid, packageName, false);
891 }
892 }
893 }
894 }
895
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800896 if (ops != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700897 scheduleFastWriteLocked();
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800898
899 final int opCount = ops.size();
900 for (int i = 0; i < opCount; i++) {
901 final Op op = ops.valueAt(i);
Svet Ganovaf189e32019-02-15 18:45:29 -0800902 if (op.running) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800903 scheduleOpActiveChangedIfNeededLocked(
Svet Ganovaf189e32019-02-15 18:45:29 -0800904 op.op, op.uidState.uid, op.packageName, false);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800905 }
906 }
Dianne Hackborn514074f2013-02-11 10:52:46 -0800907 }
908 }
909 }
910
911 public void uidRemoved(int uid) {
912 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700913 if (mUidStates.indexOfKey(uid) >= 0) {
914 mUidStates.remove(uid);
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800915 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800916 }
917 }
918 }
919
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700920 public void updateUidProcState(int uid, int procState) {
921 synchronized (this) {
922 final UidState uidState = getUidStateLocked(uid, true);
Amith Yamasania0a30a12019-01-22 11:38:06 -0800923 int newState = PROCESS_STATE_TO_UID_STATE[procState];
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700924 if (uidState != null && uidState.pendingState != newState) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700925 final int oldPendingState = uidState.pendingState;
926 uidState.pendingState = newState;
Wei Wange1f864e2019-03-28 18:12:18 -0700927 if (newState < uidState.state
928 || (newState <= UID_STATE_MAX_LAST_NON_RESTRICTED
929 && uidState.state > UID_STATE_MAX_LAST_NON_RESTRICTED)) {
930 // We are moving to a more important state, or the new state may be in the
931 // foreground and the old state is in the background, then always do it
932 // immediately.
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700933 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700934 } else if (uidState.pendingStateCommitTime == 0) {
935 // We are moving to a less important state for the first time,
936 // delay the application for a bit.
Dianne Hackborne93ab412018-05-14 17:52:30 -0700937 final long settleTime;
938 if (uidState.state <= UID_STATE_TOP) {
939 settleTime = mConstants.TOP_STATE_SETTLE_TIME;
940 } else if (uidState.state <= UID_STATE_FOREGROUND_SERVICE) {
941 settleTime = mConstants.FG_SERVICE_STATE_SETTLE_TIME;
942 } else {
943 settleTime = mConstants.BG_STATE_SETTLE_TIME;
944 }
Dianne Hackborn9fb93502018-06-18 12:29:44 -0700945 uidState.pendingStateCommitTime = SystemClock.elapsedRealtime() + settleTime;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700946 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700947 if (uidState.startNesting != 0) {
948 // There is some actively running operation... need to find it
949 // and appropriately update its state.
950 final long now = System.currentTimeMillis();
951 for (int i = uidState.pkgOps.size() - 1; i >= 0; i--) {
952 final Ops ops = uidState.pkgOps.valueAt(i);
953 for (int j = ops.size() - 1; j >= 0; j--) {
954 final Op op = ops.valueAt(j);
955 if (op.startNesting > 0) {
Svet Ganovaf189e32019-02-15 18:45:29 -0800956 final long duration = SystemClock.elapsedRealtime()
957 - op.startRealtime;
958 // We don't support proxy long running ops (start/stop)
959 mHistoricalRegistry.increaseOpAccessDuration(op.op,
960 op.uidState.uid, op.packageName, oldPendingState,
961 AppOpsManager.OP_FLAG_SELF, duration);
962 // Finish the op in the old state
963 op.finished(now, duration, oldPendingState,
964 AppOpsManager.OP_FLAG_SELF);
965 // Start the op in the new state
966 op.startRealtime = now;
967 op.started(now, newState, AppOpsManager.OP_FLAG_SELF);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700968 }
969 }
970 }
971 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700972 }
973 }
974 }
975
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800976 public void shutdown() {
977 Slog.w(TAG, "Writing app ops before shutdown...");
Dianne Hackborn35654b62013-01-14 17:38:02 -0800978 boolean doWrite = false;
979 synchronized (this) {
980 if (mWriteScheduled) {
981 mWriteScheduled = false;
982 doWrite = true;
983 }
984 }
985 if (doWrite) {
986 writeState();
987 }
988 }
989
Dianne Hackborn72e39832013-01-18 18:36:09 -0800990 private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
991 ArrayList<AppOpsManager.OpEntry> resOps = null;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700992 final long elapsedNow = SystemClock.elapsedRealtime();
Dianne Hackborn72e39832013-01-18 18:36:09 -0800993 if (ops == null) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700994 resOps = new ArrayList<>();
Dianne Hackborn72e39832013-01-18 18:36:09 -0800995 for (int j=0; j<pkgOps.size(); j++) {
996 Op curOp = pkgOps.valueAt(j);
Svet Ganovaf189e32019-02-15 18:45:29 -0800997 resOps.add(getOpEntryForResult(curOp, elapsedNow));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800998 }
999 } else {
1000 for (int j=0; j<ops.length; j++) {
1001 Op curOp = pkgOps.get(ops[j]);
1002 if (curOp != null) {
1003 if (resOps == null) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001004 resOps = new ArrayList<>();
Dianne Hackborn72e39832013-01-18 18:36:09 -08001005 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001006 resOps.add(getOpEntryForResult(curOp, elapsedNow));
Dianne Hackborn72e39832013-01-18 18:36:09 -08001007 }
1008 }
1009 }
1010 return resOps;
1011 }
1012
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001013 private ArrayList<AppOpsManager.OpEntry> collectOps(SparseIntArray uidOps, int[] ops) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08001014 if (uidOps == null) {
1015 return null;
1016 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001017 ArrayList<AppOpsManager.OpEntry> resOps = null;
1018 if (ops == null) {
1019 resOps = new ArrayList<>();
1020 for (int j=0; j<uidOps.size(); j++) {
Svet Ganovaf189e32019-02-15 18:45:29 -08001021 resOps.add(new OpEntry(uidOps.keyAt(j), uidOps.valueAt(j)));
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001022 }
1023 } else {
1024 for (int j=0; j<ops.length; j++) {
1025 int index = uidOps.indexOfKey(ops[j]);
1026 if (index >= 0) {
1027 if (resOps == null) {
1028 resOps = new ArrayList<>();
1029 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001030 resOps.add(new OpEntry(uidOps.keyAt(j), uidOps.valueAt(j)));
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001031 }
1032 }
1033 }
1034 return resOps;
1035 }
1036
Svet Ganovaf189e32019-02-15 18:45:29 -08001037 private static @NonNull OpEntry getOpEntryForResult(@NonNull Op op, long elapsedNow) {
1038 if (op.running) {
1039 op.continuing(elapsedNow - op.startRealtime,
1040 op.uidState.state, AppOpsManager.OP_FLAG_SELF);
1041 }
1042 final OpEntry entry = new OpEntry(op.op, op.running, op.mode,
1043 op.mAccessTimes != null ? op.mAccessTimes.clone() : null,
1044 op.mRejectTimes != null ? op.mRejectTimes.clone() : null,
1045 op.mDurations != null ? op.mDurations.clone() : null,
1046 op.mProxyUids != null ? op.mProxyUids.clone() : null,
1047 op.mProxyPackageNames != null ? op.mProxyPackageNames.clone() : null);
1048 return entry;
1049 }
1050
Dianne Hackborn35654b62013-01-14 17:38:02 -08001051 @Override
1052 public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
1053 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
1054 Binder.getCallingPid(), Binder.getCallingUid(), null);
1055 ArrayList<AppOpsManager.PackageOps> res = null;
1056 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -07001057 final int uidStateCount = mUidStates.size();
1058 for (int i = 0; i < uidStateCount; i++) {
1059 UidState uidState = mUidStates.valueAt(i);
1060 if (uidState.pkgOps == null || uidState.pkgOps.isEmpty()) {
1061 continue;
1062 }
1063 ArrayMap<String, Ops> packages = uidState.pkgOps;
1064 final int packageCount = packages.size();
1065 for (int j = 0; j < packageCount; j++) {
1066 Ops pkgOps = packages.valueAt(j);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001067 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001068 if (resOps != null) {
1069 if (res == null) {
1070 res = new ArrayList<AppOpsManager.PackageOps>();
1071 }
1072 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -07001073 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001074 res.add(resPackage);
1075 }
1076 }
1077 }
1078 }
1079 return res;
1080 }
1081
1082 @Override
Dianne Hackborn72e39832013-01-18 18:36:09 -08001083 public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
1084 int[] ops) {
1085 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
1086 Binder.getCallingPid(), Binder.getCallingUid(), null);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001087 String resolvedPackageName = resolvePackageName(uid, packageName);
1088 if (resolvedPackageName == null) {
1089 return Collections.emptyList();
1090 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08001091 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001092 Ops pkgOps = getOpsRawLocked(uid, resolvedPackageName, false /* edit */,
1093 false /* uidMismatchExpected */);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001094 if (pkgOps == null) {
1095 return null;
1096 }
1097 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
1098 if (resOps == null) {
1099 return null;
1100 }
1101 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
1102 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -07001103 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001104 res.add(resPackage);
1105 return res;
1106 }
1107 }
1108
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001109 @Override
Svet Ganov8455ba22019-01-02 13:05:56 -08001110 public void getHistoricalOps(int uid, @NonNull String packageName,
Svet Ganov23c88db2019-01-22 20:38:11 -08001111 @Nullable List<String> opNames, long beginTimeMillis, long endTimeMillis,
Svet Ganovaf189e32019-02-15 18:45:29 -08001112 @OpFlags int flags, @NonNull RemoteCallback callback) {
Svet Ganov23c88db2019-01-22 20:38:11 -08001113 // Use the builder to validate arguments.
Svet Ganovaf189e32019-02-15 18:45:29 -08001114 new HistoricalOpsRequest.Builder(
Svet Ganov23c88db2019-01-22 20:38:11 -08001115 beginTimeMillis, endTimeMillis)
1116 .setUid(uid)
1117 .setPackageName(packageName)
1118 .setOpNames(opNames)
Svet Ganovaf189e32019-02-15 18:45:29 -08001119 .setFlags(flags)
Svet Ganov23c88db2019-01-22 20:38:11 -08001120 .build();
Svet Ganov8455ba22019-01-02 13:05:56 -08001121 Preconditions.checkNotNull(callback, "callback cannot be null");
Svet Ganovad0a49b2018-10-29 10:07:08 -07001122
1123 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
Svet Ganov8455ba22019-01-02 13:05:56 -08001124 Binder.getCallingPid(), Binder.getCallingUid(), "getHistoricalOps");
Svet Ganovad0a49b2018-10-29 10:07:08 -07001125
Svet Ganov23c88db2019-01-22 20:38:11 -08001126 final String[] opNamesArray = (opNames != null)
1127 ? opNames.toArray(new String[opNames.size()]) : null;
Svet Ganovad0a49b2018-10-29 10:07:08 -07001128
Svet Ganovaf189e32019-02-15 18:45:29 -08001129 // Must not hold the appops lock
1130 mHistoricalRegistry.getHistoricalOps(uid, packageName, opNamesArray,
1131 beginTimeMillis, endTimeMillis, flags, callback);
Svet Ganovad0a49b2018-10-29 10:07:08 -07001132 }
1133
1134 @Override
Svet Ganov8455ba22019-01-02 13:05:56 -08001135 public void getHistoricalOpsFromDiskRaw(int uid, @NonNull String packageName,
Svet Ganov23c88db2019-01-22 20:38:11 -08001136 @Nullable List<String> opNames, long beginTimeMillis, long endTimeMillis,
Svet Ganovaf189e32019-02-15 18:45:29 -08001137 @OpFlags int flags, @NonNull RemoteCallback callback) {
Svet Ganov23c88db2019-01-22 20:38:11 -08001138 // Use the builder to validate arguments.
Svet Ganovaf189e32019-02-15 18:45:29 -08001139 new HistoricalOpsRequest.Builder(
Svet Ganov23c88db2019-01-22 20:38:11 -08001140 beginTimeMillis, endTimeMillis)
1141 .setUid(uid)
1142 .setPackageName(packageName)
1143 .setOpNames(opNames)
Svet Ganovaf189e32019-02-15 18:45:29 -08001144 .setFlags(flags)
Svet Ganov23c88db2019-01-22 20:38:11 -08001145 .build();
Svet Ganov8455ba22019-01-02 13:05:56 -08001146 Preconditions.checkNotNull(callback, "callback cannot be null");
Svet Ganovad0a49b2018-10-29 10:07:08 -07001147
Svet Ganov8e5bf962019-03-19 23:59:03 -07001148 mContext.enforcePermission(Manifest.permission.MANAGE_APPOPS,
Svet Ganov8455ba22019-01-02 13:05:56 -08001149 Binder.getCallingPid(), Binder.getCallingUid(), "getHistoricalOps");
Svet Ganovad0a49b2018-10-29 10:07:08 -07001150
Svet Ganov23c88db2019-01-22 20:38:11 -08001151 final String[] opNamesArray = (opNames != null)
1152 ? opNames.toArray(new String[opNames.size()]) : null;
1153
Svet Ganov8455ba22019-01-02 13:05:56 -08001154 // Must not hold the appops lock
Svet Ganov23c88db2019-01-22 20:38:11 -08001155 mHistoricalRegistry.getHistoricalOpsFromDiskRaw(uid, packageName, opNamesArray,
Svet Ganovaf189e32019-02-15 18:45:29 -08001156 beginTimeMillis, endTimeMillis, flags, callback);
Svet Ganovad0a49b2018-10-29 10:07:08 -07001157 }
1158
1159 @Override
Svet Ganov8e5bf962019-03-19 23:59:03 -07001160 public void reloadNonHistoricalState() {
1161 mContext.enforcePermission(Manifest.permission.MANAGE_APPOPS,
1162 Binder.getCallingPid(), Binder.getCallingUid(), "reloadNonHistoricalState");
1163 writeState();
1164 readState();
1165 }
1166
1167 @Override
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001168 public List<AppOpsManager.PackageOps> getUidOps(int uid, int[] ops) {
1169 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
1170 Binder.getCallingPid(), Binder.getCallingUid(), null);
1171 synchronized (this) {
1172 UidState uidState = getUidStateLocked(uid, false);
1173 if (uidState == null) {
1174 return null;
1175 }
1176 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(uidState.opModes, ops);
1177 if (resOps == null) {
1178 return null;
1179 }
1180 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
1181 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
1182 null, uidState.uid, resOps);
1183 res.add(resPackage);
1184 return res;
1185 }
1186 }
1187
Dianne Hackborn607b4142013-08-02 18:10:10 -07001188 private void pruneOp(Op op, int uid, String packageName) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001189 if (!op.hasAnyTime()) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001190 Ops ops = getOpsRawLocked(uid, packageName, false /* edit */,
1191 false /* uidMismatchExpected */);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001192 if (ops != null) {
1193 ops.remove(op.op);
1194 if (ops.size() <= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -07001195 UidState uidState = ops.uidState;
1196 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
Dianne Hackborn607b4142013-08-02 18:10:10 -07001197 if (pkgOps != null) {
1198 pkgOps.remove(ops.packageName);
Svet Ganov2af57082015-07-30 08:44:20 -07001199 if (pkgOps.isEmpty()) {
1200 uidState.pkgOps = null;
1201 }
1202 if (uidState.isDefault()) {
1203 mUidStates.remove(uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001204 }
1205 }
1206 }
1207 }
1208 }
1209 }
1210
Svet Ganovaf189e32019-02-15 18:45:29 -08001211 private void enforceManageAppOpsModes(int callingPid, int callingUid, int targetUid) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07001212 if (callingPid == Process.myPid()) {
1213 return;
1214 }
1215 final int callingUser = UserHandle.getUserId(callingUid);
1216 synchronized (this) {
1217 if (mProfileOwners != null && mProfileOwners.get(callingUser, -1) == callingUid) {
1218 if (targetUid >= 0 && callingUser == UserHandle.getUserId(targetUid)) {
1219 // Profile owners are allowed to change modes but only for apps
1220 // within their user.
1221 return;
1222 }
1223 }
1224 }
1225 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
1226 Binder.getCallingPid(), Binder.getCallingUid(), null);
1227 }
1228
Dianne Hackborn72e39832013-01-18 18:36:09 -08001229 @Override
Svet Ganov2af57082015-07-30 08:44:20 -07001230 public void setUidMode(int code, int uid, int mode) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08001231 if (DEBUG) {
1232 Slog.i(TAG, "uid " + uid + " OP_" + opToName(code) + " := " + modeToName(mode)
1233 + " by uid " + Binder.getCallingUid());
1234 }
1235
Dianne Hackbornd5254412018-05-11 18:02:58 -07001236 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
Svet Ganov2af57082015-07-30 08:44:20 -07001237 verifyIncomingOp(code);
1238 code = AppOpsManager.opToSwitch(code);
1239
1240 synchronized (this) {
1241 final int defaultMode = AppOpsManager.opToDefaultMode(code);
1242
1243 UidState uidState = getUidStateLocked(uid, false);
1244 if (uidState == null) {
1245 if (mode == defaultMode) {
1246 return;
1247 }
1248 uidState = new UidState(uid);
1249 uidState.opModes = new SparseIntArray();
1250 uidState.opModes.put(code, mode);
1251 mUidStates.put(uid, uidState);
1252 scheduleWriteLocked();
1253 } else if (uidState.opModes == null) {
1254 if (mode != defaultMode) {
1255 uidState.opModes = new SparseIntArray();
1256 uidState.opModes.put(code, mode);
1257 scheduleWriteLocked();
1258 }
1259 } else {
Hai Zhang2b98fb32018-09-21 15:18:46 -07001260 if (uidState.opModes.indexOfKey(code) >= 0 && uidState.opModes.get(code) == mode) {
Svet Ganov2af57082015-07-30 08:44:20 -07001261 return;
1262 }
1263 if (mode == defaultMode) {
1264 uidState.opModes.delete(code);
1265 if (uidState.opModes.size() <= 0) {
1266 uidState.opModes = null;
1267 }
1268 } else {
1269 uidState.opModes.put(code, mode);
1270 }
1271 scheduleWriteLocked();
1272 }
Wei Wang711eb662019-03-21 18:24:17 -07001273 uidState.evalForegroundOps(mOpModeWatchers);
Svet Ganov2af57082015-07-30 08:44:20 -07001274 }
1275
Svetoslav215b44a2015-08-04 19:03:40 -07001276 String[] uidPackageNames = getPackagesForUid(uid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001277 ArrayMap<ModeCallback, ArraySet<String>> callbackSpecs = null;
Svet Ganov2af57082015-07-30 08:44:20 -07001278
riddle_hsu40b300f2015-11-23 13:22:03 +08001279 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001280 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001281 if (callbacks != null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001282 final int callbackCount = callbacks.size();
1283 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001284 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +08001285 ArraySet<String> changedPackages = new ArraySet<>();
1286 Collections.addAll(changedPackages, uidPackageNames);
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001287 if (callbackSpecs == null) {
1288 callbackSpecs = new ArrayMap<>();
1289 }
riddle_hsu40b300f2015-11-23 13:22:03 +08001290 callbackSpecs.put(callback, changedPackages);
1291 }
1292 }
1293
1294 for (String uidPackageName : uidPackageNames) {
1295 callbacks = mPackageModeWatchers.get(uidPackageName);
1296 if (callbacks != null) {
1297 if (callbackSpecs == null) {
1298 callbackSpecs = new ArrayMap<>();
Svet Ganov2af57082015-07-30 08:44:20 -07001299 }
riddle_hsu40b300f2015-11-23 13:22:03 +08001300 final int callbackCount = callbacks.size();
1301 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001302 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +08001303 ArraySet<String> changedPackages = callbackSpecs.get(callback);
1304 if (changedPackages == null) {
1305 changedPackages = new ArraySet<>();
1306 callbackSpecs.put(callback, changedPackages);
1307 }
1308 changedPackages.add(uidPackageName);
1309 }
Svet Ganov2af57082015-07-30 08:44:20 -07001310 }
1311 }
1312 }
1313
1314 if (callbackSpecs == null) {
1315 return;
1316 }
1317
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001318 for (int i = 0; i < callbackSpecs.size(); i++) {
1319 final ModeCallback callback = callbackSpecs.keyAt(i);
1320 final ArraySet<String> reportedPackageNames = callbackSpecs.valueAt(i);
1321 if (reportedPackageNames == null) {
1322 mHandler.sendMessage(PooledLambda.obtainMessage(
1323 AppOpsService::notifyOpChanged,
1324 this, callback, code, uid, (String) null));
1325
1326 } else {
1327 final int reportedPackageCount = reportedPackageNames.size();
1328 for (int j = 0; j < reportedPackageCount; j++) {
1329 final String reportedPackageName = reportedPackageNames.valueAt(j);
1330 mHandler.sendMessage(PooledLambda.obtainMessage(
1331 AppOpsService::notifyOpChanged,
1332 this, callback, code, uid, reportedPackageName));
Svet Ganov2af57082015-07-30 08:44:20 -07001333 }
1334 }
Svet Ganov2af57082015-07-30 08:44:20 -07001335 }
1336 }
1337
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001338 /**
1339 * Set all {@link #setMode (package) modes} for this uid to the default value.
1340 *
1341 * @param code The app-op
1342 * @param uid The uid
1343 */
1344 private void setAllPkgModesToDefault(int code, int uid) {
1345 synchronized (this) {
1346 UidState uidState = getUidStateLocked(uid, false);
1347 if (uidState == null) {
1348 return;
1349 }
1350
1351 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
1352 if (pkgOps == null) {
1353 return;
1354 }
1355
Svet Ganovaf189e32019-02-15 18:45:29 -08001356 boolean scheduleWrite = false;
1357
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001358 int numPkgs = pkgOps.size();
1359 for (int pkgNum = 0; pkgNum < numPkgs; pkgNum++) {
1360 Ops ops = pkgOps.valueAt(pkgNum);
1361
1362 Op op = ops.get(code);
1363 if (op == null) {
1364 continue;
1365 }
1366
1367 int defaultMode = AppOpsManager.opToDefaultMode(code);
1368 if (op.mode != defaultMode) {
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001369 op.mode = defaultMode;
Svet Ganovaf189e32019-02-15 18:45:29 -08001370 scheduleWrite = true;
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001371 }
1372 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001373
1374 if (scheduleWrite) {
1375 scheduleWriteLocked();
1376 }
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001377 }
1378 }
1379
Svet Ganov2af57082015-07-30 08:44:20 -07001380 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001381 public void setMode(int code, int uid, String packageName, int mode) {
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07001382 setMode(code, uid, packageName, mode, true, false);
1383 }
1384
1385 /**
1386 * Sets the mode for a certain op and uid.
1387 *
1388 * @param code The op code to set
1389 * @param uid The UID for which to set
1390 * @param packageName The package for which to set
1391 * @param mode The new mode to set
1392 * @param verifyUid Iff {@code true}, check that the package name belongs to the uid
1393 * @param isPrivileged Whether the package is privileged. (Only used if {@code verifyUid ==
1394 * false})
1395 */
1396 private void setMode(int code, int uid, @NonNull String packageName, int mode,
1397 boolean verifyUid, boolean isPrivileged) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07001398 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001399 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001400 ArraySet<ModeCallback> repCbs = null;
Dianne Hackbornc2293022013-02-06 23:14:49 -08001401 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001402 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -07001403 UidState uidState = getUidStateLocked(uid, false);
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07001404 Op op = getOpLocked(code, uid, packageName, true, verifyUid, isPrivileged);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001405 if (op != null) {
1406 if (op.mode != mode) {
1407 op.mode = mode;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001408 if (uidState != null) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001409 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001410 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001411 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001412 if (cbs != null) {
1413 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001414 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001415 }
1416 repCbs.addAll(cbs);
1417 }
1418 cbs = mPackageModeWatchers.get(packageName);
1419 if (cbs != null) {
1420 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001421 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001422 }
1423 repCbs.addAll(cbs);
1424 }
David Braunf5d83192013-09-16 13:43:51 -07001425 if (mode == AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001426 // If going into the default mode, prune this op
1427 // if there is nothing else interesting in it.
Dianne Hackborn607b4142013-08-02 18:10:10 -07001428 pruneOp(op, uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001429 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001430 scheduleFastWriteLocked();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001431 }
1432 }
1433 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001434 if (repCbs != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001435 mHandler.sendMessage(PooledLambda.obtainMessage(
1436 AppOpsService::notifyOpChanged,
1437 this, repCbs, code, uid, packageName));
Dianne Hackbornc2293022013-02-06 23:14:49 -08001438 }
1439 }
1440
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001441 private void notifyOpChanged(ArraySet<ModeCallback> callbacks, int code,
1442 int uid, String packageName) {
1443 for (int i = 0; i < callbacks.size(); i++) {
1444 final ModeCallback callback = callbacks.valueAt(i);
1445 notifyOpChanged(callback, code, uid, packageName);
1446 }
1447 }
1448
1449 private void notifyOpChanged(ModeCallback callback, int code,
1450 int uid, String packageName) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001451 if (uid != UID_ANY && callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001452 return;
1453 }
1454 // There are components watching for mode changes such as window manager
1455 // and location manager which are in our process. The callbacks in these
1456 // components may require permissions our remote caller does not have.
1457 final long identity = Binder.clearCallingIdentity();
1458 try {
1459 callback.mCallback.opChanged(code, uid, packageName);
1460 } catch (RemoteException e) {
1461 /* ignore */
1462 } finally {
1463 Binder.restoreCallingIdentity(identity);
1464 }
1465 }
1466
1467 private static HashMap<ModeCallback, ArrayList<ChangeRec>> addCallbacks(
1468 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks,
1469 int op, int uid, String packageName, ArraySet<ModeCallback> cbs) {
Dianne Hackborn607b4142013-08-02 18:10:10 -07001470 if (cbs == null) {
1471 return callbacks;
1472 }
1473 if (callbacks == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001474 callbacks = new HashMap<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001475 }
Svet Ganov2af57082015-07-30 08:44:20 -07001476 boolean duplicate = false;
Dianne Hackborn68d76552017-02-27 15:32:03 -08001477 final int N = cbs.size();
1478 for (int i=0; i<N; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001479 ModeCallback cb = cbs.valueAt(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001480 ArrayList<ChangeRec> reports = callbacks.get(cb);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001481 if (reports == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001482 reports = new ArrayList<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001483 callbacks.put(cb, reports);
Svet Ganov2af57082015-07-30 08:44:20 -07001484 } else {
1485 final int reportCount = reports.size();
1486 for (int j = 0; j < reportCount; j++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001487 ChangeRec report = reports.get(j);
1488 if (report.op == op && report.pkg.equals(packageName)) {
Svet Ganov2af57082015-07-30 08:44:20 -07001489 duplicate = true;
1490 break;
1491 }
1492 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001493 }
Svet Ganov2af57082015-07-30 08:44:20 -07001494 if (!duplicate) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001495 reports.add(new ChangeRec(op, uid, packageName));
Svet Ganov2af57082015-07-30 08:44:20 -07001496 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001497 }
1498 return callbacks;
1499 }
1500
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001501 static final class ChangeRec {
1502 final int op;
1503 final int uid;
1504 final String pkg;
1505
1506 ChangeRec(int _op, int _uid, String _pkg) {
1507 op = _op;
1508 uid = _uid;
1509 pkg = _pkg;
1510 }
1511 }
1512
Dianne Hackborn607b4142013-08-02 18:10:10 -07001513 @Override
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001514 public void resetAllModes(int reqUserId, String reqPackageName) {
1515 final int callingPid = Binder.getCallingPid();
1516 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001517 reqUserId = ActivityManager.handleIncomingUser(callingPid, callingUid, reqUserId,
1518 true, true, "resetAllModes", null);
Svet Ganov2af57082015-07-30 08:44:20 -07001519
1520 int reqUid = -1;
1521 if (reqPackageName != null) {
1522 try {
1523 reqUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -07001524 reqPackageName, PackageManager.MATCH_UNINSTALLED_PACKAGES, reqUserId);
Svet Ganov2af57082015-07-30 08:44:20 -07001525 } catch (RemoteException e) {
1526 /* ignore - local call */
1527 }
1528 }
1529
Dianne Hackbornd5254412018-05-11 18:02:58 -07001530 enforceManageAppOpsModes(callingPid, callingUid, reqUid);
1531
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001532 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks = null;
Dianne Hackborn607b4142013-08-02 18:10:10 -07001533 synchronized (this) {
1534 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -07001535 for (int i = mUidStates.size() - 1; i >= 0; i--) {
1536 UidState uidState = mUidStates.valueAt(i);
1537
1538 SparseIntArray opModes = uidState.opModes;
1539 if (opModes != null && (uidState.uid == reqUid || reqUid == -1)) {
1540 final int uidOpCount = opModes.size();
1541 for (int j = uidOpCount - 1; j >= 0; j--) {
1542 final int code = opModes.keyAt(j);
1543 if (AppOpsManager.opAllowsReset(code)) {
1544 opModes.removeAt(j);
1545 if (opModes.size() <= 0) {
1546 uidState.opModes = null;
1547 }
1548 for (String packageName : getPackagesForUid(uidState.uid)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001549 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -07001550 mOpModeWatchers.get(code));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001551 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -07001552 mPackageModeWatchers.get(packageName));
1553 }
1554 }
1555 }
1556 }
1557
1558 if (uidState.pkgOps == null) {
1559 continue;
1560 }
1561
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001562 if (reqUserId != UserHandle.USER_ALL
Svet Ganov2af57082015-07-30 08:44:20 -07001563 && reqUserId != UserHandle.getUserId(uidState.uid)) {
Alexandra Gherghinad6a98972014-08-04 17:05:34 +01001564 // Skip any ops for a different user
1565 continue;
1566 }
Svet Ganov2af57082015-07-30 08:44:20 -07001567
1568 Map<String, Ops> packages = uidState.pkgOps;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001569 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001570 boolean uidChanged = false;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001571 while (it.hasNext()) {
1572 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001573 String packageName = ent.getKey();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001574 if (reqPackageName != null && !reqPackageName.equals(packageName)) {
1575 // Skip any ops for a different package
1576 continue;
1577 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001578 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001579 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -07001580 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -07001581 if (AppOpsManager.opAllowsReset(curOp.op)
1582 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -07001583 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001584 changed = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001585 uidChanged = true;
Svet Ganovaf189e32019-02-15 18:45:29 -08001586 final int uid = curOp.uidState.uid;
1587 callbacks = addCallbacks(callbacks, curOp.op, uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -07001588 mOpModeWatchers.get(curOp.op));
Svet Ganovaf189e32019-02-15 18:45:29 -08001589 callbacks = addCallbacks(callbacks, curOp.op, uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -07001590 mPackageModeWatchers.get(packageName));
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001591 if (!curOp.hasAnyTime()) {
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001592 pkgOps.removeAt(j);
1593 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001594 }
1595 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001596 if (pkgOps.size() == 0) {
1597 it.remove();
1598 }
1599 }
Svet Ganov2af57082015-07-30 08:44:20 -07001600 if (uidState.isDefault()) {
1601 mUidStates.remove(uidState.uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001602 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001603 if (uidChanged) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001604 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001605 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001606 }
Svet Ganov2af57082015-07-30 08:44:20 -07001607
Dianne Hackborn607b4142013-08-02 18:10:10 -07001608 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001609 scheduleFastWriteLocked();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001610 }
1611 }
1612 if (callbacks != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001613 for (Map.Entry<ModeCallback, ArrayList<ChangeRec>> ent : callbacks.entrySet()) {
1614 ModeCallback cb = ent.getKey();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001615 ArrayList<ChangeRec> reports = ent.getValue();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001616 for (int i=0; i<reports.size(); i++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001617 ChangeRec rep = reports.get(i);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001618 mHandler.sendMessage(PooledLambda.obtainMessage(
1619 AppOpsService::notifyOpChanged,
1620 this, cb, rep.op, rep.uid, rep.pkg));
Dianne Hackborn607b4142013-08-02 18:10:10 -07001621 }
1622 }
1623 }
1624 }
1625
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001626 private void evalAllForegroundOpsLocked() {
1627 for (int uidi = mUidStates.size() - 1; uidi >= 0; uidi--) {
1628 final UidState uidState = mUidStates.valueAt(uidi);
1629 if (uidState.foregroundOps != null) {
1630 uidState.evalForegroundOps(mOpModeWatchers);
1631 }
1632 }
1633 }
1634
Dianne Hackbornc2293022013-02-06 23:14:49 -08001635 @Override
1636 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001637 startWatchingModeWithFlags(op, packageName, 0, callback);
1638 }
1639
1640 @Override
1641 public void startWatchingModeWithFlags(int op, String packageName, int flags,
1642 IAppOpsCallback callback) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001643 int watchedUid = -1;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001644 final int callingUid = Binder.getCallingUid();
1645 final int callingPid = Binder.getCallingPid();
Dianne Hackborn5376edd2018-06-05 13:21:16 -07001646 // TODO: should have a privileged permission to protect this.
1647 // Also, if the caller has requested WATCH_FOREGROUND_CHANGES, should we require
1648 // the USAGE_STATS permission since this can provide information about when an
1649 // app is in the foreground?
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001650 Preconditions.checkArgumentInRange(op, AppOpsManager.OP_NONE,
1651 AppOpsManager._NUM_OP - 1, "Invalid op code: " + op);
Svetoslav Ganov8de59712015-12-09 18:25:13 -08001652 if (callback == null) {
1653 return;
1654 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001655 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -07001656 op = (op != AppOpsManager.OP_NONE) ? AppOpsManager.opToSwitch(op) : op;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001657 ModeCallback cb = mModeWatchers.get(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -08001658 if (cb == null) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001659 cb = new ModeCallback(callback, watchedUid, flags, callingUid, callingPid);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001660 mModeWatchers.put(callback.asBinder(), cb);
1661 }
1662 if (op != AppOpsManager.OP_NONE) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001663 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(op);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001664 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08001665 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001666 mOpModeWatchers.put(op, cbs);
1667 }
1668 cbs.add(cb);
1669 }
1670 if (packageName != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001671 ArraySet<ModeCallback> cbs = mPackageModeWatchers.get(packageName);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001672 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08001673 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001674 mPackageModeWatchers.put(packageName, cbs);
1675 }
1676 cbs.add(cb);
1677 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001678 evalAllForegroundOpsLocked();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001679 }
1680 }
1681
1682 @Override
1683 public void stopWatchingMode(IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -08001684 if (callback == null) {
1685 return;
1686 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001687 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001688 ModeCallback cb = mModeWatchers.remove(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -08001689 if (cb != null) {
1690 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001691 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001692 ArraySet<ModeCallback> cbs = mOpModeWatchers.valueAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001693 cbs.remove(cb);
1694 if (cbs.size() <= 0) {
1695 mOpModeWatchers.removeAt(i);
1696 }
1697 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001698 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001699 ArraySet<ModeCallback> cbs = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001700 cbs.remove(cb);
1701 if (cbs.size() <= 0) {
1702 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001703 }
1704 }
1705 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001706 evalAllForegroundOpsLocked();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001707 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001708 }
1709
1710 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001711 public IBinder getToken(IBinder clientToken) {
1712 synchronized (this) {
1713 ClientState cs = mClients.get(clientToken);
1714 if (cs == null) {
1715 cs = new ClientState(clientToken);
1716 mClients.put(clientToken, cs);
1717 }
1718 return cs;
1719 }
1720 }
1721
Svet Ganovd873ae62018-06-25 16:39:23 -07001722 public CheckOpsDelegate getAppOpsServiceDelegate() {
1723 synchronized (this) {
1724 return mCheckOpsDelegate;
1725 }
1726 }
1727
1728 public void setAppOpsServiceDelegate(CheckOpsDelegate delegate) {
1729 synchronized (this) {
1730 mCheckOpsDelegate = delegate;
1731 }
1732 }
1733
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001734 @Override
Svet Ganov9d528a12018-12-19 17:23:11 -08001735 public int checkOperationRaw(int code, int uid, String packageName) {
1736 return checkOperationInternal(code, uid, packageName, true /*raw*/);
1737 }
1738
1739 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -08001740 public int checkOperation(int code, int uid, String packageName) {
Svet Ganov9d528a12018-12-19 17:23:11 -08001741 return checkOperationInternal(code, uid, packageName, false /*raw*/);
1742 }
1743
1744 private int checkOperationInternal(int code, int uid, String packageName, boolean raw) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001745 final CheckOpsDelegate delegate;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001746 synchronized (this) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001747 delegate = mCheckOpsDelegate;
1748 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001749 if (delegate == null) {
Svet Ganov9d528a12018-12-19 17:23:11 -08001750 return checkOperationImpl(code, uid, packageName, raw);
Todd Kennedy556efba2018-11-15 07:43:55 -08001751 }
Svet Ganov9d528a12018-12-19 17:23:11 -08001752 return delegate.checkOperation(code, uid, packageName, raw,
Svet Ganovd873ae62018-06-25 16:39:23 -07001753 AppOpsService.this::checkOperationImpl);
1754 }
1755
Svet Ganov9d528a12018-12-19 17:23:11 -08001756 private int checkOperationImpl(int code, int uid, String packageName,
1757 boolean raw) {
Todd Kennedy556efba2018-11-15 07:43:55 -08001758 verifyIncomingUid(uid);
1759 verifyIncomingOp(code);
1760 String resolvedPackageName = resolvePackageName(uid, packageName);
1761 if (resolvedPackageName == null) {
1762 return AppOpsManager.MODE_IGNORED;
1763 }
Svet Ganov9d528a12018-12-19 17:23:11 -08001764 return checkOperationUnchecked(code, uid, resolvedPackageName, raw);
Todd Kennedy556efba2018-11-15 07:43:55 -08001765 }
1766
Philip P. Moltmann724150d2019-03-11 17:01:05 -07001767 /**
1768 * @see #checkOperationUnchecked(int, int, String, boolean, boolean)
1769 */
1770 private @Mode int checkOperationUnchecked(int code, int uid, @NonNull String packageName,
1771 boolean raw) {
1772 return checkOperationUnchecked(code, uid, packageName, raw, true);
1773 }
1774
1775 /**
1776 * Get the mode of an app-op.
1777 *
1778 * @param code The code of the op
1779 * @param uid The uid of the package the op belongs to
1780 * @param packageName The package the op belongs to
1781 * @param raw If the raw state of eval-ed state should be checked.
1782 * @param verify If the code should check the package belongs to the uid
1783 *
1784 * @return The mode of the op
1785 */
1786 private @Mode int checkOperationUnchecked(int code, int uid, @NonNull String packageName,
1787 boolean raw, boolean verify) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001788 synchronized (this) {
Philip P. Moltmann724150d2019-03-11 17:01:05 -07001789 if (verify) {
1790 checkPackage(uid, packageName);
1791 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001792 if (isOpRestrictedLocked(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001793 return AppOpsManager.MODE_IGNORED;
1794 }
Svet Ganov2af57082015-07-30 08:44:20 -07001795 code = AppOpsManager.opToSwitch(code);
1796 UidState uidState = getUidStateLocked(uid, false);
Svet Ganovee438d42017-01-19 18:04:38 -08001797 if (uidState != null && uidState.opModes != null
1798 && uidState.opModes.indexOfKey(code) >= 0) {
Svet Ganov9d528a12018-12-19 17:23:11 -08001799 final int rawMode = uidState.opModes.get(code);
Svet Ganovaf189e32019-02-15 18:45:29 -08001800 return raw ? rawMode : uidState.evalMode(code, rawMode);
Svet Ganov2af57082015-07-30 08:44:20 -07001801 }
Philip P. Moltmann724150d2019-03-11 17:01:05 -07001802 Op op = getOpLocked(code, uid, packageName, false, verify, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001803 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -07001804 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001805 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001806 return raw ? op.mode : op.evalMode();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001807 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001808 }
1809
1810 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001811 public int checkAudioOperation(int code, int usage, int uid, String packageName) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001812 final CheckOpsDelegate delegate;
John Spurlock1af30c72014-03-10 08:33:35 -04001813 synchronized (this) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001814 delegate = mCheckOpsDelegate;
1815 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001816 if (delegate == null) {
1817 return checkAudioOperationImpl(code, usage, uid, packageName);
1818 }
Svet Ganovd873ae62018-06-25 16:39:23 -07001819 return delegate.checkAudioOperation(code, usage, uid, packageName,
1820 AppOpsService.this::checkAudioOperationImpl);
1821 }
1822
1823 private int checkAudioOperationImpl(int code, int usage, int uid, String packageName) {
Todd Kennedy556efba2018-11-15 07:43:55 -08001824 boolean suspended;
1825 try {
1826 suspended = isPackageSuspendedForUser(packageName, uid);
1827 } catch (IllegalArgumentException ex) {
1828 // Package not found.
1829 suspended = false;
1830 }
1831
1832 if (suspended) {
1833 Slog.i(TAG, "Audio disabled for suspended package=" + packageName
1834 + " for uid=" + uid);
1835 return AppOpsManager.MODE_IGNORED;
1836 }
1837
Svet Ganovd873ae62018-06-25 16:39:23 -07001838 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001839 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -04001840 if (mode != AppOpsManager.MODE_ALLOWED) {
1841 return mode;
1842 }
1843 }
1844 return checkOperation(code, uid, packageName);
1845 }
1846
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001847 private boolean isPackageSuspendedForUser(String pkg, int uid) {
Svet Ganov8d123f42019-04-09 17:11:12 -07001848 final long identity = Binder.clearCallingIdentity();
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001849 try {
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001850 return AppGlobals.getPackageManager().isPackageSuspendedForUser(
1851 pkg, UserHandle.getUserId(uid));
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001852 } catch (RemoteException re) {
1853 throw new SecurityException("Could not talk to package manager service");
Svet Ganov8d123f42019-04-09 17:11:12 -07001854 } finally {
1855 Binder.restoreCallingIdentity(identity);
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001856 }
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001857 }
1858
John Spurlock7b414672014-07-18 13:02:39 -04001859 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
1860 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1861 if (usageRestrictions != null) {
1862 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001863 if (r != null && !r.exceptionPackages.contains(packageName)) {
1864 return r.mode;
1865 }
1866 }
1867 return AppOpsManager.MODE_ALLOWED;
1868 }
1869
1870 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001871 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -04001872 String[] exceptionPackages) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07001873 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
John Spurlock1af30c72014-03-10 08:33:35 -04001874 verifyIncomingUid(uid);
1875 verifyIncomingOp(code);
1876 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001877 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1878 if (usageRestrictions == null) {
1879 usageRestrictions = new SparseArray<Restriction>();
1880 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -04001881 }
John Spurlock7b414672014-07-18 13:02:39 -04001882 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001883 if (mode != AppOpsManager.MODE_ALLOWED) {
1884 final Restriction r = new Restriction();
1885 r.mode = mode;
1886 if (exceptionPackages != null) {
1887 final int N = exceptionPackages.length;
1888 r.exceptionPackages = new ArraySet<String>(N);
1889 for (int i = 0; i < N; i++) {
1890 final String pkg = exceptionPackages[i];
1891 if (pkg != null) {
1892 r.exceptionPackages.add(pkg.trim());
1893 }
1894 }
1895 }
John Spurlock7b414672014-07-18 13:02:39 -04001896 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -04001897 }
1898 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001899
1900 mHandler.sendMessage(PooledLambda.obtainMessage(
Svet Ganov3a95f832018-03-23 17:44:30 -07001901 AppOpsService::notifyWatchersOfChange, this, code, UID_ANY));
John Spurlock1af30c72014-03-10 08:33:35 -04001902 }
1903
1904 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001905 public int checkPackage(int uid, String packageName) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001906 Preconditions.checkNotNull(packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001907 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001908 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1909 true /* uidMismatchExpected */);
1910 if (ops != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001911 return AppOpsManager.MODE_ALLOWED;
1912 } else {
1913 return AppOpsManager.MODE_ERRORED;
1914 }
1915 }
1916 }
1917
1918 @Override
Svet Ganovd873ae62018-06-25 16:39:23 -07001919 public int noteProxyOperation(int code, int proxyUid,
1920 String proxyPackageName, int proxiedUid, String proxiedPackageName) {
1921 verifyIncomingUid(proxyUid);
Svet Ganov99b60432015-06-27 13:15:22 -07001922 verifyIncomingOp(code);
Svet Ganovaf189e32019-02-15 18:45:29 -08001923
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001924 String resolveProxyPackageName = resolvePackageName(proxyUid, proxyPackageName);
1925 if (resolveProxyPackageName == null) {
1926 return AppOpsManager.MODE_IGNORED;
1927 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001928
1929 final boolean isProxyTrusted = mContext.checkPermission(
1930 Manifest.permission.UPDATE_APP_OPS_STATS, -1, proxyUid)
1931 == PackageManager.PERMISSION_GRANTED;
1932
1933 final int proxyFlags = isProxyTrusted ? AppOpsManager.OP_FLAG_TRUSTED_PROXY
1934 : AppOpsManager.OP_FLAG_UNTRUSTED_PROXY;
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001935 final int proxyMode = noteOperationUnchecked(code, proxyUid,
Svet Ganovaf189e32019-02-15 18:45:29 -08001936 resolveProxyPackageName, Process.INVALID_UID, null, proxyFlags);
Svet Ganov99b60432015-06-27 13:15:22 -07001937 if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
1938 return proxyMode;
1939 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001940
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001941 String resolveProxiedPackageName = resolvePackageName(proxiedUid, proxiedPackageName);
1942 if (resolveProxiedPackageName == null) {
1943 return AppOpsManager.MODE_IGNORED;
1944 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001945 final int proxiedFlags = isProxyTrusted ? AppOpsManager.OP_FLAG_TRUSTED_PROXIED
1946 : AppOpsManager.OP_FLAG_UNTRUSTED_PROXIED;
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001947 return noteOperationUnchecked(code, proxiedUid, resolveProxiedPackageName,
Svet Ganovaf189e32019-02-15 18:45:29 -08001948 proxyUid, resolveProxyPackageName, proxiedFlags);
Svet Ganov99b60432015-06-27 13:15:22 -07001949 }
1950
1951 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001952 public int noteOperation(int code, int uid, String packageName) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001953 final CheckOpsDelegate delegate;
1954 synchronized (this) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001955 delegate = mCheckOpsDelegate;
1956 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001957 if (delegate == null) {
1958 return noteOperationImpl(code, uid, packageName);
1959 }
Svet Ganovd873ae62018-06-25 16:39:23 -07001960 return delegate.noteOperation(code, uid, packageName,
1961 AppOpsService.this::noteOperationImpl);
1962 }
1963
1964 private int noteOperationImpl(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001965 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001966 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001967 String resolvedPackageName = resolvePackageName(uid, packageName);
1968 if (resolvedPackageName == null) {
1969 return AppOpsManager.MODE_IGNORED;
1970 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001971 return noteOperationUnchecked(code, uid, resolvedPackageName, Process.INVALID_UID, null,
1972 AppOpsManager.OP_FLAG_SELF);
Svet Ganov99b60432015-06-27 13:15:22 -07001973 }
1974
1975 private int noteOperationUnchecked(int code, int uid, String packageName,
Svet Ganovaf189e32019-02-15 18:45:29 -08001976 int proxyUid, String proxyPackageName, @OpFlags int flags) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001977 synchronized (this) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001978 final Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
Yohei Yukawaa965d652017-10-12 15:02:26 -07001979 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001980 if (ops == null) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -08001981 scheduleOpNotedIfNeededLocked(code, uid, packageName,
1982 AppOpsManager.MODE_IGNORED);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001983 if (DEBUG) Slog.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001984 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001985 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001986 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001987 final Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07001988 if (isOpRestrictedLocked(uid, code, packageName)) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -08001989 scheduleOpNotedIfNeededLocked(code, uid, packageName,
1990 AppOpsManager.MODE_IGNORED);
Jason Monk62062992014-05-06 09:55:28 -04001991 return AppOpsManager.MODE_IGNORED;
1992 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001993 final UidState uidState = ops.uidState;
Svet Ganovaf189e32019-02-15 18:45:29 -08001994 if (op.running) {
1995 final OpEntry entry = new OpEntry(op.op, op.running, op.mode, op.mAccessTimes,
1996 op.mRejectTimes, op.mDurations, op.mProxyUids, op.mProxyPackageNames);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001997 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
Svet Ganovaf189e32019-02-15 18:45:29 -08001998 + " code " + code + " time=" + entry.getLastAccessTime(uidState.state,
1999 uidState.state, flags) + " duration=" + entry.getLastDuration(
2000 uidState.state, uidState.state, flags));
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002001 }
Svet Ganovaf189e32019-02-15 18:45:29 -08002002
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002003 final int switchCode = AppOpsManager.opToSwitch(code);
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07002004 // If there is a non-default per UID policy (we set UID op mode only if
2005 // non-default) it takes over, otherwise use the per package policy.
2006 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002007 final int uidMode = uidState.evalMode(code, uidState.opModes.get(switchCode));
Svet Ganov2af57082015-07-30 08:44:20 -07002008 if (uidMode != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002009 if (DEBUG) Slog.d(TAG, "noteOperation: uid reject #" + uidMode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07002010 + switchCode + " (" + code + ") uid " + uid + " package "
2011 + packageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08002012 op.rejected(System.currentTimeMillis(), proxyUid, proxyPackageName,
2013 uidState.state, flags);
2014 mHistoricalRegistry.incrementOpRejected(code, uid, packageName,
2015 uidState.state, flags);
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002016 scheduleOpNotedIfNeededLocked(code, uid, packageName, uidMode);
Svet Ganov2af57082015-07-30 08:44:20 -07002017 return uidMode;
2018 }
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07002019 } else {
2020 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
Svet Ganovaf189e32019-02-15 18:45:29 -08002021 final int mode = switchOp.evalMode();
2022 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002023 if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + mode + " for code "
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07002024 + switchCode + " (" + code + ") uid " + uid + " package "
2025 + packageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08002026 op.rejected(System.currentTimeMillis(), proxyUid, proxyPackageName,
2027 uidState.state, flags);
2028 mHistoricalRegistry.incrementOpRejected(code, uid, packageName,
2029 uidState.state, flags);
2030 scheduleOpNotedIfNeededLocked(code, uid, packageName, mode);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002031 return mode;
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07002032 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002033 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002034 if (DEBUG) Slog.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002035 + " package " + packageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08002036 op.accessed(System.currentTimeMillis(), proxyUid, proxyPackageName,
2037 uidState.state, flags);
Svet Ganov8455ba22019-01-02 13:05:56 -08002038 mHistoricalRegistry.incrementOpAccessedCount(op.op, uid, packageName,
Svet Ganovaf189e32019-02-15 18:45:29 -08002039 uidState.state, flags);
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002040 scheduleOpNotedIfNeededLocked(code, uid, packageName,
2041 AppOpsManager.MODE_ALLOWED);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002042 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002043 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002044 }
2045
2046 @Override
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002047 public void startWatchingActive(int[] ops, IAppOpsActiveCallback callback) {
Svet Ganovf7b47252018-02-26 11:11:27 -08002048 int watchedUid = -1;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002049 final int callingUid = Binder.getCallingUid();
2050 final int callingPid = Binder.getCallingPid();
Svet Ganovf7b47252018-02-26 11:11:27 -08002051 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
2052 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002053 watchedUid = callingUid;
Svet Ganovf7b47252018-02-26 11:11:27 -08002054 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002055 if (ops != null) {
2056 Preconditions.checkArrayElementsInRange(ops, 0,
2057 AppOpsManager._NUM_OP - 1, "Invalid op code in: " + Arrays.toString(ops));
2058 }
2059 if (callback == null) {
2060 return;
2061 }
2062 synchronized (this) {
2063 SparseArray<ActiveCallback> callbacks = mActiveWatchers.get(callback.asBinder());
2064 if (callbacks == null) {
2065 callbacks = new SparseArray<>();
2066 mActiveWatchers.put(callback.asBinder(), callbacks);
2067 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002068 final ActiveCallback activeCallback = new ActiveCallback(callback, watchedUid,
2069 callingUid, callingPid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002070 for (int op : ops) {
2071 callbacks.put(op, activeCallback);
2072 }
2073 }
2074 }
2075
2076 @Override
2077 public void stopWatchingActive(IAppOpsActiveCallback callback) {
2078 if (callback == null) {
2079 return;
2080 }
2081 synchronized (this) {
2082 final SparseArray<ActiveCallback> activeCallbacks =
2083 mActiveWatchers.remove(callback.asBinder());
2084 if (activeCallbacks == null) {
2085 return;
2086 }
2087 final int callbackCount = activeCallbacks.size();
2088 for (int i = 0; i < callbackCount; i++) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002089 activeCallbacks.valueAt(i).destroy();
2090 }
2091 }
2092 }
2093
2094 @Override
2095 public void startWatchingNoted(@NonNull int[] ops, @NonNull IAppOpsNotedCallback callback) {
2096 int watchedUid = Process.INVALID_UID;
2097 final int callingUid = Binder.getCallingUid();
2098 final int callingPid = Binder.getCallingPid();
2099 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
2100 != PackageManager.PERMISSION_GRANTED) {
2101 watchedUid = callingUid;
2102 }
2103 Preconditions.checkArgument(!ArrayUtils.isEmpty(ops), "Ops cannot be null or empty");
2104 Preconditions.checkArrayElementsInRange(ops, 0, AppOpsManager._NUM_OP - 1,
2105 "Invalid op code in: " + Arrays.toString(ops));
2106 Preconditions.checkNotNull(callback, "Callback cannot be null");
2107 synchronized (this) {
2108 SparseArray<NotedCallback> callbacks = mNotedWatchers.get(callback.asBinder());
2109 if (callbacks == null) {
2110 callbacks = new SparseArray<>();
2111 mNotedWatchers.put(callback.asBinder(), callbacks);
2112 }
2113 final NotedCallback notedCallback = new NotedCallback(callback, watchedUid,
2114 callingUid, callingPid);
2115 for (int op : ops) {
2116 callbacks.put(op, notedCallback);
2117 }
2118 }
2119 }
2120
2121 @Override
2122 public void stopWatchingNoted(IAppOpsNotedCallback callback) {
2123 Preconditions.checkNotNull(callback, "Callback cannot be null");
2124 synchronized (this) {
2125 final SparseArray<NotedCallback> notedCallbacks =
2126 mNotedWatchers.remove(callback.asBinder());
2127 if (notedCallbacks == null) {
2128 return;
2129 }
2130 final int callbackCount = notedCallbacks.size();
2131 for (int i = 0; i < callbackCount; i++) {
2132 notedCallbacks.valueAt(i).destroy();
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002133 }
2134 }
2135 }
2136
2137 @Override
Svet Ganovf7b47252018-02-26 11:11:27 -08002138 public int startOperation(IBinder token, int code, int uid, String packageName,
2139 boolean startIfModeDefault) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002140 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08002141 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002142 String resolvedPackageName = resolvePackageName(uid, packageName);
2143 if (resolvedPackageName == null) {
2144 return AppOpsManager.MODE_IGNORED;
2145 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002146 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002147 synchronized (this) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002148 final Ops ops = getOpsRawLocked(uid, resolvedPackageName, true /* edit */,
Yohei Yukawaa965d652017-10-12 15:02:26 -07002149 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002150 if (ops == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002151 if (DEBUG) Slog.d(TAG, "startOperation: no op for code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002152 + " package " + resolvedPackageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07002153 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002154 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002155 final Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07002156 if (isOpRestrictedLocked(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -04002157 return AppOpsManager.MODE_IGNORED;
2158 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002159 final int switchCode = AppOpsManager.opToSwitch(code);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002160 final UidState uidState = ops.uidState;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002161 // If there is a non-default per UID policy (we set UID op mode only if
2162 // non-default) it takes over, otherwise use the per package policy.
Svet Ganovaf189e32019-02-15 18:45:29 -08002163 final int opCode = op.op;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002164 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002165 final int uidMode = uidState.evalMode(code, uidState.opModes.get(switchCode));
Svet Ganovf7b47252018-02-26 11:11:27 -08002166 if (uidMode != AppOpsManager.MODE_ALLOWED
2167 && (!startIfModeDefault || uidMode != AppOpsManager.MODE_DEFAULT)) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002168 if (DEBUG) Slog.d(TAG, "noteOperation: uid reject #" + uidMode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07002169 + switchCode + " (" + code + ") uid " + uid + " package "
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002170 + resolvedPackageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08002171 // We don't support proxy long running ops (start/stop)
2172 op.rejected(System.currentTimeMillis(), -1 /*proxyUid*/,
2173 null /*proxyPackage*/, uidState.state, AppOpsManager.OP_FLAG_SELF);
2174 mHistoricalRegistry.incrementOpRejected(opCode, uid, packageName,
2175 uidState.state, AppOpsManager.OP_FLAG_SELF);
Svet Ganov2af57082015-07-30 08:44:20 -07002176 return uidMode;
2177 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002178 } else {
2179 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
Svet Ganovaf189e32019-02-15 18:45:29 -08002180 final int mode = switchOp.evalMode();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002181 if (mode != AppOpsManager.MODE_ALLOWED
2182 && (!startIfModeDefault || mode != AppOpsManager.MODE_DEFAULT)) {
2183 if (DEBUG) Slog.d(TAG, "startOperation: reject #" + mode + " for code "
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002184 + switchCode + " (" + code + ") uid " + uid + " package "
2185 + resolvedPackageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08002186 // We don't support proxy long running ops (start/stop)
2187 op.rejected(System.currentTimeMillis(), -1 /*proxyUid*/,
2188 null /*proxyPackage*/, uidState.state, AppOpsManager.OP_FLAG_SELF);
2189 mHistoricalRegistry.incrementOpRejected(opCode, uid, packageName,
2190 uidState.state, AppOpsManager.OP_FLAG_SELF);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002191 return mode;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002192 }
Svet Ganov2af57082015-07-30 08:44:20 -07002193 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002194 if (DEBUG) Slog.d(TAG, "startOperation: allowing code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002195 + " package " + resolvedPackageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002196 if (op.startNesting == 0) {
2197 op.startRealtime = SystemClock.elapsedRealtime();
Svet Ganovaf189e32019-02-15 18:45:29 -08002198 // We don't support proxy long running ops (start/stop)
2199 op.started(System.currentTimeMillis(), uidState.state,
2200 AppOpsManager.OP_FLAG_SELF);
2201 mHistoricalRegistry.incrementOpAccessedCount(opCode, uid, packageName,
2202 uidState.state, AppOpsManager.OP_FLAG_SELF);
2203
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002204 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002205 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002206 op.startNesting++;
2207 uidState.startNesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002208 if (client.mStartedOps != null) {
2209 client.mStartedOps.add(op);
2210 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002211 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002212
2213 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002214 }
2215
2216 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002217 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002218 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08002219 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002220 String resolvedPackageName = resolvePackageName(uid, packageName);
2221 if (resolvedPackageName == null) {
2222 return;
2223 }
2224 if (!(token instanceof ClientState)) {
2225 return;
2226 }
2227 ClientState client = (ClientState) token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002228 synchronized (this) {
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07002229 Op op = getOpLocked(code, uid, resolvedPackageName, true, true, false);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002230 if (op == null) {
2231 return;
2232 }
Svet Ganovf7b47252018-02-26 11:11:27 -08002233 if (!client.mStartedOps.remove(op)) {
Svet Ganovf5d5af12018-03-18 11:51:17 -07002234 // We finish ops when packages get removed to guarantee no dangling
2235 // started ops. However, some part of the system may asynchronously
2236 // finish ops for an already gone package. Hence, finishing an op
2237 // for a non existing package is fine and we don't log as a wtf.
2238 final long identity = Binder.clearCallingIdentity();
2239 try {
2240 if (LocalServices.getService(PackageManagerInternal.class).getPackageUid(
2241 resolvedPackageName, 0, UserHandle.getUserId(uid)) < 0) {
2242 Slog.i(TAG, "Finishing op=" + AppOpsManager.opToName(code)
2243 + " for non-existing package=" + resolvedPackageName
2244 + " in uid=" + uid);
2245 return;
2246 }
2247 } finally {
2248 Binder.restoreCallingIdentity(identity);
2249 }
Svet Ganovaf189e32019-02-15 18:45:29 -08002250 Slog.wtf(TAG, "Operation not started: uid=" + op.uidState.uid + " pkg="
Svet Ganovf5d5af12018-03-18 11:51:17 -07002251 + op.packageName + " op=" + AppOpsManager.opToName(op.op));
Svet Ganov31d83ae2018-03-15 10:45:56 -07002252 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002253 }
Svet Ganova7a0db62018-02-27 20:08:01 -08002254 finishOperationLocked(op, /*finishNested*/ false);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002255 if (op.startNesting <= 0) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002256 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, false);
2257 }
2258 }
2259 }
2260
2261 private void scheduleOpActiveChangedIfNeededLocked(int code, int uid, String packageName,
2262 boolean active) {
2263 ArraySet<ActiveCallback> dispatchedCallbacks = null;
2264 final int callbackListCount = mActiveWatchers.size();
2265 for (int i = 0; i < callbackListCount; i++) {
2266 final SparseArray<ActiveCallback> callbacks = mActiveWatchers.valueAt(i);
2267 ActiveCallback callback = callbacks.get(code);
2268 if (callback != null) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002269 if (callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
Svet Ganovf7b47252018-02-26 11:11:27 -08002270 continue;
2271 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002272 if (dispatchedCallbacks == null) {
2273 dispatchedCallbacks = new ArraySet<>();
2274 }
2275 dispatchedCallbacks.add(callback);
2276 }
2277 }
2278 if (dispatchedCallbacks == null) {
2279 return;
2280 }
2281 mHandler.sendMessage(PooledLambda.obtainMessage(
2282 AppOpsService::notifyOpActiveChanged,
2283 this, dispatchedCallbacks, code, uid, packageName, active));
2284 }
2285
2286 private void notifyOpActiveChanged(ArraySet<ActiveCallback> callbacks,
2287 int code, int uid, String packageName, boolean active) {
2288 // There are components watching for mode changes such as window manager
2289 // and location manager which are in our process. The callbacks in these
2290 // components may require permissions our remote caller does not have.
2291 final long identity = Binder.clearCallingIdentity();
2292 try {
2293 final int callbackCount = callbacks.size();
2294 for (int i = 0; i < callbackCount; i++) {
2295 final ActiveCallback callback = callbacks.valueAt(i);
2296 try {
2297 callback.mCallback.opActiveChanged(code, uid, packageName, active);
2298 } catch (RemoteException e) {
2299 /* do nothing */
2300 }
2301 }
2302 } finally {
2303 Binder.restoreCallingIdentity(identity);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002304 }
2305 }
2306
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002307 private void scheduleOpNotedIfNeededLocked(int code, int uid, String packageName,
2308 int result) {
2309 ArraySet<NotedCallback> dispatchedCallbacks = null;
2310 final int callbackListCount = mNotedWatchers.size();
2311 for (int i = 0; i < callbackListCount; i++) {
2312 final SparseArray<NotedCallback> callbacks = mNotedWatchers.valueAt(i);
2313 final NotedCallback callback = callbacks.get(code);
2314 if (callback != null) {
2315 if (callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
2316 continue;
2317 }
2318 if (dispatchedCallbacks == null) {
2319 dispatchedCallbacks = new ArraySet<>();
2320 }
2321 dispatchedCallbacks.add(callback);
2322 }
2323 }
2324 if (dispatchedCallbacks == null) {
2325 return;
2326 }
2327 mHandler.sendMessage(PooledLambda.obtainMessage(
2328 AppOpsService::notifyOpChecked,
2329 this, dispatchedCallbacks, code, uid, packageName, result));
2330 }
2331
2332 private void notifyOpChecked(ArraySet<NotedCallback> callbacks,
2333 int code, int uid, String packageName, int result) {
2334 // There are components watching for checks in our process. The callbacks in
2335 // these components may require permissions our remote caller does not have.
2336 final long identity = Binder.clearCallingIdentity();
2337 try {
2338 final int callbackCount = callbacks.size();
2339 for (int i = 0; i < callbackCount; i++) {
2340 final NotedCallback callback = callbacks.valueAt(i);
2341 try {
2342 callback.mCallback.opNoted(code, uid, packageName, result);
2343 } catch (RemoteException e) {
2344 /* do nothing */
2345 }
2346 }
2347 } finally {
2348 Binder.restoreCallingIdentity(identity);
2349 }
2350 }
2351
Svet Ganovb9d71a62015-04-30 10:38:13 -07002352 @Override
2353 public int permissionToOpCode(String permission) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002354 if (permission == null) {
2355 return AppOpsManager.OP_NONE;
2356 }
Svet Ganovb9d71a62015-04-30 10:38:13 -07002357 return AppOpsManager.permissionToOpCode(permission);
2358 }
2359
Svet Ganova7a0db62018-02-27 20:08:01 -08002360 void finishOperationLocked(Op op, boolean finishNested) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002361 final int opCode = op.op;
2362 final int uid = op.uidState.uid;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002363 if (op.startNesting <= 1 || finishNested) {
2364 if (op.startNesting == 1 || finishNested) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002365 // We don't support proxy long running ops (start/stop)
2366 final long duration = SystemClock.elapsedRealtime() - op.startRealtime;
2367 op.finished(System.currentTimeMillis(), duration, op.uidState.state,
2368 AppOpsManager.OP_FLAG_SELF);
2369 mHistoricalRegistry.increaseOpAccessDuration(opCode, uid, op.packageName,
2370 op.uidState.state, AppOpsManager.OP_FLAG_SELF, duration);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002371 } else {
Svet Ganovaf189e32019-02-15 18:45:29 -08002372 final OpEntry entry = new OpEntry(op.op, op.running, op.mode, op.mAccessTimes,
2373 op.mRejectTimes, op.mDurations, op.mProxyUids, op.mProxyPackageNames);
2374 Slog.w(TAG, "Finishing op nesting under-run: uid " + uid + " pkg "
2375 + op.packageName + " code " + opCode + " time="
2376 + entry.getLastAccessTime(OP_FLAGS_ALL)
2377 + " duration=" + entry.getLastDuration(MAX_PRIORITY_UID_STATE,
2378 MIN_PRIORITY_UID_STATE, OP_FLAGS_ALL) + " nesting=" + op.startNesting);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002379 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002380 if (op.startNesting >= 1) {
2381 op.uidState.startNesting -= op.startNesting;
2382 }
2383 op.startNesting = 0;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002384 } else {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002385 op.startNesting--;
2386 op.uidState.startNesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002387 }
2388 }
2389
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002390 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002391 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002392 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002393 }
2394 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002395 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002396 }
2397 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
2398 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002399 }
2400
Dianne Hackborn961321f2013-02-05 17:22:41 -08002401 private void verifyIncomingOp(int op) {
2402 if (op >= 0 && op < AppOpsManager._NUM_OP) {
2403 return;
2404 }
2405 throw new IllegalArgumentException("Bad operation #" + op);
2406 }
2407
Philip P. Moltmann724150d2019-03-11 17:01:05 -07002408 private @Nullable UidState getUidStateLocked(int uid, boolean edit) {
Svet Ganov2af57082015-07-30 08:44:20 -07002409 UidState uidState = mUidStates.get(uid);
2410 if (uidState == null) {
2411 if (!edit) {
2412 return null;
2413 }
2414 uidState = new UidState(uid);
2415 mUidStates.put(uid, uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002416 } else {
2417 if (uidState.pendingStateCommitTime != 0) {
Dianne Hackborn9fb93502018-06-18 12:29:44 -07002418 if (uidState.pendingStateCommitTime < mLastRealtime) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002419 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002420 } else {
Dianne Hackborn9fb93502018-06-18 12:29:44 -07002421 mLastRealtime = SystemClock.elapsedRealtime();
2422 if (uidState.pendingStateCommitTime < mLastRealtime) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002423 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002424 }
2425 }
2426 }
Svet Ganov2af57082015-07-30 08:44:20 -07002427 }
2428 return uidState;
2429 }
2430
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002431 private void commitUidPendingStateLocked(UidState uidState) {
Wei Wange1f864e2019-03-28 18:12:18 -07002432 if (uidState.hasForegroundWatchers) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002433 for (int fgi = uidState.foregroundOps.size() - 1; fgi >= 0; fgi--) {
2434 if (!uidState.foregroundOps.valueAt(fgi)) {
2435 continue;
2436 }
2437 final int code = uidState.foregroundOps.keyAt(fgi);
Svet Ganovaf189e32019-02-15 18:45:29 -08002438 // For location ops we consider fg state only if the fg service
2439 // is of location type, for all other ops any fg service will do.
Wei Wang711eb662019-03-21 18:24:17 -07002440 final long firstUnrestrictedUidState = resolveFirstUnrestrictedUidState(code);
2441 final boolean resolvedLastFg = uidState.state <= firstUnrestrictedUidState;
2442 final boolean resolvedNowFg = uidState.pendingState <= firstUnrestrictedUidState;
2443 if (resolvedLastFg == resolvedNowFg) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002444 continue;
2445 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002446 final ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
2447 if (callbacks != null) {
2448 for (int cbi = callbacks.size() - 1; cbi >= 0; cbi--) {
2449 final ModeCallback callback = callbacks.valueAt(cbi);
2450 if ((callback.mFlags & AppOpsManager.WATCH_FOREGROUND_CHANGES) == 0
2451 || !callback.isWatchingUid(uidState.uid)) {
2452 continue;
2453 }
2454 boolean doAllPackages = uidState.opModes != null
Hai Zhang2b98fb32018-09-21 15:18:46 -07002455 && uidState.opModes.indexOfKey(code) >= 0
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002456 && uidState.opModes.get(code) == AppOpsManager.MODE_FOREGROUND;
2457 if (uidState.pkgOps != null) {
2458 for (int pkgi = uidState.pkgOps.size() - 1; pkgi >= 0; pkgi--) {
2459 final Op op = uidState.pkgOps.valueAt(pkgi).get(code);
Svet Ganovaf189e32019-02-15 18:45:29 -08002460 if (op == null) {
2461 continue;
2462 }
2463 if (doAllPackages || op.mode == AppOpsManager.MODE_FOREGROUND) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002464 mHandler.sendMessage(PooledLambda.obtainMessage(
2465 AppOpsService::notifyOpChanged,
2466 this, callback, code, uidState.uid,
2467 uidState.pkgOps.keyAt(pkgi)));
2468 }
2469 }
2470 }
2471 }
2472 }
2473 }
2474 }
Wei Wang711eb662019-03-21 18:24:17 -07002475 uidState.state = uidState.pendingState;
2476 uidState.pendingStateCommitTime = 0;
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002477 }
2478
Yohei Yukawaa965d652017-10-12 15:02:26 -07002479 private Ops getOpsRawLocked(int uid, String packageName, boolean edit,
2480 boolean uidMismatchExpected) {
Svet Ganov2af57082015-07-30 08:44:20 -07002481 UidState uidState = getUidStateLocked(uid, edit);
2482 if (uidState == null) {
2483 return null;
2484 }
2485
2486 if (uidState.pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002487 if (!edit) {
2488 return null;
2489 }
Svet Ganov2af57082015-07-30 08:44:20 -07002490 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002491 }
Svet Ganov2af57082015-07-30 08:44:20 -07002492
2493 Ops ops = uidState.pkgOps.get(packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002494 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002495 if (!edit) {
2496 return null;
2497 }
Jason Monk1c7c3192014-06-26 12:52:18 -04002498 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002499 // This is the first time we have seen this package name under this uid,
2500 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -08002501 if (uid != 0) {
2502 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002503 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -08002504 int pkgUid = -1;
2505 try {
Jason Monk1c7c3192014-06-26 12:52:18 -04002506 ApplicationInfo appInfo = ActivityThread.getPackageManager()
Jeff Sharkeycd654482016-01-08 17:42:11 -07002507 .getApplicationInfo(packageName,
Svet Ganovad0a49b2018-10-29 10:07:08 -07002508 PackageManager.MATCH_DIRECT_BOOT_AWARE
Svet Ganov8455ba22019-01-02 13:05:56 -08002509 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkeycd654482016-01-08 17:42:11 -07002510 UserHandle.getUserId(uid));
Jason Monk1c7c3192014-06-26 12:52:18 -04002511 if (appInfo != null) {
2512 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002513 isPrivileged = (appInfo.privateFlags
2514 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04002515 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08002516 pkgUid = resolveUid(packageName);
2517 if (pkgUid >= 0) {
Chien-Yu Chen75cade02016-01-11 10:56:21 -08002518 isPrivileged = false;
Jason Monk1c7c3192014-06-26 12:52:18 -04002519 }
Dianne Hackborn713df152013-05-17 11:27:57 -07002520 }
Jason Monk1c7c3192014-06-26 12:52:18 -04002521 } catch (RemoteException e) {
2522 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08002523 }
2524 if (pkgUid != uid) {
2525 // Oops! The package name is not valid for the uid they are calling
2526 // under. Abort.
Yohei Yukawaa965d652017-10-12 15:02:26 -07002527 if (!uidMismatchExpected) {
2528 RuntimeException ex = new RuntimeException("here");
2529 ex.fillInStackTrace();
2530 Slog.w(TAG, "Bad call: specified package " + packageName
2531 + " under uid " + uid + " but it is really " + pkgUid, ex);
2532 }
Dianne Hackborn514074f2013-02-11 10:52:46 -08002533 return null;
2534 }
2535 } finally {
2536 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002537 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002538 }
Svet Ganov2af57082015-07-30 08:44:20 -07002539 ops = new Ops(packageName, uidState, isPrivileged);
2540 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002541 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08002542 return ops;
2543 }
2544
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07002545 /**
2546 * Get the state of all ops for a package, <b>don't verify that package belongs to uid</b>.
2547 *
2548 * <p>Usually callers should use {@link #getOpLocked} and not call this directly.
2549 *
2550 * @param uid The uid the of the package
2551 * @param packageName The package name for which to get the state for
2552 * @param edit Iff {@code true} create the {@link Ops} object if not yet created
2553 * @param isPrivileged Whether the package is privileged or not
2554 *
2555 * @return The {@link Ops state} of all ops for the package
2556 */
2557 private @Nullable Ops getOpsRawNoVerifyLocked(int uid, @NonNull String packageName,
2558 boolean edit, boolean isPrivileged) {
2559 UidState uidState = getUidStateLocked(uid, edit);
2560 if (uidState == null) {
2561 return null;
2562 }
2563
2564 if (uidState.pkgOps == null) {
2565 if (!edit) {
2566 return null;
2567 }
2568 uidState.pkgOps = new ArrayMap<>();
2569 }
2570
2571 Ops ops = uidState.pkgOps.get(packageName);
2572 if (ops == null) {
2573 if (!edit) {
2574 return null;
2575 }
2576 ops = new Ops(packageName, uidState, isPrivileged);
2577 uidState.pkgOps.put(packageName, ops);
2578 }
2579 return ops;
2580 }
2581
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002582 private void scheduleWriteLocked() {
2583 if (!mWriteScheduled) {
2584 mWriteScheduled = true;
2585 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
2586 }
2587 }
2588
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002589 private void scheduleFastWriteLocked() {
2590 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002591 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002592 mFastWriteScheduled = true;
2593 mHandler.removeCallbacks(mWriteRunner);
2594 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002595 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002596 }
2597
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07002598 /**
2599 * Get the state of an op for a uid.
2600 *
2601 * @param code The code of the op
2602 * @param uid The uid the of the package
2603 * @param packageName The package name for which to get the state for
2604 * @param edit Iff {@code true} create the {@link Op} object if not yet created
2605 * @param verifyUid Iff {@code true} check that the package belongs to the uid
2606 * @param isPrivileged Whether the package is privileged or not (only used if {@code verifyUid
2607 * == false})
2608 *
2609 * @return The {@link Op state} of the op
2610 */
2611 private @Nullable Op getOpLocked(int code, int uid, @NonNull String packageName, boolean edit,
2612 boolean verifyUid, boolean isPrivileged) {
2613 Ops ops;
2614
2615 if (verifyUid) {
2616 ops = getOpsRawLocked(uid, packageName, edit, false /* uidMismatchExpected */);
2617 } else {
2618 ops = getOpsRawNoVerifyLocked(uid, packageName, edit, isPrivileged);
2619 }
2620
Dianne Hackborn72e39832013-01-18 18:36:09 -08002621 if (ops == null) {
2622 return null;
2623 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002624 return getOpLocked(ops, code, edit);
2625 }
2626
2627 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002628 Op op = ops.get(code);
2629 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002630 if (!edit) {
2631 return null;
2632 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002633 op = new Op(ops.uidState, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002634 ops.put(code, op);
2635 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002636 if (edit) {
2637 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002638 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002639 return op;
2640 }
2641
Svet Ganov442ed572016-08-17 17:29:43 -07002642 private boolean isOpRestrictedLocked(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04002643 int userHandle = UserHandle.getUserId(uid);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002644 final int restrictionSetCount = mOpUserRestrictions.size();
Ruben Brunk29931bc2016-03-11 00:24:26 -08002645
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002646 for (int i = 0; i < restrictionSetCount; i++) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002647 // For each client, check that the given op is not restricted, or that the given
2648 // package is exempt from the restriction.
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002649 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07002650 if (restrictionState.hasRestriction(code, packageName, userHandle)) {
2651 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
2652 // If we are the system, bypass user restrictions for certain codes
2653 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07002654 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
2655 false /* uidMismatchExpected */);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07002656 if ((ops != null) && ops.isPrivileged) {
2657 return false;
2658 }
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002659 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002660 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002661 return true;
Jason Monk1c7c3192014-06-26 12:52:18 -04002662 }
Jason Monk62062992014-05-06 09:55:28 -04002663 }
2664 return false;
2665 }
2666
Dianne Hackborn35654b62013-01-14 17:38:02 -08002667 void readState() {
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002668 int oldVersion = NO_VERSION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08002669 synchronized (mFile) {
2670 synchronized (this) {
2671 FileInputStream stream;
2672 try {
2673 stream = mFile.openRead();
2674 } catch (FileNotFoundException e) {
2675 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
2676 return;
2677 }
2678 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002679 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002680 try {
2681 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002682 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08002683 int type;
2684 while ((type = parser.next()) != XmlPullParser.START_TAG
2685 && type != XmlPullParser.END_DOCUMENT) {
2686 ;
2687 }
2688
2689 if (type != XmlPullParser.START_TAG) {
2690 throw new IllegalStateException("no start tag found");
2691 }
2692
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002693 final String versionString = parser.getAttributeValue(null, "v");
2694 if (versionString != null) {
2695 oldVersion = Integer.parseInt(versionString);
2696 }
2697
Dianne Hackborn35654b62013-01-14 17:38:02 -08002698 int outerDepth = parser.getDepth();
2699 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2700 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2701 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2702 continue;
2703 }
2704
2705 String tagName = parser.getName();
2706 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00002707 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07002708 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07002709 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002710 } else {
2711 Slog.w(TAG, "Unknown element under <app-ops>: "
2712 + parser.getName());
2713 XmlUtils.skipCurrentTag(parser);
2714 }
2715 }
2716 success = true;
2717 } catch (IllegalStateException e) {
2718 Slog.w(TAG, "Failed parsing " + e);
2719 } catch (NullPointerException e) {
2720 Slog.w(TAG, "Failed parsing " + e);
2721 } catch (NumberFormatException e) {
2722 Slog.w(TAG, "Failed parsing " + e);
2723 } catch (XmlPullParserException e) {
2724 Slog.w(TAG, "Failed parsing " + e);
2725 } catch (IOException e) {
2726 Slog.w(TAG, "Failed parsing " + e);
2727 } catch (IndexOutOfBoundsException e) {
2728 Slog.w(TAG, "Failed parsing " + e);
2729 } finally {
2730 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07002731 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002732 }
2733 try {
2734 stream.close();
2735 } catch (IOException e) {
2736 }
2737 }
2738 }
2739 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002740 synchronized (this) {
2741 upgradeLocked(oldVersion);
2742 }
2743 }
2744
2745 private void upgradeRunAnyInBackgroundLocked() {
2746 for (int i = 0; i < mUidStates.size(); i++) {
2747 final UidState uidState = mUidStates.valueAt(i);
2748 if (uidState == null) {
2749 continue;
2750 }
2751 if (uidState.opModes != null) {
2752 final int idx = uidState.opModes.indexOfKey(AppOpsManager.OP_RUN_IN_BACKGROUND);
2753 if (idx >= 0) {
2754 uidState.opModes.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND,
Svet Ganovaf189e32019-02-15 18:45:29 -08002755 uidState.opModes.valueAt(idx));
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002756 }
2757 }
2758 if (uidState.pkgOps == null) {
2759 continue;
2760 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002761 boolean changed = false;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002762 for (int j = 0; j < uidState.pkgOps.size(); j++) {
2763 Ops ops = uidState.pkgOps.valueAt(j);
2764 if (ops != null) {
2765 final Op op = ops.get(AppOpsManager.OP_RUN_IN_BACKGROUND);
2766 if (op != null && op.mode != AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002767 final Op copy = new Op(op.uidState, op.packageName,
Svet Ganovaf189e32019-02-15 18:45:29 -08002768 AppOpsManager.OP_RUN_ANY_IN_BACKGROUND);
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002769 copy.mode = op.mode;
2770 ops.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, copy);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002771 changed = true;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002772 }
2773 }
2774 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002775 if (changed) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002776 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002777 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002778 }
2779 }
2780
2781 private void upgradeLocked(int oldVersion) {
2782 if (oldVersion >= CURRENT_VERSION) {
2783 return;
2784 }
2785 Slog.d(TAG, "Upgrading app-ops xml from version " + oldVersion + " to " + CURRENT_VERSION);
2786 switch (oldVersion) {
2787 case NO_VERSION:
2788 upgradeRunAnyInBackgroundLocked();
2789 // fall through
2790 case 1:
2791 // for future upgrades
2792 }
2793 scheduleFastWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002794 }
2795
Svet Ganovaf189e32019-02-15 18:45:29 -08002796 private void readUidOps(XmlPullParser parser) throws NumberFormatException,
Svet Ganov2af57082015-07-30 08:44:20 -07002797 XmlPullParserException, IOException {
2798 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
2799 int outerDepth = parser.getDepth();
2800 int type;
2801 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2802 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2803 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2804 continue;
2805 }
2806
2807 String tagName = parser.getName();
2808 if (tagName.equals("op")) {
2809 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
2810 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
2811 UidState uidState = getUidStateLocked(uid, true);
2812 if (uidState.opModes == null) {
2813 uidState.opModes = new SparseIntArray();
2814 }
2815 uidState.opModes.put(code, mode);
2816 } else {
2817 Slog.w(TAG, "Unknown element under <uid-ops>: "
2818 + parser.getName());
2819 XmlUtils.skipCurrentTag(parser);
2820 }
2821 }
2822 }
2823
Svet Ganovaf189e32019-02-15 18:45:29 -08002824 private void readPackage(XmlPullParser parser)
2825 throws NumberFormatException, XmlPullParserException, IOException {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002826 String pkgName = parser.getAttributeValue(null, "n");
2827 int outerDepth = parser.getDepth();
2828 int type;
2829 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2830 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2831 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2832 continue;
2833 }
2834
2835 String tagName = parser.getName();
2836 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00002837 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002838 } else {
2839 Slog.w(TAG, "Unknown element under <pkg>: "
2840 + parser.getName());
2841 XmlUtils.skipCurrentTag(parser);
2842 }
2843 }
2844 }
2845
Svet Ganovaf189e32019-02-15 18:45:29 -08002846 private void readUid(XmlPullParser parser, String pkgName)
2847 throws NumberFormatException, XmlPullParserException, IOException {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002848 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Svet Ganovaf189e32019-02-15 18:45:29 -08002849 final UidState uidState = getUidStateLocked(uid, true);
Jason Monk1c7c3192014-06-26 12:52:18 -04002850 String isPrivilegedString = parser.getAttributeValue(null, "p");
2851 boolean isPrivileged = false;
2852 if (isPrivilegedString == null) {
2853 try {
2854 IPackageManager packageManager = ActivityThread.getPackageManager();
2855 if (packageManager != null) {
2856 ApplicationInfo appInfo = ActivityThread.getPackageManager()
2857 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
2858 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002859 isPrivileged = (appInfo.privateFlags
2860 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04002861 }
2862 } else {
2863 // Could not load data, don't add to cache so it will be loaded later.
2864 return;
2865 }
2866 } catch (RemoteException e) {
2867 Slog.w(TAG, "Could not contact PackageManager", e);
2868 }
2869 } else {
2870 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
2871 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002872 int outerDepth = parser.getDepth();
2873 int type;
2874 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2875 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2876 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2877 continue;
2878 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002879 String tagName = parser.getName();
2880 if (tagName.equals("op")) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002881 readOp(parser, uidState, pkgName, isPrivileged);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002882 } else {
2883 Slog.w(TAG, "Unknown element under <pkg>: "
2884 + parser.getName());
2885 XmlUtils.skipCurrentTag(parser);
2886 }
2887 }
Svet Ganovaf189e32019-02-15 18:45:29 -08002888 uidState.evalForegroundOps(mOpModeWatchers);
2889 }
2890
2891 private void readOp(XmlPullParser parser, @NonNull UidState uidState,
2892 @NonNull String pkgName, boolean isPrivileged) throws NumberFormatException,
2893 XmlPullParserException, IOException {
2894 Op op = new Op(uidState, pkgName,
2895 Integer.parseInt(parser.getAttributeValue(null, "n")));
2896
2897 final int mode = XmlUtils.readIntAttribute(parser, "m",
2898 AppOpsManager.opToDefaultMode(op.op));
2899 op.mode = mode;
2900
2901 int outerDepth = parser.getDepth();
2902 int type;
2903 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2904 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2905 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2906 continue;
2907 }
2908 String tagName = parser.getName();
2909 if (tagName.equals("st")) {
2910 final long key = XmlUtils.readLongAttribute(parser, "n");
2911
2912 final int flags = AppOpsManager.extractFlagsFromKey(key);
2913 final int state = AppOpsManager.extractUidStateFromKey(key);
2914
2915 final long accessTime = XmlUtils.readLongAttribute(parser, "t", 0);
2916 final long rejectTime = XmlUtils.readLongAttribute(parser, "r", 0);
2917 final long accessDuration = XmlUtils.readLongAttribute(parser, "d", 0);
2918 final String proxyPkg = XmlUtils.readStringAttribute(parser, "pp");
2919 final int proxyUid = XmlUtils.readIntAttribute(parser, "pu", 0);
2920
2921 if (accessTime > 0) {
2922 op.accessed(accessTime, proxyUid, proxyPkg, state, flags);
2923 }
2924 if (rejectTime > 0) {
2925 op.rejected(rejectTime, proxyUid, proxyPkg, state, flags);
2926 }
2927 if (accessDuration > 0) {
2928 op.running(accessTime, accessDuration, state, flags);
2929 }
2930 } else {
2931 Slog.w(TAG, "Unknown element under <op>: "
2932 + parser.getName());
2933 XmlUtils.skipCurrentTag(parser);
2934 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002935 }
Svet Ganovaf189e32019-02-15 18:45:29 -08002936
2937 if (uidState.pkgOps == null) {
2938 uidState.pkgOps = new ArrayMap<>();
2939 }
2940 Ops ops = uidState.pkgOps.get(pkgName);
2941 if (ops == null) {
2942 ops = new Ops(pkgName, uidState, isPrivileged);
2943 uidState.pkgOps.put(pkgName, ops);
2944 }
2945 ops.put(op.op, op);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002946 }
2947
2948 void writeState() {
2949 synchronized (mFile) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002950 FileOutputStream stream;
2951 try {
2952 stream = mFile.startWrite();
2953 } catch (IOException e) {
2954 Slog.w(TAG, "Failed to write state: " + e);
2955 return;
2956 }
2957
Dianne Hackborne17b4452018-01-10 13:15:40 -08002958 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
2959
Dianne Hackborn35654b62013-01-14 17:38:02 -08002960 try {
2961 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002962 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08002963 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002964 out.startTag(null, "app-ops");
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002965 out.attribute(null, "v", String.valueOf(CURRENT_VERSION));
Svet Ganov2af57082015-07-30 08:44:20 -07002966
2967 final int uidStateCount = mUidStates.size();
2968 for (int i = 0; i < uidStateCount; i++) {
2969 UidState uidState = mUidStates.valueAt(i);
2970 if (uidState.opModes != null && uidState.opModes.size() > 0) {
2971 out.startTag(null, "uid");
2972 out.attribute(null, "n", Integer.toString(uidState.uid));
2973 SparseIntArray uidOpModes = uidState.opModes;
2974 final int opCount = uidOpModes.size();
2975 for (int j = 0; j < opCount; j++) {
2976 final int op = uidOpModes.keyAt(j);
2977 final int mode = uidOpModes.valueAt(j);
2978 out.startTag(null, "op");
2979 out.attribute(null, "n", Integer.toString(op));
2980 out.attribute(null, "m", Integer.toString(mode));
2981 out.endTag(null, "op");
2982 }
2983 out.endTag(null, "uid");
2984 }
2985 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002986
2987 if (allOps != null) {
2988 String lastPkg = null;
2989 for (int i=0; i<allOps.size(); i++) {
2990 AppOpsManager.PackageOps pkg = allOps.get(i);
2991 if (!pkg.getPackageName().equals(lastPkg)) {
2992 if (lastPkg != null) {
2993 out.endTag(null, "pkg");
2994 }
2995 lastPkg = pkg.getPackageName();
2996 out.startTag(null, "pkg");
2997 out.attribute(null, "n", lastPkg);
2998 }
2999 out.startTag(null, "uid");
3000 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04003001 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07003002 Ops ops = getOpsRawLocked(pkg.getUid(), pkg.getPackageName(),
3003 false /* edit */, false /* uidMismatchExpected */);
Jason Monk1c7c3192014-06-26 12:52:18 -04003004 // Should always be present as the list of PackageOps is generated
3005 // from Ops.
3006 if (ops != null) {
3007 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
3008 } else {
3009 out.attribute(null, "p", Boolean.toString(false));
3010 }
3011 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08003012 List<AppOpsManager.OpEntry> ops = pkg.getOps();
3013 for (int j=0; j<ops.size(); j++) {
3014 AppOpsManager.OpEntry op = ops.get(j);
3015 out.startTag(null, "op");
3016 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07003017 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003018 out.attribute(null, "m", Integer.toString(op.getMode()));
3019 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003020
3021 final LongSparseArray keys = op.collectKeys();
3022 if (keys == null || keys.size() <= 0) {
Svet Ganov8e5bf962019-03-19 23:59:03 -07003023 out.endTag(null, "op");
Svet Ganovaf189e32019-02-15 18:45:29 -08003024 continue;
3025 }
3026
3027 final int keyCount = keys.size();
3028 for (int k = 0; k < keyCount; k++) {
3029 final long key = keys.keyAt(k);
3030
3031 final int uidState = AppOpsManager.extractUidStateFromKey(key);
3032 final int flags = AppOpsManager.extractFlagsFromKey(key);
3033
3034 final long accessTime = op.getLastAccessTime(
3035 uidState, uidState, flags);
3036 final long rejectTime = op.getLastRejectTime(
3037 uidState, uidState, flags);
3038 final long accessDuration = op.getLastDuration(
3039 uidState, uidState, flags);
3040 final String proxyPkg = op.getProxyPackageName(uidState, flags);
3041 final int proxyUid = op.getProxyUid(uidState, flags);
3042
3043 if (accessTime <= 0 && rejectTime <= 0 && accessDuration <= 0
3044 && proxyPkg == null && proxyUid < 0) {
3045 continue;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003046 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003047
3048 out.startTag(null, "st");
3049 out.attribute(null, "n", Long.toString(key));
3050 if (accessTime > 0) {
3051 out.attribute(null, "t", Long.toString(accessTime));
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003052 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003053 if (rejectTime > 0) {
3054 out.attribute(null, "r", Long.toString(rejectTime));
3055 }
3056 if (accessDuration > 0) {
3057 out.attribute(null, "d", Long.toString(accessDuration));
3058 }
3059 if (proxyPkg != null) {
3060 out.attribute(null, "pp", proxyPkg);
3061 }
3062 if (proxyUid >= 0) {
3063 out.attribute(null, "pu", Integer.toString(proxyUid));
3064 }
3065 out.endTag(null, "st");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003066 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003067
Dianne Hackborn35654b62013-01-14 17:38:02 -08003068 out.endTag(null, "op");
3069 }
3070 out.endTag(null, "uid");
3071 }
3072 if (lastPkg != null) {
3073 out.endTag(null, "pkg");
3074 }
3075 }
3076
3077 out.endTag(null, "app-ops");
3078 out.endDocument();
3079 mFile.finishWrite(stream);
3080 } catch (IOException e) {
3081 Slog.w(TAG, "Failed to write state, restoring backup.", e);
3082 mFile.failWrite(stream);
3083 }
3084 }
3085 }
3086
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003087 static class Shell extends ShellCommand {
3088 final IAppOpsService mInterface;
3089 final AppOpsService mInternal;
3090
3091 int userId = UserHandle.USER_SYSTEM;
3092 String packageName;
3093 String opStr;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003094 String modeStr;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003095 int op;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003096 int mode;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003097 int packageUid;
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003098 int nonpackageUid;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003099 final static Binder sBinder = new Binder();
3100 IBinder mToken;
Svet Ganovd563e932019-04-14 13:07:41 -07003101 boolean targetsUid;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003102
3103 Shell(IAppOpsService iface, AppOpsService internal) {
3104 mInterface = iface;
3105 mInternal = internal;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003106 try {
3107 mToken = mInterface.getToken(sBinder);
3108 } catch (RemoteException e) {
3109 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003110 }
3111
3112 @Override
3113 public int onCommand(String cmd) {
3114 return onShellCommand(this, cmd);
3115 }
3116
3117 @Override
3118 public void onHelp() {
3119 PrintWriter pw = getOutPrintWriter();
3120 dumpCommandHelp(pw);
3121 }
3122
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003123 static private int strOpToOp(String op, PrintWriter err) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003124 try {
3125 return AppOpsManager.strOpToOp(op);
3126 } catch (IllegalArgumentException e) {
3127 }
3128 try {
3129 return Integer.parseInt(op);
3130 } catch (NumberFormatException e) {
3131 }
3132 try {
3133 return AppOpsManager.strDebugOpToOp(op);
3134 } catch (IllegalArgumentException e) {
3135 err.println("Error: " + e.getMessage());
3136 return -1;
3137 }
3138 }
3139
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003140 static int strModeToMode(String modeStr, PrintWriter err) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003141 for (int i = AppOpsManager.MODE_NAMES.length - 1; i >= 0; i--) {
3142 if (AppOpsManager.MODE_NAMES[i].equals(modeStr)) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003143 return i;
3144 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003145 }
3146 try {
3147 return Integer.parseInt(modeStr);
3148 } catch (NumberFormatException e) {
3149 }
3150 err.println("Error: Mode " + modeStr + " is not valid");
3151 return -1;
3152 }
3153
3154 int parseUserOpMode(int defMode, PrintWriter err) throws RemoteException {
3155 userId = UserHandle.USER_CURRENT;
3156 opStr = null;
3157 modeStr = null;
3158 for (String argument; (argument = getNextArg()) != null;) {
3159 if ("--user".equals(argument)) {
3160 userId = UserHandle.parseUserArg(getNextArgRequired());
3161 } else {
3162 if (opStr == null) {
3163 opStr = argument;
3164 } else if (modeStr == null) {
3165 modeStr = argument;
3166 break;
3167 }
3168 }
3169 }
3170 if (opStr == null) {
3171 err.println("Error: Operation not specified.");
3172 return -1;
3173 }
3174 op = strOpToOp(opStr, err);
3175 if (op < 0) {
3176 return -1;
3177 }
3178 if (modeStr != null) {
3179 if ((mode=strModeToMode(modeStr, err)) < 0) {
3180 return -1;
3181 }
3182 } else {
3183 mode = defMode;
3184 }
3185 return 0;
3186 }
3187
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003188 int parseUserPackageOp(boolean reqOp, PrintWriter err) throws RemoteException {
3189 userId = UserHandle.USER_CURRENT;
3190 packageName = null;
3191 opStr = null;
3192 for (String argument; (argument = getNextArg()) != null;) {
3193 if ("--user".equals(argument)) {
3194 userId = UserHandle.parseUserArg(getNextArgRequired());
Svet Ganovd563e932019-04-14 13:07:41 -07003195 } else if ("--uid".equals(argument)) {
3196 targetsUid = true;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003197 } else {
3198 if (packageName == null) {
3199 packageName = argument;
3200 } else if (opStr == null) {
3201 opStr = argument;
3202 break;
3203 }
3204 }
3205 }
3206 if (packageName == null) {
3207 err.println("Error: Package name not specified.");
3208 return -1;
3209 } else if (opStr == null && reqOp) {
3210 err.println("Error: Operation not specified.");
3211 return -1;
3212 }
3213 if (opStr != null) {
3214 op = strOpToOp(opStr, err);
3215 if (op < 0) {
3216 return -1;
3217 }
3218 } else {
3219 op = AppOpsManager.OP_NONE;
3220 }
3221 if (userId == UserHandle.USER_CURRENT) {
3222 userId = ActivityManager.getCurrentUser();
3223 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003224 nonpackageUid = -1;
3225 try {
3226 nonpackageUid = Integer.parseInt(packageName);
3227 } catch (NumberFormatException e) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003228 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003229 if (nonpackageUid == -1 && packageName.length() > 1 && packageName.charAt(0) == 'u'
3230 && packageName.indexOf('.') < 0) {
3231 int i = 1;
3232 while (i < packageName.length() && packageName.charAt(i) >= '0'
3233 && packageName.charAt(i) <= '9') {
3234 i++;
3235 }
3236 if (i > 1 && i < packageName.length()) {
3237 String userStr = packageName.substring(1, i);
3238 try {
3239 int user = Integer.parseInt(userStr);
3240 char type = packageName.charAt(i);
3241 i++;
3242 int startTypeVal = i;
3243 while (i < packageName.length() && packageName.charAt(i) >= '0'
3244 && packageName.charAt(i) <= '9') {
3245 i++;
3246 }
3247 if (i > startTypeVal) {
3248 String typeValStr = packageName.substring(startTypeVal, i);
3249 try {
3250 int typeVal = Integer.parseInt(typeValStr);
3251 if (type == 'a') {
3252 nonpackageUid = UserHandle.getUid(user,
3253 typeVal + Process.FIRST_APPLICATION_UID);
3254 } else if (type == 's') {
3255 nonpackageUid = UserHandle.getUid(user, typeVal);
3256 }
3257 } catch (NumberFormatException e) {
3258 }
3259 }
3260 } catch (NumberFormatException e) {
3261 }
3262 }
3263 }
3264 if (nonpackageUid != -1) {
3265 packageName = null;
3266 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08003267 packageUid = resolveUid(packageName);
3268 if (packageUid < 0) {
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003269 packageUid = AppGlobals.getPackageManager().getPackageUid(packageName,
3270 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
3271 }
3272 if (packageUid < 0) {
3273 err.println("Error: No UID for " + packageName + " in user " + userId);
3274 return -1;
3275 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003276 }
3277 return 0;
3278 }
3279 }
3280
3281 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003282 FileDescriptor err, String[] args, ShellCallback callback,
3283 ResultReceiver resultReceiver) {
3284 (new Shell(this, this)).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003285 }
3286
3287 static void dumpCommandHelp(PrintWriter pw) {
3288 pw.println("AppOps service (appops) commands:");
3289 pw.println(" help");
3290 pw.println(" Print this help text.");
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003291 pw.println(" start [--user <USER_ID>] <PACKAGE | UID> <OP> ");
3292 pw.println(" Starts a given operation for a particular application.");
3293 pw.println(" stop [--user <USER_ID>] <PACKAGE | UID> <OP> ");
3294 pw.println(" Stops a given operation for a particular application.");
Svet Ganovb687fad2019-04-30 17:32:44 -07003295 pw.println(" set [--user <USER_ID>] <[--uid] PACKAGE | UID> <OP> <MODE>");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003296 pw.println(" Set the mode for a particular application and operation.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003297 pw.println(" get [--user <USER_ID>] <PACKAGE | UID> [<OP>]");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003298 pw.println(" Return the mode for a particular application and optional operation.");
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003299 pw.println(" query-op [--user <USER_ID>] <OP> [<MODE>]");
3300 pw.println(" Print all packages that currently have the given op in the given mode.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003301 pw.println(" reset [--user <USER_ID>] [<PACKAGE>]");
3302 pw.println(" Reset the given application or all applications to default modes.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003303 pw.println(" write-settings");
3304 pw.println(" Immediately write pending changes to storage.");
3305 pw.println(" read-settings");
3306 pw.println(" Read the last written settings, replacing current state in RAM.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003307 pw.println(" options:");
Svet Ganovb687fad2019-04-30 17:32:44 -07003308 pw.println(" <PACKAGE> an Android package name or its UID if prefixed by --uid");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003309 pw.println(" <OP> an AppOps operation.");
3310 pw.println(" <MODE> one of allow, ignore, deny, or default");
3311 pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
3312 pw.println(" specified, the current user is assumed.");
3313 }
3314
3315 static int onShellCommand(Shell shell, String cmd) {
3316 if (cmd == null) {
3317 return shell.handleDefaultCommands(cmd);
3318 }
3319 PrintWriter pw = shell.getOutPrintWriter();
3320 PrintWriter err = shell.getErrPrintWriter();
3321 try {
3322 switch (cmd) {
3323 case "set": {
3324 int res = shell.parseUserPackageOp(true, err);
3325 if (res < 0) {
3326 return res;
3327 }
3328 String modeStr = shell.getNextArg();
3329 if (modeStr == null) {
3330 err.println("Error: Mode not specified.");
3331 return -1;
3332 }
3333
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003334 final int mode = shell.strModeToMode(modeStr, err);
3335 if (mode < 0) {
3336 return -1;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003337 }
3338
Svet Ganovd563e932019-04-14 13:07:41 -07003339 if (!shell.targetsUid && shell.packageName != null) {
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003340 shell.mInterface.setMode(shell.op, shell.packageUid, shell.packageName,
3341 mode);
Svet Ganovd563e932019-04-14 13:07:41 -07003342 } else if (shell.targetsUid && shell.packageName != null) {
3343 try {
3344 final int uid = shell.mInternal.mContext.getPackageManager()
3345 .getPackageUid(shell.packageName, shell.userId);
3346 shell.mInterface.setUidMode(shell.op, uid, mode);
3347 } catch (PackageManager.NameNotFoundException e) {
3348 return -1;
3349 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003350 } else {
3351 shell.mInterface.setUidMode(shell.op, shell.nonpackageUid, mode);
3352 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003353 return 0;
3354 }
3355 case "get": {
3356 int res = shell.parseUserPackageOp(false, err);
3357 if (res < 0) {
3358 return res;
3359 }
3360
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003361 List<AppOpsManager.PackageOps> ops = new ArrayList<>();
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003362 if (shell.packageName != null) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003363 // Uid mode overrides package mode, so make sure it's also reported
3364 List<AppOpsManager.PackageOps> r = shell.mInterface.getUidOps(
3365 shell.packageUid,
3366 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
3367 if (r != null) {
3368 ops.addAll(r);
3369 }
3370 r = shell.mInterface.getOpsForPackage(
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003371 shell.packageUid, shell.packageName,
3372 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003373 if (r != null) {
3374 ops.addAll(r);
3375 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003376 } else {
3377 ops = shell.mInterface.getUidOps(
3378 shell.nonpackageUid,
3379 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
3380 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003381 if (ops == null || ops.size() <= 0) {
3382 pw.println("No operations.");
Svet Ganov82f09bc2018-01-12 22:08:40 -08003383 if (shell.op > AppOpsManager.OP_NONE && shell.op < AppOpsManager._NUM_OP) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003384 pw.println("Default mode: " + AppOpsManager.modeToName(
Svet Ganov82f09bc2018-01-12 22:08:40 -08003385 AppOpsManager.opToDefaultMode(shell.op)));
3386 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003387 return 0;
3388 }
3389 final long now = System.currentTimeMillis();
3390 for (int i=0; i<ops.size(); i++) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003391 AppOpsManager.PackageOps packageOps = ops.get(i);
3392 if (packageOps.getPackageName() == null) {
3393 pw.print("Uid mode: ");
3394 }
3395 List<AppOpsManager.OpEntry> entries = packageOps.getOps();
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003396 for (int j=0; j<entries.size(); j++) {
3397 AppOpsManager.OpEntry ent = entries.get(j);
3398 pw.print(AppOpsManager.opToName(ent.getOp()));
3399 pw.print(": ");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003400 pw.print(AppOpsManager.modeToName(ent.getMode()));
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003401 if (ent.getTime() != 0) {
3402 pw.print("; time=");
3403 TimeUtils.formatDuration(now - ent.getTime(), pw);
3404 pw.print(" ago");
3405 }
3406 if (ent.getRejectTime() != 0) {
3407 pw.print("; rejectTime=");
3408 TimeUtils.formatDuration(now - ent.getRejectTime(), pw);
3409 pw.print(" ago");
3410 }
3411 if (ent.getDuration() == -1) {
3412 pw.print(" (running)");
3413 } else if (ent.getDuration() != 0) {
3414 pw.print("; duration=");
3415 TimeUtils.formatDuration(ent.getDuration(), pw);
3416 }
3417 pw.println();
3418 }
3419 }
3420 return 0;
3421 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003422 case "query-op": {
3423 int res = shell.parseUserOpMode(AppOpsManager.MODE_IGNORED, err);
3424 if (res < 0) {
3425 return res;
3426 }
3427 List<AppOpsManager.PackageOps> ops = shell.mInterface.getPackagesForOps(
3428 new int[] {shell.op});
3429 if (ops == null || ops.size() <= 0) {
3430 pw.println("No operations.");
3431 return 0;
3432 }
3433 for (int i=0; i<ops.size(); i++) {
3434 final AppOpsManager.PackageOps pkg = ops.get(i);
3435 boolean hasMatch = false;
3436 final List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
3437 for (int j=0; j<entries.size(); j++) {
3438 AppOpsManager.OpEntry ent = entries.get(j);
3439 if (ent.getOp() == shell.op && ent.getMode() == shell.mode) {
3440 hasMatch = true;
3441 break;
3442 }
3443 }
3444 if (hasMatch) {
3445 pw.println(pkg.getPackageName());
3446 }
3447 }
3448 return 0;
3449 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003450 case "reset": {
3451 String packageName = null;
3452 int userId = UserHandle.USER_CURRENT;
3453 for (String argument; (argument = shell.getNextArg()) != null;) {
3454 if ("--user".equals(argument)) {
3455 String userStr = shell.getNextArgRequired();
3456 userId = UserHandle.parseUserArg(userStr);
3457 } else {
3458 if (packageName == null) {
3459 packageName = argument;
3460 } else {
3461 err.println("Error: Unsupported argument: " + argument);
3462 return -1;
3463 }
3464 }
3465 }
3466
3467 if (userId == UserHandle.USER_CURRENT) {
3468 userId = ActivityManager.getCurrentUser();
3469 }
3470
3471 shell.mInterface.resetAllModes(userId, packageName);
3472 pw.print("Reset all modes for: ");
3473 if (userId == UserHandle.USER_ALL) {
3474 pw.print("all users");
3475 } else {
3476 pw.print("user "); pw.print(userId);
3477 }
3478 pw.print(", ");
3479 if (packageName == null) {
3480 pw.println("all packages");
3481 } else {
3482 pw.print("package "); pw.println(packageName);
3483 }
3484 return 0;
3485 }
3486 case "write-settings": {
Dianne Hackbornd5254412018-05-11 18:02:58 -07003487 shell.mInternal.enforceManageAppOpsModes(Binder.getCallingPid(),
3488 Binder.getCallingUid(), -1);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003489 long token = Binder.clearCallingIdentity();
3490 try {
3491 synchronized (shell.mInternal) {
3492 shell.mInternal.mHandler.removeCallbacks(shell.mInternal.mWriteRunner);
3493 }
3494 shell.mInternal.writeState();
3495 pw.println("Current settings written.");
3496 } finally {
3497 Binder.restoreCallingIdentity(token);
3498 }
3499 return 0;
3500 }
3501 case "read-settings": {
Dianne Hackbornd5254412018-05-11 18:02:58 -07003502 shell.mInternal.enforceManageAppOpsModes(Binder.getCallingPid(),
3503 Binder.getCallingUid(), -1);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003504 long token = Binder.clearCallingIdentity();
3505 try {
3506 shell.mInternal.readState();
3507 pw.println("Last settings read.");
3508 } finally {
3509 Binder.restoreCallingIdentity(token);
3510 }
3511 return 0;
3512 }
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003513 case "start": {
3514 int res = shell.parseUserPackageOp(true, err);
3515 if (res < 0) {
3516 return res;
3517 }
3518
3519 if (shell.packageName != null) {
3520 shell.mInterface.startOperation(shell.mToken,
3521 shell.op, shell.packageUid, shell.packageName, true);
3522 } else {
3523 return -1;
3524 }
3525 return 0;
3526 }
3527 case "stop": {
3528 int res = shell.parseUserPackageOp(true, err);
3529 if (res < 0) {
3530 return res;
3531 }
3532
3533 if (shell.packageName != null) {
3534 shell.mInterface.finishOperation(shell.mToken,
3535 shell.op, shell.packageUid, shell.packageName);
3536 } else {
3537 return -1;
3538 }
3539 return 0;
3540 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003541 default:
3542 return shell.handleDefaultCommands(cmd);
3543 }
3544 } catch (RemoteException e) {
3545 pw.println("Remote exception: " + e);
3546 }
3547 return -1;
3548 }
3549
3550 private void dumpHelp(PrintWriter pw) {
3551 pw.println("AppOps service (appops) dump options:");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003552 pw.println(" -h");
3553 pw.println(" Print this help text.");
3554 pw.println(" --op [OP]");
3555 pw.println(" Limit output to data associated with the given app op code.");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003556 pw.println(" --mode [MODE]");
3557 pw.println(" Limit output to data associated with the given app op mode.");
3558 pw.println(" --package [PACKAGE]");
3559 pw.println(" Limit output to data associated with the given package name.");
Dianne Hackborn125dc532019-01-09 13:31:48 -08003560 pw.println(" --watchers");
3561 pw.println(" Only output the watcher sections.");
Svet Ganovaf189e32019-02-15 18:45:29 -08003562 pw.println(" --history");
3563 pw.println(" Output the historical data.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003564 }
3565
Svet Ganovaf189e32019-02-15 18:45:29 -08003566 private void dumpStatesLocked(@NonNull PrintWriter pw, @NonNull Op op,
3567 long now, @NonNull SimpleDateFormat sdf, @NonNull Date date, @NonNull String prefix) {
3568
3569 final OpEntry entry = new OpEntry(op.op, op.running, op.mode, op.mAccessTimes,
3570 op.mRejectTimes, op.mDurations, op.mProxyUids, op.mProxyPackageNames);
3571
3572 final LongSparseArray keys = entry.collectKeys();
3573 if (keys == null || keys.size() <= 0) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003574 return;
3575 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003576
3577 final int keyCount = keys.size();
3578 for (int k = 0; k < keyCount; k++) {
3579 final long key = keys.keyAt(k);
3580
3581 final int uidState = AppOpsManager.extractUidStateFromKey(key);
3582 final int flags = AppOpsManager.extractFlagsFromKey(key);
3583
3584 final long accessTime = entry.getLastAccessTime(
3585 uidState, uidState, flags);
3586 final long rejectTime = entry.getLastRejectTime(
3587 uidState, uidState, flags);
3588 final long accessDuration = entry.getLastDuration(
3589 uidState, uidState, flags);
3590 final String proxyPkg = entry.getProxyPackageName(uidState, flags);
3591 final int proxyUid = entry.getProxyUid(uidState, flags);
3592
3593 if (accessTime > 0) {
3594 pw.print(prefix);
3595 pw.print("Access: ");
3596 pw.print(AppOpsManager.keyToString(key));
3597 pw.print(" ");
3598 date.setTime(accessTime);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003599 pw.print(sdf.format(date));
3600 pw.print(" (");
Svet Ganovaf189e32019-02-15 18:45:29 -08003601 TimeUtils.formatDuration(accessTime - now, pw);
3602 pw.print(")");
3603 if (accessDuration > 0) {
3604 pw.print(" duration=");
3605 TimeUtils.formatDuration(accessDuration, pw);
3606 }
3607 if (proxyUid >= 0) {
3608 pw.print(" proxy[");
3609 pw.print("uid=");
3610 pw.print(proxyUid);
3611 pw.print(", pkg=");
3612 pw.print(proxyPkg);
3613 pw.print("]");
3614 }
3615 pw.println();
3616 }
3617
3618 if (rejectTime > 0) {
3619 pw.print(prefix);
3620 pw.print("Reject: ");
3621 pw.print(AppOpsManager.keyToString(key));
3622 date.setTime(rejectTime);
3623 pw.print(sdf.format(date));
3624 pw.print(" (");
3625 TimeUtils.formatDuration(rejectTime - now, pw);
3626 pw.print(")");
3627 if (proxyUid >= 0) {
3628 pw.print(" proxy[");
3629 pw.print("uid=");
3630 pw.print(proxyUid);
3631 pw.print(", pkg=");
3632 pw.print(proxyPkg);
3633 pw.print("]");
3634 }
3635 pw.println();
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003636 }
3637 }
3638 }
3639
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003640 @Override
3641 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06003642 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003643
Svet Ganov8455ba22019-01-02 13:05:56 -08003644 int dumpOp = OP_NONE;
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003645 String dumpPackage = null;
Svet Ganov8455ba22019-01-02 13:05:56 -08003646 int dumpUid = Process.INVALID_UID;
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003647 int dumpMode = -1;
Dianne Hackborn125dc532019-01-09 13:31:48 -08003648 boolean dumpWatchers = false;
Svet Ganovaf189e32019-02-15 18:45:29 -08003649 boolean dumpHistory = false;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003650
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003651 if (args != null) {
3652 for (int i=0; i<args.length; i++) {
3653 String arg = args[i];
3654 if ("-h".equals(arg)) {
3655 dumpHelp(pw);
3656 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07003657 } else if ("-a".equals(arg)) {
3658 // dump all data
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003659 } else if ("--op".equals(arg)) {
3660 i++;
3661 if (i >= args.length) {
3662 pw.println("No argument for --op option");
3663 return;
3664 }
3665 dumpOp = Shell.strOpToOp(args[i], pw);
3666 if (dumpOp < 0) {
3667 return;
3668 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003669 } else if ("--package".equals(arg)) {
3670 i++;
3671 if (i >= args.length) {
3672 pw.println("No argument for --package option");
3673 return;
3674 }
3675 dumpPackage = args[i];
3676 try {
3677 dumpUid = AppGlobals.getPackageManager().getPackageUid(dumpPackage,
3678 PackageManager.MATCH_KNOWN_PACKAGES | PackageManager.MATCH_INSTANT,
3679 0);
3680 } catch (RemoteException e) {
3681 }
3682 if (dumpUid < 0) {
3683 pw.println("Unknown package: " + dumpPackage);
3684 return;
3685 }
3686 dumpUid = UserHandle.getAppId(dumpUid);
3687 } else if ("--mode".equals(arg)) {
3688 i++;
3689 if (i >= args.length) {
3690 pw.println("No argument for --mode option");
3691 return;
3692 }
3693 dumpMode = Shell.strModeToMode(args[i], pw);
3694 if (dumpMode < 0) {
3695 return;
3696 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08003697 } else if ("--watchers".equals(arg)) {
3698 dumpWatchers = true;
Svet Ganovaf189e32019-02-15 18:45:29 -08003699 } else if ("--history".equals(arg)) {
3700 dumpHistory = true;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003701 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
3702 pw.println("Unknown option: " + arg);
3703 return;
3704 } else {
3705 pw.println("Unknown command: " + arg);
3706 return;
3707 }
3708 }
3709 }
3710
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003711 synchronized (this) {
3712 pw.println("Current AppOps Service state:");
Svet Ganovaf189e32019-02-15 18:45:29 -08003713 if (!dumpHistory && !dumpWatchers) {
3714 mConstants.dump(pw);
3715 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003716 pw.println();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003717 final long now = System.currentTimeMillis();
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003718 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003719 final long nowUptime = SystemClock.uptimeMillis();
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003720 final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
3721 final Date date = new Date();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003722 boolean needSep = false;
Dianne Hackborn125dc532019-01-09 13:31:48 -08003723 if (dumpOp < 0 && dumpMode < 0 && dumpPackage == null && mProfileOwners != null
Svet Ganovaf189e32019-02-15 18:45:29 -08003724 && !dumpWatchers && !dumpHistory) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07003725 pw.println(" Profile owners:");
3726 for (int poi = 0; poi < mProfileOwners.size(); poi++) {
3727 pw.print(" User #");
3728 pw.print(mProfileOwners.keyAt(poi));
3729 pw.print(": ");
3730 UserHandle.formatUid(pw, mProfileOwners.valueAt(poi));
3731 pw.println();
3732 }
3733 pw.println();
3734 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003735 if (mOpModeWatchers.size() > 0 && !dumpHistory) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003736 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003737 for (int i=0; i<mOpModeWatchers.size(); i++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003738 if (dumpOp >= 0 && dumpOp != mOpModeWatchers.keyAt(i)) {
3739 continue;
3740 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003741 boolean printedOpHeader = false;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003742 ArraySet<ModeCallback> callbacks = mOpModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003743 for (int j=0; j<callbacks.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003744 final ModeCallback cb = callbacks.valueAt(j);
Dianne Hackborn125dc532019-01-09 13:31:48 -08003745 if (dumpPackage != null
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003746 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3747 continue;
3748 }
3749 needSep = true;
3750 if (!printedHeader) {
3751 pw.println(" Op mode watchers:");
3752 printedHeader = true;
3753 }
3754 if (!printedOpHeader) {
3755 pw.print(" Op ");
3756 pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
3757 pw.println(":");
3758 printedOpHeader = true;
3759 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003760 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003761 pw.println(cb);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003762 }
3763 }
3764 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003765 if (mPackageModeWatchers.size() > 0 && dumpOp < 0 && !dumpHistory) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003766 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003767 for (int i=0; i<mPackageModeWatchers.size(); i++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003768 if (dumpPackage != null && !dumpPackage.equals(mPackageModeWatchers.keyAt(i))) {
3769 continue;
3770 }
3771 needSep = true;
3772 if (!printedHeader) {
3773 pw.println(" Package mode watchers:");
3774 printedHeader = true;
3775 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003776 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
3777 pw.println(":");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003778 ArraySet<ModeCallback> callbacks = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003779 for (int j=0; j<callbacks.size(); j++) {
3780 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08003781 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003782 }
3783 }
3784 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003785 if (mModeWatchers.size() > 0 && dumpOp < 0 && !dumpHistory) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003786 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003787 for (int i=0; i<mModeWatchers.size(); i++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003788 final ModeCallback cb = mModeWatchers.valueAt(i);
Dianne Hackborn125dc532019-01-09 13:31:48 -08003789 if (dumpPackage != null
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003790 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3791 continue;
3792 }
3793 needSep = true;
3794 if (!printedHeader) {
3795 pw.println(" All op mode watchers:");
3796 printedHeader = true;
3797 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003798 pw.print(" ");
3799 pw.print(Integer.toHexString(System.identityHashCode(mModeWatchers.keyAt(i))));
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003800 pw.print(": "); pw.println(cb);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003801 }
3802 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003803 if (mActiveWatchers.size() > 0 && dumpMode < 0) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003804 needSep = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003805 boolean printedHeader = false;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003806 for (int i = 0; i < mActiveWatchers.size(); i++) {
3807 final SparseArray<ActiveCallback> activeWatchers = mActiveWatchers.valueAt(i);
3808 if (activeWatchers.size() <= 0) {
3809 continue;
3810 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003811 final ActiveCallback cb = activeWatchers.valueAt(0);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003812 if (dumpOp >= 0 && activeWatchers.indexOfKey(dumpOp) < 0) {
3813 continue;
3814 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08003815 if (dumpPackage != null
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003816 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3817 continue;
3818 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003819 if (!printedHeader) {
3820 pw.println(" All op active watchers:");
3821 printedHeader = true;
3822 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003823 pw.print(" ");
3824 pw.print(Integer.toHexString(System.identityHashCode(
3825 mActiveWatchers.keyAt(i))));
3826 pw.println(" ->");
3827 pw.print(" [");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003828 final int opCount = activeWatchers.size();
3829 for (i = 0; i < opCount; i++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003830 if (i > 0) {
3831 pw.print(' ');
3832 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003833 pw.print(AppOpsManager.opToName(activeWatchers.keyAt(i)));
3834 if (i < opCount - 1) {
3835 pw.print(',');
3836 }
3837 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003838 pw.println("]");
3839 pw.print(" ");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003840 pw.println(cb);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003841 }
3842 }
Svet Ganovb3d2ae22018-12-17 22:06:15 -08003843 if (mNotedWatchers.size() > 0 && dumpMode < 0) {
3844 needSep = true;
3845 boolean printedHeader = false;
3846 for (int i = 0; i < mNotedWatchers.size(); i++) {
3847 final SparseArray<NotedCallback> notedWatchers = mNotedWatchers.valueAt(i);
3848 if (notedWatchers.size() <= 0) {
3849 continue;
3850 }
3851 final NotedCallback cb = notedWatchers.valueAt(0);
3852 if (dumpOp >= 0 && notedWatchers.indexOfKey(dumpOp) < 0) {
3853 continue;
3854 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08003855 if (dumpPackage != null
Svet Ganovb3d2ae22018-12-17 22:06:15 -08003856 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3857 continue;
3858 }
3859 if (!printedHeader) {
3860 pw.println(" All op noted watchers:");
3861 printedHeader = true;
3862 }
3863 pw.print(" ");
3864 pw.print(Integer.toHexString(System.identityHashCode(
3865 mNotedWatchers.keyAt(i))));
3866 pw.println(" ->");
3867 pw.print(" [");
3868 final int opCount = notedWatchers.size();
3869 for (i = 0; i < opCount; i++) {
3870 if (i > 0) {
3871 pw.print(' ');
3872 }
3873 pw.print(AppOpsManager.opToName(notedWatchers.keyAt(i)));
3874 if (i < opCount - 1) {
3875 pw.print(',');
3876 }
3877 }
3878 pw.println("]");
3879 pw.print(" ");
3880 pw.println(cb);
3881 }
3882 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003883 if (mClients.size() > 0 && dumpMode < 0 && !dumpWatchers && !dumpHistory) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003884 needSep = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003885 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003886 for (int i=0; i<mClients.size(); i++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003887 boolean printedClient = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003888 ClientState cs = mClients.valueAt(i);
Svet Ganovf7b47252018-02-26 11:11:27 -08003889 if (cs.mStartedOps.size() > 0) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003890 boolean printedStarted = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003891 for (int j=0; j<cs.mStartedOps.size(); j++) {
3892 Op op = cs.mStartedOps.get(j);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003893 if (dumpOp >= 0 && op.op != dumpOp) {
3894 continue;
3895 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003896 if (dumpPackage != null && !dumpPackage.equals(op.packageName)) {
3897 continue;
3898 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003899 if (!printedHeader) {
3900 pw.println(" Clients:");
3901 printedHeader = true;
3902 }
3903 if (!printedClient) {
3904 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
3905 pw.print(" "); pw.println(cs);
3906 printedClient = true;
3907 }
3908 if (!printedStarted) {
3909 pw.println(" Started ops:");
3910 printedStarted = true;
3911 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003912 pw.print(" "); pw.print("uid="); pw.print(op.uidState.uid);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003913 pw.print(" pkg="); pw.print(op.packageName);
3914 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
3915 }
3916 }
3917 }
3918 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003919 if (mAudioRestrictions.size() > 0 && dumpOp < 0 && dumpPackage != null
Svet Ganovaf189e32019-02-15 18:45:29 -08003920 && dumpMode < 0 && !dumpWatchers && !dumpWatchers) {
John Spurlock1af30c72014-03-10 08:33:35 -04003921 boolean printedHeader = false;
3922 for (int o=0; o<mAudioRestrictions.size(); o++) {
3923 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
3924 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
3925 for (int i=0; i<restrictions.size(); i++) {
3926 if (!printedHeader){
3927 pw.println(" Audio Restrictions:");
3928 printedHeader = true;
3929 needSep = true;
3930 }
John Spurlock7b414672014-07-18 13:02:39 -04003931 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04003932 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04003933 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04003934 Restriction r = restrictions.valueAt(i);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003935 pw.print(": mode="); pw.println(AppOpsManager.modeToName(r.mode));
John Spurlock1af30c72014-03-10 08:33:35 -04003936 if (!r.exceptionPackages.isEmpty()) {
3937 pw.println(" Exceptions:");
3938 for (int j=0; j<r.exceptionPackages.size(); j++) {
3939 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
3940 }
3941 }
3942 }
3943 }
3944 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003945 if (needSep) {
3946 pw.println();
3947 }
Svet Ganov2af57082015-07-30 08:44:20 -07003948 for (int i=0; i<mUidStates.size(); i++) {
3949 UidState uidState = mUidStates.valueAt(i);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003950 final SparseIntArray opModes = uidState.opModes;
3951 final ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
3952
Svet Ganovaf189e32019-02-15 18:45:29 -08003953 if (dumpWatchers || dumpHistory) {
Dianne Hackborn125dc532019-01-09 13:31:48 -08003954 continue;
3955 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003956 if (dumpOp >= 0 || dumpPackage != null || dumpMode >= 0) {
3957 boolean hasOp = dumpOp < 0 || (uidState.opModes != null
3958 && uidState.opModes.indexOfKey(dumpOp) >= 0);
3959 boolean hasPackage = dumpPackage == null;
3960 boolean hasMode = dumpMode < 0;
3961 if (!hasMode && opModes != null) {
3962 for (int opi = 0; !hasMode && opi < opModes.size(); opi++) {
3963 if (opModes.valueAt(opi) == dumpMode) {
3964 hasMode = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003965 }
3966 }
3967 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003968 if (pkgOps != null) {
3969 for (int pkgi = 0;
Svet Ganov8455ba22019-01-02 13:05:56 -08003970 (!hasOp || !hasPackage || !hasMode) && pkgi < pkgOps.size();
3971 pkgi++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003972 Ops ops = pkgOps.valueAt(pkgi);
3973 if (!hasOp && ops != null && ops.indexOfKey(dumpOp) >= 0) {
3974 hasOp = true;
3975 }
3976 if (!hasMode) {
3977 for (int opi = 0; !hasMode && opi < ops.size(); opi++) {
3978 if (ops.valueAt(opi).mode == dumpMode) {
3979 hasMode = true;
3980 }
3981 }
3982 }
3983 if (!hasPackage && dumpPackage.equals(ops.packageName)) {
3984 hasPackage = true;
3985 }
3986 }
3987 }
3988 if (uidState.foregroundOps != null && !hasOp) {
3989 if (uidState.foregroundOps.indexOfKey(dumpOp) > 0) {
3990 hasOp = true;
3991 }
3992 }
3993 if (!hasOp || !hasPackage || !hasMode) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003994 continue;
3995 }
3996 }
Svet Ganov2af57082015-07-30 08:44:20 -07003997
3998 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003999 pw.print(" state=");
Svet Ganovaf189e32019-02-15 18:45:29 -08004000 pw.println(AppOpsManager.getUidStateName(uidState.state));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004001 if (uidState.state != uidState.pendingState) {
4002 pw.print(" pendingState=");
Svet Ganovaf189e32019-02-15 18:45:29 -08004003 pw.println(AppOpsManager.getUidStateName(uidState.pendingState));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004004 }
4005 if (uidState.pendingStateCommitTime != 0) {
4006 pw.print(" pendingStateCommitTime=");
Dianne Hackborn9fb93502018-06-18 12:29:44 -07004007 TimeUtils.formatDuration(uidState.pendingStateCommitTime, nowElapsed, pw);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004008 pw.println();
4009 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07004010 if (uidState.startNesting != 0) {
4011 pw.print(" startNesting=");
4012 pw.println(uidState.startNesting);
4013 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004014 if (uidState.foregroundOps != null && (dumpMode < 0
4015 || dumpMode == AppOpsManager.MODE_FOREGROUND)) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004016 pw.println(" foregroundOps:");
4017 for (int j = 0; j < uidState.foregroundOps.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004018 if (dumpOp >= 0 && dumpOp != uidState.foregroundOps.keyAt(j)) {
4019 continue;
4020 }
4021 pw.print(" ");
4022 pw.print(AppOpsManager.opToName(uidState.foregroundOps.keyAt(j)));
4023 pw.print(": ");
4024 pw.println(uidState.foregroundOps.valueAt(j) ? "WATCHER" : "SILENT");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004025 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004026 pw.print(" hasForegroundWatchers=");
4027 pw.println(uidState.hasForegroundWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004028 }
Svet Ganovee438d42017-01-19 18:04:38 -08004029 needSep = true;
Svet Ganov2af57082015-07-30 08:44:20 -07004030
Svet Ganov2af57082015-07-30 08:44:20 -07004031 if (opModes != null) {
4032 final int opModeCount = opModes.size();
4033 for (int j = 0; j < opModeCount; j++) {
4034 final int code = opModes.keyAt(j);
4035 final int mode = opModes.valueAt(j);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004036 if (dumpOp >= 0 && dumpOp != code) {
4037 continue;
4038 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004039 if (dumpMode >= 0 && dumpMode != mode) {
4040 continue;
4041 }
Svet Ganov2af57082015-07-30 08:44:20 -07004042 pw.print(" "); pw.print(AppOpsManager.opToName(code));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004043 pw.print(": mode="); pw.println(AppOpsManager.modeToName(mode));
Svet Ganov2af57082015-07-30 08:44:20 -07004044 }
4045 }
4046
Svet Ganov2af57082015-07-30 08:44:20 -07004047 if (pkgOps == null) {
4048 continue;
4049 }
4050
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004051 for (int pkgi = 0; pkgi < pkgOps.size(); pkgi++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004052 final Ops ops = pkgOps.valueAt(pkgi);
4053 if (dumpPackage != null && !dumpPackage.equals(ops.packageName)) {
4054 continue;
4055 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004056 boolean printedPackage = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004057 for (int j=0; j<ops.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004058 final Op op = ops.valueAt(j);
Svet Ganovaf189e32019-02-15 18:45:29 -08004059 final int opCode = op.op;
4060 if (dumpOp >= 0 && dumpOp != opCode) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004061 continue;
4062 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004063 if (dumpMode >= 0 && dumpMode != op.mode) {
4064 continue;
4065 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004066 if (!printedPackage) {
4067 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
4068 printedPackage = true;
4069 }
Svet Ganovaf189e32019-02-15 18:45:29 -08004070 pw.print(" "); pw.print(AppOpsManager.opToName(opCode));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004071 pw.print(" ("); pw.print(AppOpsManager.modeToName(op.mode));
Svet Ganovaf189e32019-02-15 18:45:29 -08004072 final int switchOp = AppOpsManager.opToSwitch(opCode);
4073 if (switchOp != opCode) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004074 pw.print(" / switch ");
4075 pw.print(AppOpsManager.opToName(switchOp));
4076 final Op switchObj = ops.get(switchOp);
Svet Ganovaf189e32019-02-15 18:45:29 -08004077 int mode = switchObj != null ? switchObj.mode
4078 : AppOpsManager.opToDefaultMode(switchOp);
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004079 pw.print("="); pw.print(AppOpsManager.modeToName(mode));
4080 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004081 pw.println("): ");
Svet Ganovaf189e32019-02-15 18:45:29 -08004082 dumpStatesLocked(pw, op, now, sdf, date, " ");
4083 if (op.running) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07004084 pw.print(" Running start at: ");
4085 TimeUtils.formatDuration(nowElapsed-op.startRealtime, pw);
4086 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004087 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07004088 if (op.startNesting != 0) {
4089 pw.print(" startNesting=");
4090 pw.println(op.startNesting);
4091 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004092 }
4093 }
4094 }
Svet Ganovee438d42017-01-19 18:04:38 -08004095 if (needSep) {
4096 pw.println();
4097 }
4098
4099 final int userRestrictionCount = mOpUserRestrictions.size();
4100 for (int i = 0; i < userRestrictionCount; i++) {
4101 IBinder token = mOpUserRestrictions.keyAt(i);
4102 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
Dianne Hackborn125dc532019-01-09 13:31:48 -08004103 boolean printedTokenHeader = false;
4104
Svet Ganovaf189e32019-02-15 18:45:29 -08004105 if (dumpMode >= 0 || dumpWatchers || dumpHistory) {
Dianne Hackborn125dc532019-01-09 13:31:48 -08004106 continue;
4107 }
Svet Ganovee438d42017-01-19 18:04:38 -08004108
4109 final int restrictionCount = restrictionState.perUserRestrictions != null
4110 ? restrictionState.perUserRestrictions.size() : 0;
Dianne Hackborn125dc532019-01-09 13:31:48 -08004111 if (restrictionCount > 0 && dumpPackage == null) {
4112 boolean printedOpsHeader = false;
Svet Ganovee438d42017-01-19 18:04:38 -08004113 for (int j = 0; j < restrictionCount; j++) {
4114 int userId = restrictionState.perUserRestrictions.keyAt(j);
4115 boolean[] restrictedOps = restrictionState.perUserRestrictions.valueAt(j);
4116 if (restrictedOps == null) {
4117 continue;
4118 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08004119 if (dumpOp >= 0 && (dumpOp >= restrictedOps.length
4120 || !restrictedOps[dumpOp])) {
4121 continue;
4122 }
4123 if (!printedTokenHeader) {
4124 pw.println(" User restrictions for token " + token + ":");
4125 printedTokenHeader = true;
4126 }
4127 if (!printedOpsHeader) {
4128 pw.println(" Restricted ops:");
4129 printedOpsHeader = true;
4130 }
Svet Ganovee438d42017-01-19 18:04:38 -08004131 StringBuilder restrictedOpsValue = new StringBuilder();
4132 restrictedOpsValue.append("[");
4133 final int restrictedOpCount = restrictedOps.length;
4134 for (int k = 0; k < restrictedOpCount; k++) {
4135 if (restrictedOps[k]) {
4136 if (restrictedOpsValue.length() > 1) {
4137 restrictedOpsValue.append(", ");
4138 }
4139 restrictedOpsValue.append(AppOpsManager.opToName(k));
4140 }
4141 }
4142 restrictedOpsValue.append("]");
4143 pw.print(" "); pw.print("user: "); pw.print(userId);
4144 pw.print(" restricted ops: "); pw.println(restrictedOpsValue);
4145 }
4146 }
4147
4148 final int excludedPackageCount = restrictionState.perUserExcludedPackages != null
4149 ? restrictionState.perUserExcludedPackages.size() : 0;
Dianne Hackborn125dc532019-01-09 13:31:48 -08004150 if (excludedPackageCount > 0 && dumpOp < 0) {
4151 boolean printedPackagesHeader = false;
Svet Ganovee438d42017-01-19 18:04:38 -08004152 for (int j = 0; j < excludedPackageCount; j++) {
4153 int userId = restrictionState.perUserExcludedPackages.keyAt(j);
4154 String[] packageNames = restrictionState.perUserExcludedPackages.valueAt(j);
Dianne Hackborn125dc532019-01-09 13:31:48 -08004155 if (packageNames == null) {
4156 continue;
4157 }
4158 boolean hasPackage;
4159 if (dumpPackage != null) {
4160 hasPackage = false;
4161 for (String pkg : packageNames) {
4162 if (dumpPackage.equals(pkg)) {
4163 hasPackage = true;
4164 break;
4165 }
4166 }
4167 } else {
4168 hasPackage = true;
4169 }
4170 if (!hasPackage) {
4171 continue;
4172 }
4173 if (!printedTokenHeader) {
4174 pw.println(" User restrictions for token " + token + ":");
4175 printedTokenHeader = true;
4176 }
4177 if (!printedPackagesHeader) {
4178 pw.println(" Excluded packages:");
4179 printedPackagesHeader = true;
4180 }
Svet Ganovee438d42017-01-19 18:04:38 -08004181 pw.print(" "); pw.print("user: "); pw.print(userId);
4182 pw.print(" packages: "); pw.println(Arrays.toString(packageNames));
4183 }
4184 }
4185 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004186 }
Svet Ganov8455ba22019-01-02 13:05:56 -08004187
4188 // Must not hold the appops lock
Svet Ganovaf189e32019-02-15 18:45:29 -08004189 if (dumpHistory && !dumpWatchers) {
4190 mHistoricalRegistry.dump(" ", pw, dumpUid, dumpPackage, dumpOp);
4191 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004192 }
John Spurlock1af30c72014-03-10 08:33:35 -04004193
4194 private static final class Restriction {
4195 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
4196 int mode;
4197 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
4198 }
Jason Monk62062992014-05-06 09:55:28 -04004199
4200 @Override
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004201 public void setUserRestrictions(Bundle restrictions, IBinder token, int userHandle) {
Jason Monk62062992014-05-06 09:55:28 -04004202 checkSystemUid("setUserRestrictions");
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004203 Preconditions.checkNotNull(restrictions);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004204 Preconditions.checkNotNull(token);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004205 for (int i = 0; i < AppOpsManager._NUM_OP; i++) {
Jason Monk62062992014-05-06 09:55:28 -04004206 String restriction = AppOpsManager.opToRestriction(i);
Suprabh Shukla64e0dcb2016-05-24 16:23:11 -07004207 if (restriction != null) {
4208 setUserRestrictionNoCheck(i, restrictions.getBoolean(restriction, false), token,
4209 userHandle, null);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004210 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004211 }
4212 }
4213
4214 @Override
Ruben Brunk29931bc2016-03-11 00:24:26 -08004215 public void setUserRestriction(int code, boolean restricted, IBinder token, int userHandle,
4216 String[] exceptionPackages) {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004217 if (Binder.getCallingPid() != Process.myPid()) {
4218 mContext.enforcePermission(Manifest.permission.MANAGE_APP_OPS_RESTRICTIONS,
4219 Binder.getCallingPid(), Binder.getCallingUid(), null);
4220 }
4221 if (userHandle != UserHandle.getCallingUserId()) {
4222 if (mContext.checkCallingOrSelfPermission(Manifest.permission
4223 .INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
4224 && mContext.checkCallingOrSelfPermission(Manifest.permission
4225 .INTERACT_ACROSS_USERS) != PackageManager.PERMISSION_GRANTED) {
4226 throw new SecurityException("Need INTERACT_ACROSS_USERS_FULL or"
4227 + " INTERACT_ACROSS_USERS to interact cross user ");
Jason Monk62062992014-05-06 09:55:28 -04004228 }
4229 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004230 verifyIncomingOp(code);
4231 Preconditions.checkNotNull(token);
Ruben Brunk29931bc2016-03-11 00:24:26 -08004232 setUserRestrictionNoCheck(code, restricted, token, userHandle, exceptionPackages);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004233 }
4234
4235 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
Ruben Brunk29931bc2016-03-11 00:24:26 -08004236 int userHandle, String[] exceptionPackages) {
Svet Ganov442ed572016-08-17 17:29:43 -07004237 synchronized (AppOpsService.this) {
4238 ClientRestrictionState restrictionState = mOpUserRestrictions.get(token);
4239
4240 if (restrictionState == null) {
4241 try {
4242 restrictionState = new ClientRestrictionState(token);
4243 } catch (RemoteException e) {
4244 return;
4245 }
4246 mOpUserRestrictions.put(token, restrictionState);
Ruben Brunk29931bc2016-03-11 00:24:26 -08004247 }
Svet Ganov442ed572016-08-17 17:29:43 -07004248
4249 if (restrictionState.setRestriction(code, restricted, exceptionPackages, userHandle)) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004250 mHandler.sendMessage(PooledLambda.obtainMessage(
Svet Ganov3a95f832018-03-23 17:44:30 -07004251 AppOpsService::notifyWatchersOfChange, this, code, UID_ANY));
Svet Ganov442ed572016-08-17 17:29:43 -07004252 }
4253
4254 if (restrictionState.isDefault()) {
4255 mOpUserRestrictions.remove(token);
4256 restrictionState.destroy();
4257 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08004258 }
Julia Reynoldsbb21c252016-04-05 16:01:49 -04004259 }
4260
Svet Ganov3a95f832018-03-23 17:44:30 -07004261 private void notifyWatchersOfChange(int code, int uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004262 final ArraySet<ModeCallback> clonedCallbacks;
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004263 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004264 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004265 if (callbacks == null) {
4266 return;
4267 }
Dianne Hackborn68d76552017-02-27 15:32:03 -08004268 clonedCallbacks = new ArraySet<>(callbacks);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004269 }
4270
Svet Ganov3a95f832018-03-23 17:44:30 -07004271 notifyOpChanged(clonedCallbacks, code, uid, null);
Jason Monk62062992014-05-06 09:55:28 -04004272 }
4273
4274 @Override
4275 public void removeUser(int userHandle) throws RemoteException {
4276 checkSystemUid("removeUser");
Svet Ganov442ed572016-08-17 17:29:43 -07004277 synchronized (AppOpsService.this) {
4278 final int tokenCount = mOpUserRestrictions.size();
4279 for (int i = tokenCount - 1; i >= 0; i--) {
4280 ClientRestrictionState opRestrictions = mOpUserRestrictions.valueAt(i);
4281 opRestrictions.removeUser(userHandle);
4282 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07004283 removeUidsForUserLocked(userHandle);
4284 }
4285 }
4286
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004287 @Override
4288 public boolean isOperationActive(int code, int uid, String packageName) {
Svet Ganovf7b47252018-02-26 11:11:27 -08004289 if (Binder.getCallingUid() != uid) {
4290 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
4291 != PackageManager.PERMISSION_GRANTED) {
4292 return false;
4293 }
4294 }
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004295 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004296 final String resolvedPackageName = resolvePackageName(uid, packageName);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004297 if (resolvedPackageName == null) {
4298 return false;
4299 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004300 synchronized (AppOpsService.this) {
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004301 for (int i = mClients.size() - 1; i >= 0; i--) {
4302 final ClientState client = mClients.valueAt(i);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004303 for (int j = client.mStartedOps.size() - 1; j >= 0; j--) {
4304 final Op op = client.mStartedOps.get(j);
Svet Ganovaf189e32019-02-15 18:45:29 -08004305 if (op.op == code && op.uidState.uid == uid) return true;
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004306 }
4307 }
4308 }
4309 return false;
4310 }
4311
Svet Ganov8455ba22019-01-02 13:05:56 -08004312 @Override
4313 public void setHistoryParameters(@AppOpsManager.HistoricalMode int mode,
4314 long baseSnapshotInterval, int compressionStep) {
4315 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4316 "setHistoryParameters");
4317 // Must not hold the appops lock
4318 mHistoricalRegistry.setHistoryParameters(mode, baseSnapshotInterval, compressionStep);
4319 }
4320
4321 @Override
4322 public void offsetHistory(long offsetMillis) {
4323 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4324 "offsetHistory");
4325 // Must not hold the appops lock
4326 mHistoricalRegistry.offsetHistory(offsetMillis);
4327 }
4328
4329 @Override
4330 public void addHistoricalOps(HistoricalOps ops) {
4331 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4332 "addHistoricalOps");
4333 // Must not hold the appops lock
4334 mHistoricalRegistry.addHistoricalOps(ops);
4335 }
4336
4337 @Override
4338 public void resetHistoryParameters() {
4339 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4340 "resetHistoryParameters");
4341 // Must not hold the appops lock
4342 mHistoricalRegistry.resetHistoryParameters();
4343 }
4344
4345 @Override
4346 public void clearHistory() {
4347 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4348 "clearHistory");
4349 // Must not hold the appops lock
4350 mHistoricalRegistry.clearHistory();
4351 }
4352
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07004353 private void removeUidsForUserLocked(int userHandle) {
4354 for (int i = mUidStates.size() - 1; i >= 0; --i) {
4355 final int uid = mUidStates.keyAt(i);
4356 if (UserHandle.getUserId(uid) == userHandle) {
4357 mUidStates.removeAt(i);
4358 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004359 }
4360 }
4361
Jason Monk62062992014-05-06 09:55:28 -04004362 private void checkSystemUid(String function) {
4363 int uid = Binder.getCallingUid();
4364 if (uid != Process.SYSTEM_UID) {
4365 throw new SecurityException(function + " must by called by the system");
4366 }
4367 }
4368
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004369 private static String resolvePackageName(int uid, String packageName) {
Svet Ganov82f09bc2018-01-12 22:08:40 -08004370 if (uid == Process.ROOT_UID) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004371 return "root";
4372 } else if (uid == Process.SHELL_UID) {
4373 return "com.android.shell";
Svet Ganov82f09bc2018-01-12 22:08:40 -08004374 } else if (uid == Process.MEDIA_UID) {
4375 return "media";
4376 } else if (uid == Process.AUDIOSERVER_UID) {
4377 return "audioserver";
4378 } else if (uid == Process.CAMERASERVER_UID) {
4379 return "cameraserver";
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004380 } else if (uid == Process.SYSTEM_UID && packageName == null) {
4381 return "android";
4382 }
4383 return packageName;
4384 }
4385
Svet Ganov82f09bc2018-01-12 22:08:40 -08004386 private static int resolveUid(String packageName) {
4387 if (packageName == null) {
4388 return -1;
4389 }
4390 switch (packageName) {
4391 case "root":
4392 return Process.ROOT_UID;
4393 case "shell":
4394 return Process.SHELL_UID;
4395 case "media":
4396 return Process.MEDIA_UID;
4397 case "audioserver":
4398 return Process.AUDIOSERVER_UID;
4399 case "cameraserver":
4400 return Process.CAMERASERVER_UID;
4401 }
4402 return -1;
4403 }
4404
Svet Ganov2af57082015-07-30 08:44:20 -07004405 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07004406 String[] packageNames = null;
Philip P. Moltmann159d98b2018-12-20 08:30:53 -08004407
4408 // Very early during boot the package manager is not yet or not yet fully started. At this
4409 // time there are no packages yet.
4410 if (AppGlobals.getPackageManager() != null) {
4411 try {
4412 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
4413 } catch (RemoteException e) {
4414 /* ignore - local call */
4415 }
Svet Ganov2af57082015-07-30 08:44:20 -07004416 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07004417 if (packageNames == null) {
4418 return EmptyArray.STRING;
4419 }
4420 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07004421 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004422
4423 private final class ClientRestrictionState implements DeathRecipient {
4424 private final IBinder token;
4425 SparseArray<boolean[]> perUserRestrictions;
4426 SparseArray<String[]> perUserExcludedPackages;
4427
4428 public ClientRestrictionState(IBinder token)
4429 throws RemoteException {
4430 token.linkToDeath(this, 0);
4431 this.token = token;
4432 }
4433
4434 public boolean setRestriction(int code, boolean restricted,
4435 String[] excludedPackages, int userId) {
4436 boolean changed = false;
4437
4438 if (perUserRestrictions == null && restricted) {
4439 perUserRestrictions = new SparseArray<>();
4440 }
4441
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004442 int[] users;
4443 if (userId == UserHandle.USER_ALL) {
4444 List<UserInfo> liveUsers = UserManager.get(mContext).getUsers(false);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004445
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004446 users = new int[liveUsers.size()];
4447 for (int i = 0; i < liveUsers.size(); i++) {
4448 users[i] = liveUsers.get(i).id;
4449 }
4450 } else {
4451 users = new int[]{userId};
4452 }
4453
4454 if (perUserRestrictions != null) {
4455 int numUsers = users.length;
4456
4457 for (int i = 0; i < numUsers; i++) {
4458 int thisUserId = users[i];
4459
4460 boolean[] userRestrictions = perUserRestrictions.get(thisUserId);
4461 if (userRestrictions == null && restricted) {
4462 userRestrictions = new boolean[AppOpsManager._NUM_OP];
4463 perUserRestrictions.put(thisUserId, userRestrictions);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004464 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004465 if (userRestrictions != null && userRestrictions[code] != restricted) {
4466 userRestrictions[code] = restricted;
4467 if (!restricted && isDefault(userRestrictions)) {
4468 perUserRestrictions.remove(thisUserId);
4469 userRestrictions = null;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004470 }
4471 changed = true;
4472 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004473
4474 if (userRestrictions != null) {
4475 final boolean noExcludedPackages = ArrayUtils.isEmpty(excludedPackages);
4476 if (perUserExcludedPackages == null && !noExcludedPackages) {
4477 perUserExcludedPackages = new SparseArray<>();
4478 }
4479 if (perUserExcludedPackages != null && !Arrays.equals(excludedPackages,
4480 perUserExcludedPackages.get(thisUserId))) {
4481 if (noExcludedPackages) {
4482 perUserExcludedPackages.remove(thisUserId);
4483 if (perUserExcludedPackages.size() <= 0) {
4484 perUserExcludedPackages = null;
4485 }
4486 } else {
4487 perUserExcludedPackages.put(thisUserId, excludedPackages);
4488 }
4489 changed = true;
4490 }
4491 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004492 }
4493 }
4494
4495 return changed;
4496 }
4497
4498 public boolean hasRestriction(int restriction, String packageName, int userId) {
4499 if (perUserRestrictions == null) {
4500 return false;
4501 }
4502 boolean[] restrictions = perUserRestrictions.get(userId);
4503 if (restrictions == null) {
4504 return false;
4505 }
4506 if (!restrictions[restriction]) {
4507 return false;
4508 }
4509 if (perUserExcludedPackages == null) {
4510 return true;
4511 }
4512 String[] perUserExclusions = perUserExcludedPackages.get(userId);
4513 if (perUserExclusions == null) {
4514 return true;
4515 }
4516 return !ArrayUtils.contains(perUserExclusions, packageName);
4517 }
4518
4519 public void removeUser(int userId) {
4520 if (perUserExcludedPackages != null) {
4521 perUserExcludedPackages.remove(userId);
4522 if (perUserExcludedPackages.size() <= 0) {
4523 perUserExcludedPackages = null;
4524 }
4525 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07004526 if (perUserRestrictions != null) {
4527 perUserRestrictions.remove(userId);
4528 if (perUserRestrictions.size() <= 0) {
4529 perUserRestrictions = null;
4530 }
4531 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004532 }
4533
4534 public boolean isDefault() {
4535 return perUserRestrictions == null || perUserRestrictions.size() <= 0;
4536 }
4537
4538 @Override
4539 public void binderDied() {
4540 synchronized (AppOpsService.this) {
4541 mOpUserRestrictions.remove(token);
4542 if (perUserRestrictions == null) {
4543 return;
4544 }
4545 final int userCount = perUserRestrictions.size();
4546 for (int i = 0; i < userCount; i++) {
4547 final boolean[] restrictions = perUserRestrictions.valueAt(i);
4548 final int restrictionCount = restrictions.length;
4549 for (int j = 0; j < restrictionCount; j++) {
4550 if (restrictions[j]) {
4551 final int changedCode = j;
Svet Ganov3a95f832018-03-23 17:44:30 -07004552 mHandler.post(() -> notifyWatchersOfChange(changedCode, UID_ANY));
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004553 }
4554 }
4555 }
4556 destroy();
4557 }
4558 }
4559
4560 public void destroy() {
4561 token.unlinkToDeath(this, 0);
4562 }
4563
4564 private boolean isDefault(boolean[] array) {
4565 if (ArrayUtils.isEmpty(array)) {
4566 return true;
4567 }
4568 for (boolean value : array) {
4569 if (value) {
4570 return false;
4571 }
4572 }
4573 return true;
4574 }
4575 }
Dianne Hackbornd5254412018-05-11 18:02:58 -07004576
4577 private final class AppOpsManagerInternalImpl extends AppOpsManagerInternal {
4578 @Override public void setDeviceAndProfileOwners(SparseIntArray owners) {
4579 synchronized (AppOpsService.this) {
4580 mProfileOwners = owners;
4581 }
4582 }
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07004583
4584 @Override
Philip P. Moltmann159d98b2018-12-20 08:30:53 -08004585 public void setUidMode(int code, int uid, int mode) {
4586 AppOpsService.this.setUidMode(code, uid, mode);
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07004587 }
Philip P. Moltmanndde07852019-01-25 16:42:36 -08004588
4589 @Override
4590 public void setAllPkgModesToDefault(int code, int uid) {
4591 AppOpsService.this.setAllPkgModesToDefault(code, uid);
4592 }
Philip P. Moltmann724150d2019-03-11 17:01:05 -07004593
4594 @Override
4595 public @Mode int checkOperationUnchecked(int code, int uid, @NonNull String packageName) {
4596 return AppOpsService.this.checkOperationUnchecked(code, uid, packageName, true, false);
4597 }
Dianne Hackbornd5254412018-05-11 18:02:58 -07004598 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004599}