blob: 314e04c8da3284e1d8db91c4dbcdd3427b76ee88 [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;
Suprabh Shukla873e19f2019-09-16 13:20:22 -070021import static android.app.AppOpsManager.OP_CAMERA;
Svet Ganovaf189e32019-02-15 18:45:29 -080022import static android.app.AppOpsManager.OP_FLAGS_ALL;
Svet Ganov8455ba22019-01-02 13:05:56 -080023import static android.app.AppOpsManager.OP_NONE;
Philip P. Moltmanndde07852019-01-25 16:42:36 -080024import static android.app.AppOpsManager.OP_PLAY_AUDIO;
Suprabh Shukla873e19f2019-09-16 13:20:22 -070025import static android.app.AppOpsManager.OP_RECORD_AUDIO;
Hai Zhang2b98fb32018-09-21 15:18:46 -070026import static android.app.AppOpsManager.UID_STATE_BACKGROUND;
27import static android.app.AppOpsManager.UID_STATE_CACHED;
28import static android.app.AppOpsManager.UID_STATE_FOREGROUND;
29import static android.app.AppOpsManager.UID_STATE_FOREGROUND_SERVICE;
Amith Yamasania0a30a12019-01-22 11:38:06 -080030import static android.app.AppOpsManager.UID_STATE_FOREGROUND_SERVICE_LOCATION;
Svet Ganovaf189e32019-02-15 18:45:29 -080031import static android.app.AppOpsManager.UID_STATE_MAX_LAST_NON_RESTRICTED;
Hai Zhang2b98fb32018-09-21 15:18:46 -070032import static android.app.AppOpsManager.UID_STATE_PERSISTENT;
33import static android.app.AppOpsManager.UID_STATE_TOP;
Eugene Suslae4ee2c22018-11-05 12:23:30 -080034import static android.app.AppOpsManager.modeToName;
35import static android.app.AppOpsManager.opToName;
Svet Ganovaf189e32019-02-15 18:45:29 -080036import static android.app.AppOpsManager.resolveFirstUnrestrictedUidState;
Hai Zhang2b98fb32018-09-21 15:18:46 -070037
Philip P. Moltmanne683f192017-06-23 14:05:04 -070038import android.Manifest;
Svet Ganovad0a49b2018-10-29 10:07:08 -070039import android.annotation.NonNull;
40import android.annotation.Nullable;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070041import android.app.ActivityManager;
42import android.app.ActivityThread;
43import android.app.AppGlobals;
44import android.app.AppOpsManager;
Svet Ganov8455ba22019-01-02 13:05:56 -080045import android.app.AppOpsManager.HistoricalOps;
Svet Ganov23c88db2019-01-22 20:38:11 -080046import android.app.AppOpsManager.HistoricalOpsRequest;
Svet Ganovaf189e32019-02-15 18:45:29 -080047import android.app.AppOpsManager.Mode;
48import android.app.AppOpsManager.OpEntry;
49import android.app.AppOpsManager.OpFlags;
Dianne Hackbornd5254412018-05-11 18:02:58 -070050import android.app.AppOpsManagerInternal;
Svet Ganovd873ae62018-06-25 16:39:23 -070051import android.app.AppOpsManagerInternal.CheckOpsDelegate;
Suprabh Shukla3017fe42018-11-08 19:00:01 -080052import android.content.BroadcastReceiver;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070053import android.content.ContentResolver;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070054import android.content.Context;
Suprabh Shukla3017fe42018-11-08 19:00:01 -080055import android.content.Intent;
56import android.content.IntentFilter;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070057import android.content.pm.ApplicationInfo;
58import android.content.pm.IPackageManager;
59import android.content.pm.PackageManager;
60import android.content.pm.PackageManagerInternal;
61import android.content.pm.UserInfo;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070062import android.database.ContentObserver;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070063import android.media.AudioAttributes;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070064import android.net.Uri;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070065import android.os.AsyncTask;
66import android.os.Binder;
67import android.os.Bundle;
68import android.os.Handler;
69import android.os.IBinder;
70import android.os.Process;
Svet Ganov8455ba22019-01-02 13:05:56 -080071import android.os.RemoteCallback;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070072import android.os.RemoteException;
73import android.os.ResultReceiver;
74import android.os.ServiceManager;
75import android.os.ShellCallback;
76import android.os.ShellCommand;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -070077import android.os.SystemClock;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070078import android.os.UserHandle;
79import android.os.UserManager;
Sudheer Shanka98cb3f02018-08-17 16:10:29 -070080import android.os.storage.StorageManager;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070081import android.os.storage.StorageManagerInternal;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070082import android.provider.Settings;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070083import android.util.ArrayMap;
84import android.util.ArraySet;
85import android.util.AtomicFile;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070086import android.util.KeyValueListParser;
Svet Ganovaf189e32019-02-15 18:45:29 -080087import android.util.LongSparseArray;
88import android.util.LongSparseLongArray;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070089import android.util.Slog;
90import android.util.SparseArray;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -070091import android.util.SparseBooleanArray;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070092import android.util.SparseIntArray;
93import android.util.TimeUtils;
94import android.util.Xml;
95
Todd Kennedy556efba2018-11-15 07:43:55 -080096import com.android.internal.annotations.GuardedBy;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070097import com.android.internal.annotations.VisibleForTesting;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -080098import com.android.internal.app.IAppOpsActiveCallback;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070099import com.android.internal.app.IAppOpsCallback;
Svet Ganovb3d2ae22018-12-17 22:06:15 -0800100import com.android.internal.app.IAppOpsNotedCallback;
Philip P. Moltmanne683f192017-06-23 14:05:04 -0700101import com.android.internal.app.IAppOpsService;
102import com.android.internal.os.Zygote;
103import com.android.internal.util.ArrayUtils;
104import com.android.internal.util.DumpUtils;
105import com.android.internal.util.FastXmlSerializer;
106import com.android.internal.util.Preconditions;
107import com.android.internal.util.XmlUtils;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800108import com.android.internal.util.function.pooled.PooledLambda;
Svet Ganov8455ba22019-01-02 13:05:56 -0800109import com.android.server.LocalServices;
110import com.android.server.LockGuard;
Philip P. Moltmanndde07852019-01-25 16:42:36 -0800111
Philip P. Moltmanne683f192017-06-23 14:05:04 -0700112import libcore.util.EmptyArray;
113
114import org.xmlpull.v1.XmlPullParser;
115import org.xmlpull.v1.XmlPullParserException;
116import org.xmlpull.v1.XmlSerializer;
117
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800118import java.io.File;
119import java.io.FileDescriptor;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800120import java.io.FileInputStream;
121import java.io.FileNotFoundException;
122import java.io.FileOutputStream;
123import java.io.IOException;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800124import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100125import java.nio.charset.StandardCharsets;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700126import java.text.SimpleDateFormat;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800127import java.util.ArrayList;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -0700128import java.util.Arrays;
Svetoslav215b44a2015-08-04 19:03:40 -0700129import java.util.Collections;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700130import java.util.Date;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800131import java.util.HashMap;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800132import java.util.Iterator;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800133import java.util.List;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700134import java.util.Map;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800135
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800136public class AppOpsService extends IAppOpsService.Stub {
137 static final String TAG = "AppOps";
Dianne Hackborn35654b62013-01-14 17:38:02 -0800138 static final boolean DEBUG = false;
139
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700140 private static final int NO_VERSION = -1;
141 /** Increment by one every time and add the corresponding upgrade logic in
142 * {@link #upgradeLocked(int)} below. The first version was 1 */
143 private static final int CURRENT_VERSION = 1;
144
Dianne Hackborn35654b62013-01-14 17:38:02 -0800145 // Write at most every 30 minutes.
146 static final long WRITE_DELAY = DEBUG ? 1000 : 30*60*1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800147
Svet Ganov3a95f832018-03-23 17:44:30 -0700148 // Constant meaning that any UID should be matched when dispatching callbacks
149 private static final int UID_ANY = -2;
150
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700151 // Map from process states to the uid states we track.
152 private static final int[] PROCESS_STATE_TO_UID_STATE = new int[] {
153 UID_STATE_PERSISTENT, // ActivityManager.PROCESS_STATE_PERSISTENT
154 UID_STATE_PERSISTENT, // ActivityManager.PROCESS_STATE_PERSISTENT_UI
155 UID_STATE_TOP, // ActivityManager.PROCESS_STATE_TOP
Amith Yamasania0a30a12019-01-22 11:38:06 -0800156 UID_STATE_FOREGROUND_SERVICE_LOCATION,
157 // ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE_LOCATION
Amith Yamasanif235d0b2019-03-20 22:49:43 -0700158 UID_STATE_FOREGROUND, // ActivityManager.PROCESS_STATE_BOUND_TOP
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700159 UID_STATE_FOREGROUND_SERVICE, // ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
160 UID_STATE_FOREGROUND, // ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
161 UID_STATE_FOREGROUND, // ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND
162 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND
163 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_TRANSIENT_BACKGROUND
164 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_BACKUP
165 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_SERVICE
166 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_RECEIVER
167 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_TOP_SLEEPING
168 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_HEAVY_WEIGHT
169 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_HOME
170 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_LAST_ACTIVITY
171 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY
172 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT
173 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_RECENT
174 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_EMPTY
175 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_NONEXISTENT
176 };
177
Suprabh Shukla873e19f2019-09-16 13:20:22 -0700178 private static final int[] OPS_RESTRICTED_ON_SUSPEND = {
179 OP_PLAY_AUDIO,
180 OP_RECORD_AUDIO,
181 OP_CAMERA,
182 };
183
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800184 Context mContext;
185 final AtomicFile mFile;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800186 final Handler mHandler;
187
Dianne Hackbornd5254412018-05-11 18:02:58 -0700188 private final AppOpsManagerInternalImpl mAppOpsManagerInternal
189 = new AppOpsManagerInternalImpl();
190
Dianne Hackborn35654b62013-01-14 17:38:02 -0800191 boolean mWriteScheduled;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800192 boolean mFastWriteScheduled;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800193 final Runnable mWriteRunner = new Runnable() {
194 public void run() {
195 synchronized (AppOpsService.this) {
196 mWriteScheduled = false;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800197 mFastWriteScheduled = false;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800198 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
199 @Override protected Void doInBackground(Void... params) {
200 writeState();
201 return null;
202 }
203 };
204 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
205 }
206 }
207 };
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800208
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700209 @VisibleForTesting
210 final SparseArray<UidState> mUidStates = new SparseArray<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800211
Svet Ganovdc0f4432019-06-04 14:16:51 -0700212 final HistoricalRegistry mHistoricalRegistry = new HistoricalRegistry(this);
Svet Ganov8455ba22019-01-02 13:05:56 -0800213
Dianne Hackborn9fb93502018-06-18 12:29:44 -0700214 long mLastRealtime;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700215
Ruben Brunk29931bc2016-03-11 00:24:26 -0800216 /*
217 * These are app op restrictions imposed per user from various parties.
Ruben Brunk29931bc2016-03-11 00:24:26 -0800218 */
Svetoslav Ganova8bbd762016-05-13 17:08:16 -0700219 private final ArrayMap<IBinder, ClientRestrictionState> mOpUserRestrictions = new ArrayMap<>();
Jason Monk62062992014-05-06 09:55:28 -0400220
Dianne Hackbornd5254412018-05-11 18:02:58 -0700221 SparseIntArray mProfileOwners;
222
Todd Kennedy556efba2018-11-15 07:43:55 -0800223 @GuardedBy("this")
Svet Ganovd873ae62018-06-25 16:39:23 -0700224 private CheckOpsDelegate mCheckOpsDelegate;
225
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700226 /**
227 * All times are in milliseconds. These constants are kept synchronized with the system
228 * global Settings. Any access to this class or its fields should be done while
229 * holding the AppOpsService lock.
230 */
Amith Yamasani23d4cd72019-04-10 17:57:00 -0700231 @VisibleForTesting
232 final class Constants extends ContentObserver {
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700233 // Key names stored in the settings value.
Dianne Hackborne93ab412018-05-14 17:52:30 -0700234 private static final String KEY_TOP_STATE_SETTLE_TIME = "top_state_settle_time";
235 private static final String KEY_FG_SERVICE_STATE_SETTLE_TIME
236 = "fg_service_state_settle_time";
237 private static final String KEY_BG_STATE_SETTLE_TIME = "bg_state_settle_time";
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700238
239 /**
Dianne Hackborne93ab412018-05-14 17:52:30 -0700240 * How long we want for a drop in uid state from top to settle before applying it.
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700241 * @see Settings.Global#APP_OPS_CONSTANTS
Dianne Hackborne93ab412018-05-14 17:52:30 -0700242 * @see #KEY_TOP_STATE_SETTLE_TIME
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700243 */
Dianne Hackborne93ab412018-05-14 17:52:30 -0700244 public long TOP_STATE_SETTLE_TIME;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700245
Dianne Hackborne93ab412018-05-14 17:52:30 -0700246 /**
247 * How long we want for a drop in uid state from foreground to settle before applying it.
248 * @see Settings.Global#APP_OPS_CONSTANTS
249 * @see #KEY_FG_SERVICE_STATE_SETTLE_TIME
250 */
251 public long FG_SERVICE_STATE_SETTLE_TIME;
252
253 /**
254 * How long we want for a drop in uid state from background to settle before applying it.
255 * @see Settings.Global#APP_OPS_CONSTANTS
256 * @see #KEY_BG_STATE_SETTLE_TIME
257 */
258 public long BG_STATE_SETTLE_TIME;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700259
260 private final KeyValueListParser mParser = new KeyValueListParser(',');
261 private ContentResolver mResolver;
262
263 public Constants(Handler handler) {
264 super(handler);
265 updateConstants();
266 }
267
268 public void startMonitoring(ContentResolver resolver) {
269 mResolver = resolver;
270 mResolver.registerContentObserver(
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700271 Settings.Global.getUriFor(Settings.Global.APP_OPS_CONSTANTS),
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700272 false, this);
273 updateConstants();
274 }
275
276 @Override
277 public void onChange(boolean selfChange, Uri uri) {
278 updateConstants();
279 }
280
281 private void updateConstants() {
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700282 String value = mResolver != null ? Settings.Global.getString(mResolver,
283 Settings.Global.APP_OPS_CONSTANTS) : "";
284
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700285 synchronized (AppOpsService.this) {
286 try {
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700287 mParser.setString(value);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700288 } catch (IllegalArgumentException e) {
289 // Failed to parse the settings string, log this and move on
290 // with defaults.
291 Slog.e(TAG, "Bad app ops settings", e);
292 }
Dianne Hackborne93ab412018-05-14 17:52:30 -0700293 TOP_STATE_SETTLE_TIME = mParser.getDurationMillis(
294 KEY_TOP_STATE_SETTLE_TIME, 30 * 1000L);
295 FG_SERVICE_STATE_SETTLE_TIME = mParser.getDurationMillis(
296 KEY_FG_SERVICE_STATE_SETTLE_TIME, 10 * 1000L);
297 BG_STATE_SETTLE_TIME = mParser.getDurationMillis(
298 KEY_BG_STATE_SETTLE_TIME, 1 * 1000L);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700299 }
300 }
301
302 void dump(PrintWriter pw) {
303 pw.println(" Settings:");
304
Dianne Hackborne93ab412018-05-14 17:52:30 -0700305 pw.print(" "); pw.print(KEY_TOP_STATE_SETTLE_TIME); pw.print("=");
306 TimeUtils.formatDuration(TOP_STATE_SETTLE_TIME, pw);
Dianne Hackbornb94d82f2018-05-16 17:03:01 -0700307 pw.println();
Dianne Hackborne93ab412018-05-14 17:52:30 -0700308 pw.print(" "); pw.print(KEY_FG_SERVICE_STATE_SETTLE_TIME); pw.print("=");
309 TimeUtils.formatDuration(FG_SERVICE_STATE_SETTLE_TIME, pw);
Dianne Hackbornb94d82f2018-05-16 17:03:01 -0700310 pw.println();
Dianne Hackborne93ab412018-05-14 17:52:30 -0700311 pw.print(" "); pw.print(KEY_BG_STATE_SETTLE_TIME); pw.print("=");
312 TimeUtils.formatDuration(BG_STATE_SETTLE_TIME, pw);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700313 pw.println();
314 }
315 }
316
Amith Yamasani23d4cd72019-04-10 17:57:00 -0700317 @VisibleForTesting
318 final Constants mConstants;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700319
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700320 @VisibleForTesting
321 static final class UidState {
Svet Ganov2af57082015-07-30 08:44:20 -0700322 public final int uid;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700323
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700324 public int state = UID_STATE_CACHED;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700325 public int pendingState = UID_STATE_CACHED;
326 public long pendingStateCommitTime;
327
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700328 public int startNesting;
Svet Ganov2af57082015-07-30 08:44:20 -0700329 public ArrayMap<String, Ops> pkgOps;
330 public SparseIntArray opModes;
331
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700332 // true indicates there is an interested observer, false there isn't but it has such an op
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700333 public SparseBooleanArray foregroundOps;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700334 public boolean hasForegroundWatchers;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700335
Svet Ganov2af57082015-07-30 08:44:20 -0700336 public UidState(int uid) {
337 this.uid = uid;
338 }
339
340 public void clear() {
341 pkgOps = null;
342 opModes = null;
343 }
344
345 public boolean isDefault() {
346 return (pkgOps == null || pkgOps.isEmpty())
Svet Ganovaf189e32019-02-15 18:45:29 -0800347 && (opModes == null || opModes.size() <= 0)
348 && (state == UID_STATE_CACHED
349 && (pendingState == UID_STATE_CACHED));
Svet Ganov2af57082015-07-30 08:44:20 -0700350 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700351
Svet Ganovaf189e32019-02-15 18:45:29 -0800352 int evalMode(int op, int mode) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700353 if (mode == AppOpsManager.MODE_FOREGROUND) {
Wei Wange1f864e2019-03-28 18:12:18 -0700354 return state <= AppOpsManager.resolveFirstUnrestrictedUidState(op)
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700355 ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED;
356 }
357 return mode;
358 }
359
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700360 private void evalForegroundWatchers(int op, SparseArray<ArraySet<ModeCallback>> watchers,
361 SparseBooleanArray which) {
362 boolean curValue = which.get(op, false);
363 ArraySet<ModeCallback> callbacks = watchers.get(op);
364 if (callbacks != null) {
365 for (int cbi = callbacks.size() - 1; !curValue && cbi >= 0; cbi--) {
366 if ((callbacks.valueAt(cbi).mFlags
367 & AppOpsManager.WATCH_FOREGROUND_CHANGES) != 0) {
368 hasForegroundWatchers = true;
369 curValue = true;
370 }
371 }
372 }
373 which.put(op, curValue);
374 }
375
376 public void evalForegroundOps(SparseArray<ArraySet<ModeCallback>> watchers) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700377 SparseBooleanArray which = null;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700378 hasForegroundWatchers = false;
379 if (opModes != null) {
380 for (int i = opModes.size() - 1; i >= 0; i--) {
381 if (opModes.valueAt(i) == AppOpsManager.MODE_FOREGROUND) {
382 if (which == null) {
383 which = new SparseBooleanArray();
384 }
385 evalForegroundWatchers(opModes.keyAt(i), watchers, which);
386 }
387 }
388 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700389 if (pkgOps != null) {
390 for (int i = pkgOps.size() - 1; i >= 0; i--) {
391 Ops ops = pkgOps.valueAt(i);
392 for (int j = ops.size() - 1; j >= 0; j--) {
393 if (ops.valueAt(j).mode == AppOpsManager.MODE_FOREGROUND) {
394 if (which == null) {
395 which = new SparseBooleanArray();
396 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700397 evalForegroundWatchers(ops.keyAt(j), watchers, which);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700398 }
399 }
400 }
401 }
402 foregroundOps = which;
403 }
Svet Ganov2af57082015-07-30 08:44:20 -0700404 }
405
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700406 final static class Ops extends SparseArray<Op> {
407 final String packageName;
408 final UidState uidState;
409 final boolean isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800410
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700411 Ops(String _packageName, UidState _uidState, boolean _isPrivileged) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800412 packageName = _packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700413 uidState = _uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400414 isPrivileged = _isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800415 }
416 }
417
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700418 final static class Op {
Svet Ganovaf189e32019-02-15 18:45:29 -0800419 int op;
420 boolean running;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700421 final UidState uidState;
Svet Ganovaf189e32019-02-15 18:45:29 -0800422 final @NonNull String packageName;
423
424 private @Mode int mode;
425 private @Nullable LongSparseLongArray mAccessTimes;
426 private @Nullable LongSparseLongArray mRejectTimes;
427 private @Nullable LongSparseLongArray mDurations;
428 private @Nullable LongSparseLongArray mProxyUids;
429 private @Nullable LongSparseArray<String> mProxyPackageNames;
430
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700431 int startNesting;
432 long startRealtime;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800433
Svet Ganovaf189e32019-02-15 18:45:29 -0800434 Op(UidState uidState, String packageName, int op) {
435 this.op = op;
436 this.uidState = uidState;
437 this.packageName = packageName;
438 this.mode = AppOpsManager.opToDefaultMode(op);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700439 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700440
441 int getMode() {
Svet Ganovaf189e32019-02-15 18:45:29 -0800442 return mode;
443 }
444
445 int evalMode() {
446 return uidState.evalMode(op, mode);
447 }
448
449 /** @hide */
450 public void accessed(long time, int proxyUid, @Nullable String proxyPackageName,
451 @AppOpsManager.UidState int uidState, @OpFlags int flags) {
452 final long key = AppOpsManager.makeKey(uidState, flags);
453 if (mAccessTimes == null) {
454 mAccessTimes = new LongSparseLongArray();
455 }
456 mAccessTimes.put(key, time);
457 updateProxyState(key, proxyUid, proxyPackageName);
458 if (mDurations != null) {
459 mDurations.delete(key);
460 }
461 }
462
463 /** @hide */
464 public void rejected(long time, int proxyUid, @Nullable String proxyPackageName,
465 @AppOpsManager.UidState int uidState, @OpFlags int flags) {
466 final long key = AppOpsManager.makeKey(uidState, flags);
467 if (mRejectTimes == null) {
468 mRejectTimes = new LongSparseLongArray();
469 }
470 mRejectTimes.put(key, time);
471 updateProxyState(key, proxyUid, proxyPackageName);
472 if (mDurations != null) {
473 mDurations.delete(key);
474 }
475 }
476
477 /** @hide */
478 public void started(long time, @AppOpsManager.UidState int uidState, @OpFlags int flags) {
479 updateAccessTimeAndDuration(time, -1 /*duration*/, uidState, flags);
480 running = true;
481 }
482
483 /** @hide */
484 public void finished(long time, long duration, @AppOpsManager.UidState int uidState,
485 @OpFlags int flags) {
486 updateAccessTimeAndDuration(time, duration, uidState, flags);
487 running = false;
488 }
489
490 /** @hide */
491 public void running(long time, long duration, @AppOpsManager.UidState int uidState,
492 @OpFlags int flags) {
493 updateAccessTimeAndDuration(time, duration, uidState, flags);
494 }
495
496 /** @hide */
497 public void continuing(long duration, @AppOpsManager.UidState int uidState,
498 @OpFlags int flags) {
499 final long key = AppOpsManager.makeKey(uidState, flags);
500 if (mDurations == null) {
501 mDurations = new LongSparseLongArray();
502 }
503 mDurations.put(key, duration);
504 }
505
506 private void updateAccessTimeAndDuration(long time, long duration,
507 @AppOpsManager.UidState int uidState, @OpFlags int flags) {
508 final long key = AppOpsManager.makeKey(uidState, flags);
509 if (mAccessTimes == null) {
510 mAccessTimes = new LongSparseLongArray();
511 }
512 mAccessTimes.put(key, time);
513 if (mDurations == null) {
514 mDurations = new LongSparseLongArray();
515 }
516 mDurations.put(key, duration);
517 }
518
519 private void updateProxyState(long key, int proxyUid,
520 @Nullable String proxyPackageName) {
Philip P. Moltmann4052d362019-09-19 14:52:38 -0700521 if (proxyUid == Process.INVALID_UID) {
522 return;
523 }
524
Svet Ganovaf189e32019-02-15 18:45:29 -0800525 if (mProxyUids == null) {
526 mProxyUids = new LongSparseLongArray();
527 }
528 mProxyUids.put(key, proxyUid);
529 if (mProxyPackageNames == null) {
530 mProxyPackageNames = new LongSparseArray<>();
531 }
532 mProxyPackageNames.put(key, proxyPackageName);
533 }
534
535 boolean hasAnyTime() {
536 return (mAccessTimes != null && mAccessTimes.size() > 0)
537 || (mRejectTimes != null && mRejectTimes.size() > 0);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700538 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800539 }
540
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800541 final SparseArray<ArraySet<ModeCallback>> mOpModeWatchers = new SparseArray<>();
542 final ArrayMap<String, ArraySet<ModeCallback>> mPackageModeWatchers = new ArrayMap<>();
543 final ArrayMap<IBinder, ModeCallback> mModeWatchers = new ArrayMap<>();
544 final ArrayMap<IBinder, SparseArray<ActiveCallback>> mActiveWatchers = new ArrayMap<>();
Svet Ganovb3d2ae22018-12-17 22:06:15 -0800545 final ArrayMap<IBinder, SparseArray<NotedCallback>> mNotedWatchers = new ArrayMap<>();
Dianne Hackborn68d76552017-02-27 15:32:03 -0800546 final SparseArray<SparseArray<Restriction>> mAudioRestrictions = new SparseArray<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800547
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700548 final class ModeCallback implements DeathRecipient {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800549 final IAppOpsCallback mCallback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700550 final int mWatchingUid;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700551 final int mFlags;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700552 final int mCallingUid;
553 final int mCallingPid;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800554
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700555 ModeCallback(IAppOpsCallback callback, int watchingUid, int flags, int callingUid,
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700556 int callingPid) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800557 mCallback = callback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700558 mWatchingUid = watchingUid;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700559 mFlags = flags;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700560 mCallingUid = callingUid;
561 mCallingPid = callingPid;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800562 try {
563 mCallback.asBinder().linkToDeath(this, 0);
564 } catch (RemoteException e) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -0800565 /*ignored*/
Dianne Hackbornc2293022013-02-06 23:14:49 -0800566 }
567 }
568
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700569 public boolean isWatchingUid(int uid) {
570 return uid == UID_ANY || mWatchingUid < 0 || mWatchingUid == uid;
571 }
572
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700573 @Override
574 public String toString() {
575 StringBuilder sb = new StringBuilder(128);
576 sb.append("ModeCallback{");
577 sb.append(Integer.toHexString(System.identityHashCode(this)));
578 sb.append(" watchinguid=");
579 UserHandle.formatUid(sb, mWatchingUid);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700580 sb.append(" flags=0x");
581 sb.append(Integer.toHexString(mFlags));
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700582 sb.append(" from uid=");
583 UserHandle.formatUid(sb, mCallingUid);
584 sb.append(" pid=");
585 sb.append(mCallingPid);
586 sb.append('}');
587 return sb.toString();
588 }
589
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700590 void unlinkToDeath() {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800591 mCallback.asBinder().unlinkToDeath(this, 0);
592 }
593
594 @Override
595 public void binderDied() {
596 stopWatchingMode(mCallback);
597 }
598 }
599
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700600 final class ActiveCallback implements DeathRecipient {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800601 final IAppOpsActiveCallback mCallback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700602 final int mWatchingUid;
603 final int mCallingUid;
604 final int mCallingPid;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800605
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700606 ActiveCallback(IAppOpsActiveCallback callback, int watchingUid, int callingUid,
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700607 int callingPid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800608 mCallback = callback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700609 mWatchingUid = watchingUid;
610 mCallingUid = callingUid;
611 mCallingPid = callingPid;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800612 try {
613 mCallback.asBinder().linkToDeath(this, 0);
614 } catch (RemoteException e) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -0800615 /*ignored*/
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800616 }
617 }
618
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700619 @Override
620 public String toString() {
621 StringBuilder sb = new StringBuilder(128);
622 sb.append("ActiveCallback{");
623 sb.append(Integer.toHexString(System.identityHashCode(this)));
624 sb.append(" watchinguid=");
625 UserHandle.formatUid(sb, mWatchingUid);
626 sb.append(" from uid=");
627 UserHandle.formatUid(sb, mCallingUid);
628 sb.append(" pid=");
629 sb.append(mCallingPid);
630 sb.append('}');
631 return sb.toString();
632 }
633
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700634 void destroy() {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800635 mCallback.asBinder().unlinkToDeath(this, 0);
636 }
637
638 @Override
639 public void binderDied() {
640 stopWatchingActive(mCallback);
641 }
642 }
643
Svet Ganovb3d2ae22018-12-17 22:06:15 -0800644 final class NotedCallback implements DeathRecipient {
645 final IAppOpsNotedCallback mCallback;
646 final int mWatchingUid;
647 final int mCallingUid;
648 final int mCallingPid;
649
650 NotedCallback(IAppOpsNotedCallback callback, int watchingUid, int callingUid,
651 int callingPid) {
652 mCallback = callback;
653 mWatchingUid = watchingUid;
654 mCallingUid = callingUid;
655 mCallingPid = callingPid;
656 try {
657 mCallback.asBinder().linkToDeath(this, 0);
658 } catch (RemoteException e) {
659 /*ignored*/
660 }
661 }
662
663 @Override
664 public String toString() {
665 StringBuilder sb = new StringBuilder(128);
666 sb.append("NotedCallback{");
667 sb.append(Integer.toHexString(System.identityHashCode(this)));
668 sb.append(" watchinguid=");
669 UserHandle.formatUid(sb, mWatchingUid);
670 sb.append(" from uid=");
671 UserHandle.formatUid(sb, mCallingUid);
672 sb.append(" pid=");
673 sb.append(mCallingPid);
674 sb.append('}');
675 return sb.toString();
676 }
677
678 void destroy() {
679 mCallback.asBinder().unlinkToDeath(this, 0);
680 }
681
682 @Override
683 public void binderDied() {
684 stopWatchingNoted(mCallback);
685 }
686 }
687
Svet Ganova7a0db62018-02-27 20:08:01 -0800688 final ArrayMap<IBinder, ClientState> mClients = new ArrayMap<>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700689
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700690 final class ClientState extends Binder implements DeathRecipient {
Svet Ganovf7b47252018-02-26 11:11:27 -0800691 final ArrayList<Op> mStartedOps = new ArrayList<>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700692 final IBinder mAppToken;
693 final int mPid;
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700694
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700695 ClientState(IBinder appToken) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700696 mAppToken = appToken;
697 mPid = Binder.getCallingPid();
Svet Ganovf7b47252018-02-26 11:11:27 -0800698 // Watch only for remote processes dying
699 if (!(appToken instanceof Binder)) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700700 try {
701 mAppToken.linkToDeath(this, 0);
702 } catch (RemoteException e) {
Svet Ganovf7b47252018-02-26 11:11:27 -0800703 /* do nothing */
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700704 }
705 }
706 }
707
708 @Override
709 public String toString() {
710 return "ClientState{" +
711 "mAppToken=" + mAppToken +
Svet Ganovf7b47252018-02-26 11:11:27 -0800712 ", " + "pid=" + mPid +
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700713 '}';
714 }
715
716 @Override
717 public void binderDied() {
718 synchronized (AppOpsService.this) {
719 for (int i=mStartedOps.size()-1; i>=0; i--) {
Bruno Martins8e0636d2018-12-30 16:02:59 +0000720 final Op op = mStartedOps.get(i);
721 finishOperationLocked(op, /*finishNested*/ true);
722 if (op.startNesting <= 0) {
723 scheduleOpActiveChangedIfNeededLocked(op.op, op.uidState.uid,
724 op.packageName, false);
725 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700726 }
727 mClients.remove(mAppToken);
728 }
729 }
730 }
731
Jeff Brown6f357d32014-01-15 20:40:55 -0800732 public AppOpsService(File storagePath, Handler handler) {
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600733 LockGuard.installLock(this, LockGuard.INDEX_APP_OPS);
Dianne Hackborne17b4452018-01-10 13:15:40 -0800734 mFile = new AtomicFile(storagePath, "appops");
Jeff Brown6f357d32014-01-15 20:40:55 -0800735 mHandler = handler;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700736 mConstants = new Constants(mHandler);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800737 readState();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800738 }
David Braunf5d83192013-09-16 13:43:51 -0700739
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800740 public void publish(Context context) {
741 mContext = context;
742 ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
Dianne Hackbornd5254412018-05-11 18:02:58 -0700743 LocalServices.addService(AppOpsManagerInternal.class, mAppOpsManagerInternal);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800744 }
745
Dianne Hackborn514074f2013-02-11 10:52:46 -0800746 public void systemReady() {
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700747 mConstants.startMonitoring(mContext.getContentResolver());
Svet Ganov8455ba22019-01-02 13:05:56 -0800748 mHistoricalRegistry.systemReady(mContext.getContentResolver());
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700749
Dianne Hackborn514074f2013-02-11 10:52:46 -0800750 synchronized (this) {
751 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700752 for (int i = mUidStates.size() - 1; i >= 0; i--) {
753 UidState uidState = mUidStates.valueAt(i);
754
755 String[] packageNames = getPackagesForUid(uidState.uid);
756 if (ArrayUtils.isEmpty(packageNames)) {
757 uidState.clear();
758 mUidStates.removeAt(i);
759 changed = true;
760 continue;
761 }
762
763 ArrayMap<String, Ops> pkgs = uidState.pkgOps;
764 if (pkgs == null) {
765 continue;
766 }
767
Dianne Hackborn514074f2013-02-11 10:52:46 -0800768 Iterator<Ops> it = pkgs.values().iterator();
769 while (it.hasNext()) {
770 Ops ops = it.next();
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700771 int curUid = -1;
Dianne Hackborn514074f2013-02-11 10:52:46 -0800772 try {
Jeff Sharkeycd654482016-01-08 17:42:11 -0700773 curUid = AppGlobals.getPackageManager().getPackageUid(ops.packageName,
774 PackageManager.MATCH_UNINSTALLED_PACKAGES,
Svet Ganov2af57082015-07-30 08:44:20 -0700775 UserHandle.getUserId(ops.uidState.uid));
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700776 } catch (RemoteException ignored) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800777 }
Svet Ganov2af57082015-07-30 08:44:20 -0700778 if (curUid != ops.uidState.uid) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800779 Slog.i(TAG, "Pruning old package " + ops.packageName
Svet Ganov2af57082015-07-30 08:44:20 -0700780 + "/" + ops.uidState + ": new uid=" + curUid);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800781 it.remove();
782 changed = true;
783 }
784 }
Svet Ganov2af57082015-07-30 08:44:20 -0700785
786 if (uidState.isDefault()) {
787 mUidStates.removeAt(i);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800788 }
789 }
790 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800791 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800792 }
793 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700794
Suprabh Shukla3017fe42018-11-08 19:00:01 -0800795 final IntentFilter packageSuspendFilter = new IntentFilter();
796 packageSuspendFilter.addAction(Intent.ACTION_PACKAGES_UNSUSPENDED);
797 packageSuspendFilter.addAction(Intent.ACTION_PACKAGES_SUSPENDED);
798 mContext.registerReceiver(new BroadcastReceiver() {
799 @Override
800 public void onReceive(Context context, Intent intent) {
801 final int[] changedUids = intent.getIntArrayExtra(Intent.EXTRA_CHANGED_UID_LIST);
802 final String[] changedPkgs = intent.getStringArrayExtra(
803 Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suprabh Shukla873e19f2019-09-16 13:20:22 -0700804 for (int code : OPS_RESTRICTED_ON_SUSPEND) {
805 ArraySet<ModeCallback> callbacks;
806 synchronized (AppOpsService.this) {
807 callbacks = mOpModeWatchers.get(code);
808 if (callbacks == null) {
809 continue;
810 }
811 callbacks = new ArraySet<>(callbacks);
Dianne Hackbornb298b352019-04-04 11:01:41 -0700812 }
Suprabh Shukla873e19f2019-09-16 13:20:22 -0700813 for (int i = 0; i < changedUids.length; i++) {
814 final int changedUid = changedUids[i];
815 final String changedPkg = changedPkgs[i];
816 // We trust packagemanager to insert matching uid and packageNames in the
817 // extras
818 notifyOpChanged(callbacks, code, changedUid, changedPkg);
819 }
Suprabh Shukla3017fe42018-11-08 19:00:01 -0800820 }
821 }
822 }, packageSuspendFilter);
823
Suprabh Shuklaaef25132017-01-23 18:09:03 -0800824 PackageManagerInternal packageManagerInternal = LocalServices.getService(
825 PackageManagerInternal.class);
826 packageManagerInternal.setExternalSourcesPolicy(
827 new PackageManagerInternal.ExternalSourcesPolicy() {
828 @Override
829 public int getPackageTrustedToInstallApps(String packageName, int uid) {
830 int appOpMode = checkOperation(AppOpsManager.OP_REQUEST_INSTALL_PACKAGES,
831 uid, packageName);
832 switch (appOpMode) {
833 case AppOpsManager.MODE_ALLOWED:
834 return PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
835 case AppOpsManager.MODE_ERRORED:
836 return PackageManagerInternal.ExternalSourcesPolicy.USER_BLOCKED;
837 default:
838 return PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT;
839 }
840 }
841 });
842
Jeff Sharkey10ec9d82018-11-28 14:52:45 -0700843 if (!StorageManager.hasIsolatedStorage()) {
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700844 StorageManagerInternal storageManagerInternal = LocalServices.getService(
845 StorageManagerInternal.class);
846 storageManagerInternal.addExternalStoragePolicy(
847 new StorageManagerInternal.ExternalStorageMountPolicy() {
848 @Override
849 public int getMountMode(int uid, String packageName) {
850 if (Process.isIsolated(uid)) {
851 return Zygote.MOUNT_EXTERNAL_NONE;
852 }
853 if (noteOperation(AppOpsManager.OP_READ_EXTERNAL_STORAGE, uid,
854 packageName) != AppOpsManager.MODE_ALLOWED) {
855 return Zygote.MOUNT_EXTERNAL_NONE;
856 }
857 if (noteOperation(AppOpsManager.OP_WRITE_EXTERNAL_STORAGE, uid,
858 packageName) != AppOpsManager.MODE_ALLOWED) {
859 return Zygote.MOUNT_EXTERNAL_READ;
860 }
861 return Zygote.MOUNT_EXTERNAL_WRITE;
Svet Ganov6ee871e2015-07-10 14:29:33 -0700862 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700863
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700864 @Override
865 public boolean hasExternalStorage(int uid, String packageName) {
866 final int mountMode = getMountMode(uid, packageName);
867 return mountMode == Zygote.MOUNT_EXTERNAL_READ
868 || mountMode == Zygote.MOUNT_EXTERNAL_WRITE;
869 }
870 });
871 }
Dianne Hackborn514074f2013-02-11 10:52:46 -0800872 }
873
874 public void packageRemoved(int uid, String packageName) {
875 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700876 UidState uidState = mUidStates.get(uid);
877 if (uidState == null) {
878 return;
879 }
880
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800881 Ops ops = null;
Svet Ganov2af57082015-07-30 08:44:20 -0700882
883 // Remove any package state if such.
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800884 if (uidState.pkgOps != null) {
885 ops = uidState.pkgOps.remove(packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700886 }
887
888 // If we just nuked the last package state check if the UID is valid.
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800889 if (ops != null && uidState.pkgOps.isEmpty()
Svet Ganov2af57082015-07-30 08:44:20 -0700890 && getPackagesForUid(uid).length <= 0) {
891 mUidStates.remove(uid);
892 }
893
Svet Ganova7a0db62018-02-27 20:08:01 -0800894 // Finish ops other packages started on behalf of the package.
895 final int clientCount = mClients.size();
896 for (int i = 0; i < clientCount; i++) {
897 final ClientState client = mClients.valueAt(i);
898 if (client.mStartedOps == null) {
899 continue;
900 }
901 final int opCount = client.mStartedOps.size();
902 for (int j = opCount - 1; j >= 0; j--) {
903 final Op op = client.mStartedOps.get(j);
Svet Ganovaf189e32019-02-15 18:45:29 -0800904 if (uid == op.uidState.uid && packageName.equals(op.packageName)) {
Svet Ganova7a0db62018-02-27 20:08:01 -0800905 finishOperationLocked(op, /*finishNested*/ true);
906 client.mStartedOps.remove(j);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700907 if (op.startNesting <= 0) {
Svet Ganova7a0db62018-02-27 20:08:01 -0800908 scheduleOpActiveChangedIfNeededLocked(op.op,
909 uid, packageName, false);
910 }
911 }
912 }
913 }
914
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800915 if (ops != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700916 scheduleFastWriteLocked();
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800917
918 final int opCount = ops.size();
919 for (int i = 0; i < opCount; i++) {
920 final Op op = ops.valueAt(i);
Svet Ganovaf189e32019-02-15 18:45:29 -0800921 if (op.running) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800922 scheduleOpActiveChangedIfNeededLocked(
Svet Ganovaf189e32019-02-15 18:45:29 -0800923 op.op, op.uidState.uid, op.packageName, false);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800924 }
925 }
Dianne Hackborn514074f2013-02-11 10:52:46 -0800926 }
Winson4e3b4352019-05-07 16:29:59 -0700927
928 mHistoricalRegistry.clearHistory(uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800929 }
930 }
931
932 public void uidRemoved(int uid) {
933 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700934 if (mUidStates.indexOfKey(uid) >= 0) {
935 mUidStates.remove(uid);
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800936 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800937 }
938 }
939 }
940
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700941 public void updateUidProcState(int uid, int procState) {
942 synchronized (this) {
943 final UidState uidState = getUidStateLocked(uid, true);
Amith Yamasania0a30a12019-01-22 11:38:06 -0800944 int newState = PROCESS_STATE_TO_UID_STATE[procState];
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700945 if (uidState != null && uidState.pendingState != newState) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700946 final int oldPendingState = uidState.pendingState;
947 uidState.pendingState = newState;
Wei Wange1f864e2019-03-28 18:12:18 -0700948 if (newState < uidState.state
949 || (newState <= UID_STATE_MAX_LAST_NON_RESTRICTED
950 && uidState.state > UID_STATE_MAX_LAST_NON_RESTRICTED)) {
951 // We are moving to a more important state, or the new state may be in the
952 // foreground and the old state is in the background, then always do it
953 // immediately.
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700954 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700955 } else if (uidState.pendingStateCommitTime == 0) {
956 // We are moving to a less important state for the first time,
957 // delay the application for a bit.
Dianne Hackborne93ab412018-05-14 17:52:30 -0700958 final long settleTime;
959 if (uidState.state <= UID_STATE_TOP) {
960 settleTime = mConstants.TOP_STATE_SETTLE_TIME;
961 } else if (uidState.state <= UID_STATE_FOREGROUND_SERVICE) {
962 settleTime = mConstants.FG_SERVICE_STATE_SETTLE_TIME;
963 } else {
964 settleTime = mConstants.BG_STATE_SETTLE_TIME;
965 }
Dianne Hackborn9fb93502018-06-18 12:29:44 -0700966 uidState.pendingStateCommitTime = SystemClock.elapsedRealtime() + settleTime;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700967 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700968 if (uidState.startNesting != 0) {
969 // There is some actively running operation... need to find it
970 // and appropriately update its state.
971 final long now = System.currentTimeMillis();
972 for (int i = uidState.pkgOps.size() - 1; i >= 0; i--) {
973 final Ops ops = uidState.pkgOps.valueAt(i);
974 for (int j = ops.size() - 1; j >= 0; j--) {
975 final Op op = ops.valueAt(j);
976 if (op.startNesting > 0) {
Svet Ganovaf189e32019-02-15 18:45:29 -0800977 final long duration = SystemClock.elapsedRealtime()
978 - op.startRealtime;
979 // We don't support proxy long running ops (start/stop)
980 mHistoricalRegistry.increaseOpAccessDuration(op.op,
981 op.uidState.uid, op.packageName, oldPendingState,
982 AppOpsManager.OP_FLAG_SELF, duration);
983 // Finish the op in the old state
984 op.finished(now, duration, oldPendingState,
985 AppOpsManager.OP_FLAG_SELF);
986 // Start the op in the new state
987 op.startRealtime = now;
988 op.started(now, newState, AppOpsManager.OP_FLAG_SELF);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700989 }
990 }
991 }
992 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700993 }
994 }
995 }
996
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800997 public void shutdown() {
998 Slog.w(TAG, "Writing app ops before shutdown...");
Dianne Hackborn35654b62013-01-14 17:38:02 -0800999 boolean doWrite = false;
1000 synchronized (this) {
1001 if (mWriteScheduled) {
1002 mWriteScheduled = false;
1003 doWrite = true;
1004 }
1005 }
1006 if (doWrite) {
1007 writeState();
1008 }
1009 }
1010
Dianne Hackborn72e39832013-01-18 18:36:09 -08001011 private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
1012 ArrayList<AppOpsManager.OpEntry> resOps = null;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001013 final long elapsedNow = SystemClock.elapsedRealtime();
Dianne Hackborn72e39832013-01-18 18:36:09 -08001014 if (ops == null) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001015 resOps = new ArrayList<>();
Dianne Hackborn72e39832013-01-18 18:36:09 -08001016 for (int j=0; j<pkgOps.size(); j++) {
1017 Op curOp = pkgOps.valueAt(j);
Svet Ganovaf189e32019-02-15 18:45:29 -08001018 resOps.add(getOpEntryForResult(curOp, elapsedNow));
Dianne Hackborn72e39832013-01-18 18:36:09 -08001019 }
1020 } else {
1021 for (int j=0; j<ops.length; j++) {
1022 Op curOp = pkgOps.get(ops[j]);
1023 if (curOp != null) {
1024 if (resOps == null) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001025 resOps = new ArrayList<>();
Dianne Hackborn72e39832013-01-18 18:36:09 -08001026 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001027 resOps.add(getOpEntryForResult(curOp, elapsedNow));
Dianne Hackborn72e39832013-01-18 18:36:09 -08001028 }
1029 }
1030 }
1031 return resOps;
1032 }
1033
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001034 private ArrayList<AppOpsManager.OpEntry> collectOps(SparseIntArray uidOps, int[] ops) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08001035 if (uidOps == null) {
1036 return null;
1037 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001038 ArrayList<AppOpsManager.OpEntry> resOps = null;
1039 if (ops == null) {
1040 resOps = new ArrayList<>();
1041 for (int j=0; j<uidOps.size(); j++) {
Svet Ganovaf189e32019-02-15 18:45:29 -08001042 resOps.add(new OpEntry(uidOps.keyAt(j), uidOps.valueAt(j)));
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001043 }
1044 } else {
1045 for (int j=0; j<ops.length; j++) {
1046 int index = uidOps.indexOfKey(ops[j]);
1047 if (index >= 0) {
1048 if (resOps == null) {
1049 resOps = new ArrayList<>();
1050 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001051 resOps.add(new OpEntry(uidOps.keyAt(j), uidOps.valueAt(j)));
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001052 }
1053 }
1054 }
1055 return resOps;
1056 }
1057
Svet Ganovaf189e32019-02-15 18:45:29 -08001058 private static @NonNull OpEntry getOpEntryForResult(@NonNull Op op, long elapsedNow) {
1059 if (op.running) {
1060 op.continuing(elapsedNow - op.startRealtime,
1061 op.uidState.state, AppOpsManager.OP_FLAG_SELF);
1062 }
1063 final OpEntry entry = new OpEntry(op.op, op.running, op.mode,
1064 op.mAccessTimes != null ? op.mAccessTimes.clone() : null,
1065 op.mRejectTimes != null ? op.mRejectTimes.clone() : null,
1066 op.mDurations != null ? op.mDurations.clone() : null,
1067 op.mProxyUids != null ? op.mProxyUids.clone() : null,
1068 op.mProxyPackageNames != null ? op.mProxyPackageNames.clone() : null);
1069 return entry;
1070 }
1071
Dianne Hackborn35654b62013-01-14 17:38:02 -08001072 @Override
1073 public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
1074 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
1075 Binder.getCallingPid(), Binder.getCallingUid(), null);
1076 ArrayList<AppOpsManager.PackageOps> res = null;
1077 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -07001078 final int uidStateCount = mUidStates.size();
1079 for (int i = 0; i < uidStateCount; i++) {
1080 UidState uidState = mUidStates.valueAt(i);
1081 if (uidState.pkgOps == null || uidState.pkgOps.isEmpty()) {
1082 continue;
1083 }
1084 ArrayMap<String, Ops> packages = uidState.pkgOps;
1085 final int packageCount = packages.size();
1086 for (int j = 0; j < packageCount; j++) {
1087 Ops pkgOps = packages.valueAt(j);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001088 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001089 if (resOps != null) {
1090 if (res == null) {
1091 res = new ArrayList<AppOpsManager.PackageOps>();
1092 }
1093 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -07001094 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001095 res.add(resPackage);
1096 }
1097 }
1098 }
1099 }
1100 return res;
1101 }
1102
1103 @Override
Dianne Hackborn72e39832013-01-18 18:36:09 -08001104 public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
1105 int[] ops) {
1106 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
1107 Binder.getCallingPid(), Binder.getCallingUid(), null);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001108 String resolvedPackageName = resolvePackageName(uid, packageName);
1109 if (resolvedPackageName == null) {
1110 return Collections.emptyList();
1111 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08001112 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001113 Ops pkgOps = getOpsRawLocked(uid, resolvedPackageName, false /* edit */,
1114 false /* uidMismatchExpected */);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001115 if (pkgOps == null) {
1116 return null;
1117 }
1118 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
1119 if (resOps == null) {
1120 return null;
1121 }
1122 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
1123 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -07001124 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001125 res.add(resPackage);
1126 return res;
1127 }
1128 }
1129
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001130 @Override
Svet Ganov8455ba22019-01-02 13:05:56 -08001131 public void getHistoricalOps(int uid, @NonNull String packageName,
Svet Ganov23c88db2019-01-22 20:38:11 -08001132 @Nullable List<String> opNames, long beginTimeMillis, long endTimeMillis,
Svet Ganovaf189e32019-02-15 18:45:29 -08001133 @OpFlags int flags, @NonNull RemoteCallback callback) {
Svet Ganov23c88db2019-01-22 20:38:11 -08001134 // Use the builder to validate arguments.
Svet Ganovaf189e32019-02-15 18:45:29 -08001135 new HistoricalOpsRequest.Builder(
Svet Ganov23c88db2019-01-22 20:38:11 -08001136 beginTimeMillis, endTimeMillis)
1137 .setUid(uid)
1138 .setPackageName(packageName)
1139 .setOpNames(opNames)
Svet Ganovaf189e32019-02-15 18:45:29 -08001140 .setFlags(flags)
Svet Ganov23c88db2019-01-22 20:38:11 -08001141 .build();
Svet Ganov8455ba22019-01-02 13:05:56 -08001142 Preconditions.checkNotNull(callback, "callback cannot be null");
Svet Ganovad0a49b2018-10-29 10:07:08 -07001143
1144 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
Svet Ganov8455ba22019-01-02 13:05:56 -08001145 Binder.getCallingPid(), Binder.getCallingUid(), "getHistoricalOps");
Svet Ganovad0a49b2018-10-29 10:07:08 -07001146
Svet Ganov23c88db2019-01-22 20:38:11 -08001147 final String[] opNamesArray = (opNames != null)
1148 ? opNames.toArray(new String[opNames.size()]) : null;
Svet Ganovad0a49b2018-10-29 10:07:08 -07001149
Svet Ganovaf189e32019-02-15 18:45:29 -08001150 // Must not hold the appops lock
1151 mHistoricalRegistry.getHistoricalOps(uid, packageName, opNamesArray,
1152 beginTimeMillis, endTimeMillis, flags, callback);
Svet Ganovad0a49b2018-10-29 10:07:08 -07001153 }
1154
1155 @Override
Svet Ganov8455ba22019-01-02 13:05:56 -08001156 public void getHistoricalOpsFromDiskRaw(int uid, @NonNull String packageName,
Svet Ganov23c88db2019-01-22 20:38:11 -08001157 @Nullable List<String> opNames, long beginTimeMillis, long endTimeMillis,
Svet Ganovaf189e32019-02-15 18:45:29 -08001158 @OpFlags int flags, @NonNull RemoteCallback callback) {
Svet Ganov23c88db2019-01-22 20:38:11 -08001159 // Use the builder to validate arguments.
Svet Ganovaf189e32019-02-15 18:45:29 -08001160 new HistoricalOpsRequest.Builder(
Svet Ganov23c88db2019-01-22 20:38:11 -08001161 beginTimeMillis, endTimeMillis)
1162 .setUid(uid)
1163 .setPackageName(packageName)
1164 .setOpNames(opNames)
Svet Ganovaf189e32019-02-15 18:45:29 -08001165 .setFlags(flags)
Svet Ganov23c88db2019-01-22 20:38:11 -08001166 .build();
Svet Ganov8455ba22019-01-02 13:05:56 -08001167 Preconditions.checkNotNull(callback, "callback cannot be null");
Svet Ganovad0a49b2018-10-29 10:07:08 -07001168
Svet Ganov8e5bf962019-03-19 23:59:03 -07001169 mContext.enforcePermission(Manifest.permission.MANAGE_APPOPS,
Svet Ganov8455ba22019-01-02 13:05:56 -08001170 Binder.getCallingPid(), Binder.getCallingUid(), "getHistoricalOps");
Svet Ganovad0a49b2018-10-29 10:07:08 -07001171
Svet Ganov23c88db2019-01-22 20:38:11 -08001172 final String[] opNamesArray = (opNames != null)
1173 ? opNames.toArray(new String[opNames.size()]) : null;
1174
Svet Ganov8455ba22019-01-02 13:05:56 -08001175 // Must not hold the appops lock
Svet Ganov23c88db2019-01-22 20:38:11 -08001176 mHistoricalRegistry.getHistoricalOpsFromDiskRaw(uid, packageName, opNamesArray,
Svet Ganovaf189e32019-02-15 18:45:29 -08001177 beginTimeMillis, endTimeMillis, flags, callback);
Svet Ganovad0a49b2018-10-29 10:07:08 -07001178 }
1179
1180 @Override
Svet Ganov8e5bf962019-03-19 23:59:03 -07001181 public void reloadNonHistoricalState() {
1182 mContext.enforcePermission(Manifest.permission.MANAGE_APPOPS,
1183 Binder.getCallingPid(), Binder.getCallingUid(), "reloadNonHistoricalState");
1184 writeState();
1185 readState();
1186 }
1187
1188 @Override
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001189 public List<AppOpsManager.PackageOps> getUidOps(int uid, int[] ops) {
1190 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
1191 Binder.getCallingPid(), Binder.getCallingUid(), null);
1192 synchronized (this) {
1193 UidState uidState = getUidStateLocked(uid, false);
1194 if (uidState == null) {
1195 return null;
1196 }
1197 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(uidState.opModes, ops);
1198 if (resOps == null) {
1199 return null;
1200 }
1201 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
1202 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
1203 null, uidState.uid, resOps);
1204 res.add(resPackage);
1205 return res;
1206 }
1207 }
1208
Dianne Hackborn607b4142013-08-02 18:10:10 -07001209 private void pruneOp(Op op, int uid, String packageName) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001210 if (!op.hasAnyTime()) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001211 Ops ops = getOpsRawLocked(uid, packageName, false /* edit */,
1212 false /* uidMismatchExpected */);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001213 if (ops != null) {
1214 ops.remove(op.op);
1215 if (ops.size() <= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -07001216 UidState uidState = ops.uidState;
1217 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
Dianne Hackborn607b4142013-08-02 18:10:10 -07001218 if (pkgOps != null) {
1219 pkgOps.remove(ops.packageName);
Svet Ganov2af57082015-07-30 08:44:20 -07001220 if (pkgOps.isEmpty()) {
1221 uidState.pkgOps = null;
1222 }
1223 if (uidState.isDefault()) {
1224 mUidStates.remove(uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001225 }
1226 }
1227 }
1228 }
1229 }
1230 }
1231
Svet Ganovaf189e32019-02-15 18:45:29 -08001232 private void enforceManageAppOpsModes(int callingPid, int callingUid, int targetUid) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07001233 if (callingPid == Process.myPid()) {
1234 return;
1235 }
1236 final int callingUser = UserHandle.getUserId(callingUid);
1237 synchronized (this) {
1238 if (mProfileOwners != null && mProfileOwners.get(callingUser, -1) == callingUid) {
1239 if (targetUid >= 0 && callingUser == UserHandle.getUserId(targetUid)) {
1240 // Profile owners are allowed to change modes but only for apps
1241 // within their user.
1242 return;
1243 }
1244 }
1245 }
1246 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
1247 Binder.getCallingPid(), Binder.getCallingUid(), null);
1248 }
1249
Dianne Hackborn72e39832013-01-18 18:36:09 -08001250 @Override
Svet Ganov2af57082015-07-30 08:44:20 -07001251 public void setUidMode(int code, int uid, int mode) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08001252 if (DEBUG) {
1253 Slog.i(TAG, "uid " + uid + " OP_" + opToName(code) + " := " + modeToName(mode)
1254 + " by uid " + Binder.getCallingUid());
1255 }
1256
Dianne Hackbornd5254412018-05-11 18:02:58 -07001257 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
Svet Ganov2af57082015-07-30 08:44:20 -07001258 verifyIncomingOp(code);
1259 code = AppOpsManager.opToSwitch(code);
1260
1261 synchronized (this) {
1262 final int defaultMode = AppOpsManager.opToDefaultMode(code);
1263
1264 UidState uidState = getUidStateLocked(uid, false);
1265 if (uidState == null) {
1266 if (mode == defaultMode) {
1267 return;
1268 }
1269 uidState = new UidState(uid);
1270 uidState.opModes = new SparseIntArray();
1271 uidState.opModes.put(code, mode);
1272 mUidStates.put(uid, uidState);
1273 scheduleWriteLocked();
1274 } else if (uidState.opModes == null) {
1275 if (mode != defaultMode) {
1276 uidState.opModes = new SparseIntArray();
1277 uidState.opModes.put(code, mode);
1278 scheduleWriteLocked();
1279 }
1280 } else {
Hai Zhang2b98fb32018-09-21 15:18:46 -07001281 if (uidState.opModes.indexOfKey(code) >= 0 && uidState.opModes.get(code) == mode) {
Svet Ganov2af57082015-07-30 08:44:20 -07001282 return;
1283 }
1284 if (mode == defaultMode) {
1285 uidState.opModes.delete(code);
1286 if (uidState.opModes.size() <= 0) {
1287 uidState.opModes = null;
1288 }
1289 } else {
1290 uidState.opModes.put(code, mode);
1291 }
1292 scheduleWriteLocked();
1293 }
Wei Wang711eb662019-03-21 18:24:17 -07001294 uidState.evalForegroundOps(mOpModeWatchers);
Svet Ganov2af57082015-07-30 08:44:20 -07001295 }
1296
Svetoslav215b44a2015-08-04 19:03:40 -07001297 String[] uidPackageNames = getPackagesForUid(uid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001298 ArrayMap<ModeCallback, ArraySet<String>> callbackSpecs = null;
Svet Ganov2af57082015-07-30 08:44:20 -07001299
riddle_hsu40b300f2015-11-23 13:22:03 +08001300 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001301 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001302 if (callbacks != null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001303 final int callbackCount = callbacks.size();
1304 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001305 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +08001306 ArraySet<String> changedPackages = new ArraySet<>();
1307 Collections.addAll(changedPackages, uidPackageNames);
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001308 if (callbackSpecs == null) {
1309 callbackSpecs = new ArrayMap<>();
1310 }
riddle_hsu40b300f2015-11-23 13:22:03 +08001311 callbackSpecs.put(callback, changedPackages);
1312 }
1313 }
1314
1315 for (String uidPackageName : uidPackageNames) {
1316 callbacks = mPackageModeWatchers.get(uidPackageName);
1317 if (callbacks != null) {
1318 if (callbackSpecs == null) {
1319 callbackSpecs = new ArrayMap<>();
Svet Ganov2af57082015-07-30 08:44:20 -07001320 }
riddle_hsu40b300f2015-11-23 13:22:03 +08001321 final int callbackCount = callbacks.size();
1322 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001323 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +08001324 ArraySet<String> changedPackages = callbackSpecs.get(callback);
1325 if (changedPackages == null) {
1326 changedPackages = new ArraySet<>();
1327 callbackSpecs.put(callback, changedPackages);
1328 }
1329 changedPackages.add(uidPackageName);
1330 }
Svet Ganov2af57082015-07-30 08:44:20 -07001331 }
1332 }
1333 }
1334
1335 if (callbackSpecs == null) {
Sudheer Shankab1613982019-05-16 16:55:50 -07001336 notifyOpChangedSync(code, uid, null, mode);
Svet Ganov2af57082015-07-30 08:44:20 -07001337 return;
1338 }
1339
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001340 for (int i = 0; i < callbackSpecs.size(); i++) {
1341 final ModeCallback callback = callbackSpecs.keyAt(i);
1342 final ArraySet<String> reportedPackageNames = callbackSpecs.valueAt(i);
1343 if (reportedPackageNames == null) {
1344 mHandler.sendMessage(PooledLambda.obtainMessage(
1345 AppOpsService::notifyOpChanged,
1346 this, callback, code, uid, (String) null));
1347
1348 } else {
1349 final int reportedPackageCount = reportedPackageNames.size();
1350 for (int j = 0; j < reportedPackageCount; j++) {
1351 final String reportedPackageName = reportedPackageNames.valueAt(j);
1352 mHandler.sendMessage(PooledLambda.obtainMessage(
1353 AppOpsService::notifyOpChanged,
1354 this, callback, code, uid, reportedPackageName));
Svet Ganov2af57082015-07-30 08:44:20 -07001355 }
1356 }
Svet Ganov2af57082015-07-30 08:44:20 -07001357 }
Sudheer Shankab1613982019-05-16 16:55:50 -07001358
1359 notifyOpChangedSync(code, uid, null, mode);
1360 }
1361
1362 private void notifyOpChangedSync(int code, int uid, @NonNull String packageName, int mode) {
1363 final StorageManagerInternal storageManagerInternal =
1364 LocalServices.getService(StorageManagerInternal.class);
1365 if (storageManagerInternal != null) {
1366 storageManagerInternal.onAppOpsChanged(code, uid, packageName, mode);
1367 }
Svet Ganov2af57082015-07-30 08:44:20 -07001368 }
1369
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001370 /**
1371 * Set all {@link #setMode (package) modes} for this uid to the default value.
1372 *
1373 * @param code The app-op
1374 * @param uid The uid
1375 */
1376 private void setAllPkgModesToDefault(int code, int uid) {
1377 synchronized (this) {
1378 UidState uidState = getUidStateLocked(uid, false);
1379 if (uidState == null) {
1380 return;
1381 }
1382
1383 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
1384 if (pkgOps == null) {
1385 return;
1386 }
1387
Svet Ganovaf189e32019-02-15 18:45:29 -08001388 boolean scheduleWrite = false;
1389
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001390 int numPkgs = pkgOps.size();
1391 for (int pkgNum = 0; pkgNum < numPkgs; pkgNum++) {
1392 Ops ops = pkgOps.valueAt(pkgNum);
1393
1394 Op op = ops.get(code);
1395 if (op == null) {
1396 continue;
1397 }
1398
1399 int defaultMode = AppOpsManager.opToDefaultMode(code);
1400 if (op.mode != defaultMode) {
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001401 op.mode = defaultMode;
Svet Ganovaf189e32019-02-15 18:45:29 -08001402 scheduleWrite = true;
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001403 }
1404 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001405
1406 if (scheduleWrite) {
1407 scheduleWriteLocked();
1408 }
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001409 }
1410 }
1411
Svet Ganov2af57082015-07-30 08:44:20 -07001412 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001413 public void setMode(int code, int uid, String packageName, int mode) {
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07001414 setMode(code, uid, packageName, mode, true, false);
1415 }
1416
1417 /**
1418 * Sets the mode for a certain op and uid.
1419 *
1420 * @param code The op code to set
1421 * @param uid The UID for which to set
1422 * @param packageName The package for which to set
1423 * @param mode The new mode to set
1424 * @param verifyUid Iff {@code true}, check that the package name belongs to the uid
1425 * @param isPrivileged Whether the package is privileged. (Only used if {@code verifyUid ==
1426 * false})
1427 */
1428 private void setMode(int code, int uid, @NonNull String packageName, int mode,
1429 boolean verifyUid, boolean isPrivileged) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07001430 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001431 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001432 ArraySet<ModeCallback> repCbs = null;
Dianne Hackbornc2293022013-02-06 23:14:49 -08001433 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001434 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -07001435 UidState uidState = getUidStateLocked(uid, false);
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07001436 Op op = getOpLocked(code, uid, packageName, true, verifyUid, isPrivileged);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001437 if (op != null) {
1438 if (op.mode != mode) {
1439 op.mode = mode;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001440 if (uidState != null) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001441 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001442 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001443 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001444 if (cbs != null) {
1445 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001446 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001447 }
1448 repCbs.addAll(cbs);
1449 }
1450 cbs = mPackageModeWatchers.get(packageName);
1451 if (cbs != null) {
1452 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001453 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001454 }
1455 repCbs.addAll(cbs);
1456 }
David Braunf5d83192013-09-16 13:43:51 -07001457 if (mode == AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001458 // If going into the default mode, prune this op
1459 // if there is nothing else interesting in it.
Dianne Hackborn607b4142013-08-02 18:10:10 -07001460 pruneOp(op, uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001461 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001462 scheduleFastWriteLocked();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001463 }
1464 }
1465 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001466 if (repCbs != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001467 mHandler.sendMessage(PooledLambda.obtainMessage(
1468 AppOpsService::notifyOpChanged,
1469 this, repCbs, code, uid, packageName));
Dianne Hackbornc2293022013-02-06 23:14:49 -08001470 }
Sudheer Shankab1613982019-05-16 16:55:50 -07001471
1472 notifyOpChangedSync(code, uid, packageName, mode);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001473 }
1474
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001475 private void notifyOpChanged(ArraySet<ModeCallback> callbacks, int code,
1476 int uid, String packageName) {
1477 for (int i = 0; i < callbacks.size(); i++) {
1478 final ModeCallback callback = callbacks.valueAt(i);
1479 notifyOpChanged(callback, code, uid, packageName);
1480 }
1481 }
1482
1483 private void notifyOpChanged(ModeCallback callback, int code,
1484 int uid, String packageName) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001485 if (uid != UID_ANY && callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001486 return;
1487 }
1488 // There are components watching for mode changes such as window manager
1489 // and location manager which are in our process. The callbacks in these
1490 // components may require permissions our remote caller does not have.
1491 final long identity = Binder.clearCallingIdentity();
1492 try {
1493 callback.mCallback.opChanged(code, uid, packageName);
1494 } catch (RemoteException e) {
1495 /* ignore */
1496 } finally {
1497 Binder.restoreCallingIdentity(identity);
1498 }
1499 }
1500
1501 private static HashMap<ModeCallback, ArrayList<ChangeRec>> addCallbacks(
1502 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks,
1503 int op, int uid, String packageName, ArraySet<ModeCallback> cbs) {
Dianne Hackborn607b4142013-08-02 18:10:10 -07001504 if (cbs == null) {
1505 return callbacks;
1506 }
1507 if (callbacks == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001508 callbacks = new HashMap<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001509 }
Svet Ganov2af57082015-07-30 08:44:20 -07001510 boolean duplicate = false;
Dianne Hackborn68d76552017-02-27 15:32:03 -08001511 final int N = cbs.size();
1512 for (int i=0; i<N; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001513 ModeCallback cb = cbs.valueAt(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001514 ArrayList<ChangeRec> reports = callbacks.get(cb);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001515 if (reports == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001516 reports = new ArrayList<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001517 callbacks.put(cb, reports);
Svet Ganov2af57082015-07-30 08:44:20 -07001518 } else {
1519 final int reportCount = reports.size();
1520 for (int j = 0; j < reportCount; j++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001521 ChangeRec report = reports.get(j);
1522 if (report.op == op && report.pkg.equals(packageName)) {
Svet Ganov2af57082015-07-30 08:44:20 -07001523 duplicate = true;
1524 break;
1525 }
1526 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001527 }
Svet Ganov2af57082015-07-30 08:44:20 -07001528 if (!duplicate) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001529 reports.add(new ChangeRec(op, uid, packageName));
Svet Ganov2af57082015-07-30 08:44:20 -07001530 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001531 }
1532 return callbacks;
1533 }
1534
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001535 static final class ChangeRec {
1536 final int op;
1537 final int uid;
1538 final String pkg;
1539
1540 ChangeRec(int _op, int _uid, String _pkg) {
1541 op = _op;
1542 uid = _uid;
1543 pkg = _pkg;
1544 }
1545 }
1546
Dianne Hackborn607b4142013-08-02 18:10:10 -07001547 @Override
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001548 public void resetAllModes(int reqUserId, String reqPackageName) {
1549 final int callingPid = Binder.getCallingPid();
1550 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001551 reqUserId = ActivityManager.handleIncomingUser(callingPid, callingUid, reqUserId,
1552 true, true, "resetAllModes", null);
Svet Ganov2af57082015-07-30 08:44:20 -07001553
1554 int reqUid = -1;
1555 if (reqPackageName != null) {
1556 try {
1557 reqUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -07001558 reqPackageName, PackageManager.MATCH_UNINSTALLED_PACKAGES, reqUserId);
Svet Ganov2af57082015-07-30 08:44:20 -07001559 } catch (RemoteException e) {
1560 /* ignore - local call */
1561 }
1562 }
1563
Dianne Hackbornd5254412018-05-11 18:02:58 -07001564 enforceManageAppOpsModes(callingPid, callingUid, reqUid);
1565
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001566 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks = null;
Dianne Hackborn607b4142013-08-02 18:10:10 -07001567 synchronized (this) {
1568 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -07001569 for (int i = mUidStates.size() - 1; i >= 0; i--) {
1570 UidState uidState = mUidStates.valueAt(i);
1571
1572 SparseIntArray opModes = uidState.opModes;
1573 if (opModes != null && (uidState.uid == reqUid || reqUid == -1)) {
1574 final int uidOpCount = opModes.size();
1575 for (int j = uidOpCount - 1; j >= 0; j--) {
1576 final int code = opModes.keyAt(j);
1577 if (AppOpsManager.opAllowsReset(code)) {
1578 opModes.removeAt(j);
1579 if (opModes.size() <= 0) {
1580 uidState.opModes = null;
1581 }
1582 for (String packageName : getPackagesForUid(uidState.uid)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001583 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -07001584 mOpModeWatchers.get(code));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001585 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -07001586 mPackageModeWatchers.get(packageName));
1587 }
1588 }
1589 }
1590 }
1591
1592 if (uidState.pkgOps == null) {
1593 continue;
1594 }
1595
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001596 if (reqUserId != UserHandle.USER_ALL
Svet Ganov2af57082015-07-30 08:44:20 -07001597 && reqUserId != UserHandle.getUserId(uidState.uid)) {
Alexandra Gherghinad6a98972014-08-04 17:05:34 +01001598 // Skip any ops for a different user
1599 continue;
1600 }
Svet Ganov2af57082015-07-30 08:44:20 -07001601
1602 Map<String, Ops> packages = uidState.pkgOps;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001603 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001604 boolean uidChanged = false;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001605 while (it.hasNext()) {
1606 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001607 String packageName = ent.getKey();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001608 if (reqPackageName != null && !reqPackageName.equals(packageName)) {
1609 // Skip any ops for a different package
1610 continue;
1611 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001612 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001613 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -07001614 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -07001615 if (AppOpsManager.opAllowsReset(curOp.op)
1616 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -07001617 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001618 changed = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001619 uidChanged = true;
Svet Ganovaf189e32019-02-15 18:45:29 -08001620 final int uid = curOp.uidState.uid;
1621 callbacks = addCallbacks(callbacks, curOp.op, uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -07001622 mOpModeWatchers.get(curOp.op));
Svet Ganovaf189e32019-02-15 18:45:29 -08001623 callbacks = addCallbacks(callbacks, curOp.op, uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -07001624 mPackageModeWatchers.get(packageName));
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001625 if (!curOp.hasAnyTime()) {
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001626 pkgOps.removeAt(j);
1627 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001628 }
1629 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001630 if (pkgOps.size() == 0) {
1631 it.remove();
1632 }
1633 }
Svet Ganov2af57082015-07-30 08:44:20 -07001634 if (uidState.isDefault()) {
1635 mUidStates.remove(uidState.uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001636 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001637 if (uidChanged) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001638 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001639 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001640 }
Svet Ganov2af57082015-07-30 08:44:20 -07001641
Dianne Hackborn607b4142013-08-02 18:10:10 -07001642 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001643 scheduleFastWriteLocked();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001644 }
1645 }
1646 if (callbacks != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001647 for (Map.Entry<ModeCallback, ArrayList<ChangeRec>> ent : callbacks.entrySet()) {
1648 ModeCallback cb = ent.getKey();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001649 ArrayList<ChangeRec> reports = ent.getValue();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001650 for (int i=0; i<reports.size(); i++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001651 ChangeRec rep = reports.get(i);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001652 mHandler.sendMessage(PooledLambda.obtainMessage(
1653 AppOpsService::notifyOpChanged,
1654 this, cb, rep.op, rep.uid, rep.pkg));
Dianne Hackborn607b4142013-08-02 18:10:10 -07001655 }
1656 }
1657 }
1658 }
1659
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001660 private void evalAllForegroundOpsLocked() {
1661 for (int uidi = mUidStates.size() - 1; uidi >= 0; uidi--) {
1662 final UidState uidState = mUidStates.valueAt(uidi);
1663 if (uidState.foregroundOps != null) {
1664 uidState.evalForegroundOps(mOpModeWatchers);
1665 }
1666 }
1667 }
1668
Dianne Hackbornc2293022013-02-06 23:14:49 -08001669 @Override
1670 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001671 startWatchingModeWithFlags(op, packageName, 0, callback);
1672 }
1673
1674 @Override
1675 public void startWatchingModeWithFlags(int op, String packageName, int flags,
1676 IAppOpsCallback callback) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001677 int watchedUid = -1;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001678 final int callingUid = Binder.getCallingUid();
1679 final int callingPid = Binder.getCallingPid();
Dianne Hackborn5376edd2018-06-05 13:21:16 -07001680 // TODO: should have a privileged permission to protect this.
1681 // Also, if the caller has requested WATCH_FOREGROUND_CHANGES, should we require
1682 // the USAGE_STATS permission since this can provide information about when an
1683 // app is in the foreground?
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001684 Preconditions.checkArgumentInRange(op, AppOpsManager.OP_NONE,
1685 AppOpsManager._NUM_OP - 1, "Invalid op code: " + op);
Svetoslav Ganov8de59712015-12-09 18:25:13 -08001686 if (callback == null) {
1687 return;
1688 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001689 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -07001690 op = (op != AppOpsManager.OP_NONE) ? AppOpsManager.opToSwitch(op) : op;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001691 ModeCallback cb = mModeWatchers.get(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -08001692 if (cb == null) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001693 cb = new ModeCallback(callback, watchedUid, flags, callingUid, callingPid);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001694 mModeWatchers.put(callback.asBinder(), cb);
1695 }
1696 if (op != AppOpsManager.OP_NONE) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001697 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(op);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001698 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08001699 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001700 mOpModeWatchers.put(op, cbs);
1701 }
1702 cbs.add(cb);
1703 }
1704 if (packageName != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001705 ArraySet<ModeCallback> cbs = mPackageModeWatchers.get(packageName);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001706 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08001707 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001708 mPackageModeWatchers.put(packageName, cbs);
1709 }
1710 cbs.add(cb);
1711 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001712 evalAllForegroundOpsLocked();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001713 }
1714 }
1715
1716 @Override
1717 public void stopWatchingMode(IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -08001718 if (callback == null) {
1719 return;
1720 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001721 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001722 ModeCallback cb = mModeWatchers.remove(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -08001723 if (cb != null) {
1724 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001725 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001726 ArraySet<ModeCallback> cbs = mOpModeWatchers.valueAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001727 cbs.remove(cb);
1728 if (cbs.size() <= 0) {
1729 mOpModeWatchers.removeAt(i);
1730 }
1731 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001732 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001733 ArraySet<ModeCallback> cbs = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001734 cbs.remove(cb);
1735 if (cbs.size() <= 0) {
1736 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001737 }
1738 }
1739 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001740 evalAllForegroundOpsLocked();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001741 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001742 }
1743
1744 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001745 public IBinder getToken(IBinder clientToken) {
1746 synchronized (this) {
1747 ClientState cs = mClients.get(clientToken);
1748 if (cs == null) {
1749 cs = new ClientState(clientToken);
1750 mClients.put(clientToken, cs);
1751 }
1752 return cs;
1753 }
1754 }
1755
Svet Ganovd873ae62018-06-25 16:39:23 -07001756 public CheckOpsDelegate getAppOpsServiceDelegate() {
1757 synchronized (this) {
1758 return mCheckOpsDelegate;
1759 }
1760 }
1761
1762 public void setAppOpsServiceDelegate(CheckOpsDelegate delegate) {
1763 synchronized (this) {
1764 mCheckOpsDelegate = delegate;
1765 }
1766 }
1767
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001768 @Override
Svet Ganov9d528a12018-12-19 17:23:11 -08001769 public int checkOperationRaw(int code, int uid, String packageName) {
1770 return checkOperationInternal(code, uid, packageName, true /*raw*/);
1771 }
1772
1773 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -08001774 public int checkOperation(int code, int uid, String packageName) {
Svet Ganov9d528a12018-12-19 17:23:11 -08001775 return checkOperationInternal(code, uid, packageName, false /*raw*/);
1776 }
1777
1778 private int checkOperationInternal(int code, int uid, String packageName, boolean raw) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001779 final CheckOpsDelegate delegate;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001780 synchronized (this) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001781 delegate = mCheckOpsDelegate;
1782 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001783 if (delegate == null) {
Svet Ganov9d528a12018-12-19 17:23:11 -08001784 return checkOperationImpl(code, uid, packageName, raw);
Todd Kennedy556efba2018-11-15 07:43:55 -08001785 }
Svet Ganov9d528a12018-12-19 17:23:11 -08001786 return delegate.checkOperation(code, uid, packageName, raw,
Svet Ganovd873ae62018-06-25 16:39:23 -07001787 AppOpsService.this::checkOperationImpl);
1788 }
1789
Svet Ganov9d528a12018-12-19 17:23:11 -08001790 private int checkOperationImpl(int code, int uid, String packageName,
1791 boolean raw) {
Todd Kennedy556efba2018-11-15 07:43:55 -08001792 verifyIncomingUid(uid);
1793 verifyIncomingOp(code);
1794 String resolvedPackageName = resolvePackageName(uid, packageName);
1795 if (resolvedPackageName == null) {
1796 return AppOpsManager.MODE_IGNORED;
1797 }
Svet Ganov9d528a12018-12-19 17:23:11 -08001798 return checkOperationUnchecked(code, uid, resolvedPackageName, raw);
Todd Kennedy556efba2018-11-15 07:43:55 -08001799 }
1800
Philip P. Moltmann724150d2019-03-11 17:01:05 -07001801 /**
1802 * @see #checkOperationUnchecked(int, int, String, boolean, boolean)
1803 */
1804 private @Mode int checkOperationUnchecked(int code, int uid, @NonNull String packageName,
1805 boolean raw) {
1806 return checkOperationUnchecked(code, uid, packageName, raw, true);
1807 }
1808
1809 /**
1810 * Get the mode of an app-op.
1811 *
1812 * @param code The code of the op
1813 * @param uid The uid of the package the op belongs to
1814 * @param packageName The package the op belongs to
1815 * @param raw If the raw state of eval-ed state should be checked.
1816 * @param verify If the code should check the package belongs to the uid
1817 *
1818 * @return The mode of the op
1819 */
1820 private @Mode int checkOperationUnchecked(int code, int uid, @NonNull String packageName,
1821 boolean raw, boolean verify) {
Suprabh Shukla873e19f2019-09-16 13:20:22 -07001822 if (isOpRestrictedDueToSuspend(code, packageName, uid)) {
1823 return AppOpsManager.MODE_IGNORED;
1824 }
Svet Ganovd873ae62018-06-25 16:39:23 -07001825 synchronized (this) {
Philip P. Moltmann724150d2019-03-11 17:01:05 -07001826 if (verify) {
1827 checkPackage(uid, packageName);
1828 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001829 if (isOpRestrictedLocked(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001830 return AppOpsManager.MODE_IGNORED;
1831 }
Svet Ganov2af57082015-07-30 08:44:20 -07001832 code = AppOpsManager.opToSwitch(code);
1833 UidState uidState = getUidStateLocked(uid, false);
Svet Ganovee438d42017-01-19 18:04:38 -08001834 if (uidState != null && uidState.opModes != null
1835 && uidState.opModes.indexOfKey(code) >= 0) {
Svet Ganov9d528a12018-12-19 17:23:11 -08001836 final int rawMode = uidState.opModes.get(code);
Svet Ganovaf189e32019-02-15 18:45:29 -08001837 return raw ? rawMode : uidState.evalMode(code, rawMode);
Svet Ganov2af57082015-07-30 08:44:20 -07001838 }
Philip P. Moltmann724150d2019-03-11 17:01:05 -07001839 Op op = getOpLocked(code, uid, packageName, false, verify, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001840 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -07001841 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001842 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001843 return raw ? op.mode : op.evalMode();
Dianne Hackborn35654b62013-01-14 17:38:02 -08001844 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001845 }
1846
1847 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001848 public int checkAudioOperation(int code, int usage, int uid, String packageName) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001849 final CheckOpsDelegate delegate;
John Spurlock1af30c72014-03-10 08:33:35 -04001850 synchronized (this) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001851 delegate = mCheckOpsDelegate;
1852 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001853 if (delegate == null) {
1854 return checkAudioOperationImpl(code, usage, uid, packageName);
1855 }
Svet Ganovd873ae62018-06-25 16:39:23 -07001856 return delegate.checkAudioOperation(code, usage, uid, packageName,
1857 AppOpsService.this::checkAudioOperationImpl);
1858 }
1859
1860 private int checkAudioOperationImpl(int code, int usage, int uid, String packageName) {
Todd Kennedy556efba2018-11-15 07:43:55 -08001861 boolean suspended;
1862 try {
1863 suspended = isPackageSuspendedForUser(packageName, uid);
1864 } catch (IllegalArgumentException ex) {
1865 // Package not found.
1866 suspended = false;
1867 }
1868
1869 if (suspended) {
1870 Slog.i(TAG, "Audio disabled for suspended package=" + packageName
1871 + " for uid=" + uid);
1872 return AppOpsManager.MODE_IGNORED;
1873 }
1874
Svet Ganovd873ae62018-06-25 16:39:23 -07001875 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001876 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -04001877 if (mode != AppOpsManager.MODE_ALLOWED) {
1878 return mode;
1879 }
1880 }
1881 return checkOperation(code, uid, packageName);
1882 }
1883
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001884 private boolean isPackageSuspendedForUser(String pkg, int uid) {
Svet Ganov8d123f42019-04-09 17:11:12 -07001885 final long identity = Binder.clearCallingIdentity();
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001886 try {
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001887 return AppGlobals.getPackageManager().isPackageSuspendedForUser(
1888 pkg, UserHandle.getUserId(uid));
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001889 } catch (RemoteException re) {
1890 throw new SecurityException("Could not talk to package manager service");
Svet Ganov8d123f42019-04-09 17:11:12 -07001891 } finally {
1892 Binder.restoreCallingIdentity(identity);
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001893 }
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001894 }
1895
John Spurlock7b414672014-07-18 13:02:39 -04001896 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
1897 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1898 if (usageRestrictions != null) {
1899 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001900 if (r != null && !r.exceptionPackages.contains(packageName)) {
1901 return r.mode;
1902 }
1903 }
1904 return AppOpsManager.MODE_ALLOWED;
1905 }
1906
1907 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001908 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -04001909 String[] exceptionPackages) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07001910 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
John Spurlock1af30c72014-03-10 08:33:35 -04001911 verifyIncomingUid(uid);
1912 verifyIncomingOp(code);
1913 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001914 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1915 if (usageRestrictions == null) {
1916 usageRestrictions = new SparseArray<Restriction>();
1917 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -04001918 }
John Spurlock7b414672014-07-18 13:02:39 -04001919 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001920 if (mode != AppOpsManager.MODE_ALLOWED) {
1921 final Restriction r = new Restriction();
1922 r.mode = mode;
1923 if (exceptionPackages != null) {
1924 final int N = exceptionPackages.length;
1925 r.exceptionPackages = new ArraySet<String>(N);
1926 for (int i = 0; i < N; i++) {
1927 final String pkg = exceptionPackages[i];
1928 if (pkg != null) {
1929 r.exceptionPackages.add(pkg.trim());
1930 }
1931 }
1932 }
John Spurlock7b414672014-07-18 13:02:39 -04001933 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -04001934 }
1935 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001936
1937 mHandler.sendMessage(PooledLambda.obtainMessage(
Svet Ganov3a95f832018-03-23 17:44:30 -07001938 AppOpsService::notifyWatchersOfChange, this, code, UID_ANY));
John Spurlock1af30c72014-03-10 08:33:35 -04001939 }
1940
1941 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001942 public int checkPackage(int uid, String packageName) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001943 Preconditions.checkNotNull(packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001944 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001945 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1946 true /* uidMismatchExpected */);
1947 if (ops != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001948 return AppOpsManager.MODE_ALLOWED;
1949 } else {
1950 return AppOpsManager.MODE_ERRORED;
1951 }
1952 }
1953 }
1954
1955 @Override
Svet Ganovd873ae62018-06-25 16:39:23 -07001956 public int noteProxyOperation(int code, int proxyUid,
1957 String proxyPackageName, int proxiedUid, String proxiedPackageName) {
1958 verifyIncomingUid(proxyUid);
Svet Ganov99b60432015-06-27 13:15:22 -07001959 verifyIncomingOp(code);
Svet Ganovaf189e32019-02-15 18:45:29 -08001960
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001961 String resolveProxyPackageName = resolvePackageName(proxyUid, proxyPackageName);
1962 if (resolveProxyPackageName == null) {
1963 return AppOpsManager.MODE_IGNORED;
1964 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001965
1966 final boolean isProxyTrusted = mContext.checkPermission(
1967 Manifest.permission.UPDATE_APP_OPS_STATS, -1, proxyUid)
1968 == PackageManager.PERMISSION_GRANTED;
1969
1970 final int proxyFlags = isProxyTrusted ? AppOpsManager.OP_FLAG_TRUSTED_PROXY
1971 : AppOpsManager.OP_FLAG_UNTRUSTED_PROXY;
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001972 final int proxyMode = noteOperationUnchecked(code, proxyUid,
Svet Ganovaf189e32019-02-15 18:45:29 -08001973 resolveProxyPackageName, Process.INVALID_UID, null, proxyFlags);
Svet Ganov99b60432015-06-27 13:15:22 -07001974 if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
1975 return proxyMode;
1976 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001977
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001978 String resolveProxiedPackageName = resolvePackageName(proxiedUid, proxiedPackageName);
1979 if (resolveProxiedPackageName == null) {
1980 return AppOpsManager.MODE_IGNORED;
1981 }
Svet Ganovaf189e32019-02-15 18:45:29 -08001982 final int proxiedFlags = isProxyTrusted ? AppOpsManager.OP_FLAG_TRUSTED_PROXIED
1983 : AppOpsManager.OP_FLAG_UNTRUSTED_PROXIED;
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001984 return noteOperationUnchecked(code, proxiedUid, resolveProxiedPackageName,
Svet Ganovaf189e32019-02-15 18:45:29 -08001985 proxyUid, resolveProxyPackageName, proxiedFlags);
Svet Ganov99b60432015-06-27 13:15:22 -07001986 }
1987
1988 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001989 public int noteOperation(int code, int uid, String packageName) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001990 final CheckOpsDelegate delegate;
1991 synchronized (this) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001992 delegate = mCheckOpsDelegate;
1993 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001994 if (delegate == null) {
1995 return noteOperationImpl(code, uid, packageName);
1996 }
Svet Ganovd873ae62018-06-25 16:39:23 -07001997 return delegate.noteOperation(code, uid, packageName,
1998 AppOpsService.this::noteOperationImpl);
1999 }
2000
2001 private int noteOperationImpl(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002002 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08002003 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002004 String resolvedPackageName = resolvePackageName(uid, packageName);
2005 if (resolvedPackageName == null) {
2006 return AppOpsManager.MODE_IGNORED;
2007 }
Svet Ganovaf189e32019-02-15 18:45:29 -08002008 return noteOperationUnchecked(code, uid, resolvedPackageName, Process.INVALID_UID, null,
2009 AppOpsManager.OP_FLAG_SELF);
Svet Ganov99b60432015-06-27 13:15:22 -07002010 }
2011
2012 private int noteOperationUnchecked(int code, int uid, String packageName,
Svet Ganovaf189e32019-02-15 18:45:29 -08002013 int proxyUid, String proxyPackageName, @OpFlags int flags) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002014 synchronized (this) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002015 final Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
Yohei Yukawaa965d652017-10-12 15:02:26 -07002016 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002017 if (ops == null) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002018 scheduleOpNotedIfNeededLocked(code, uid, packageName,
2019 AppOpsManager.MODE_IGNORED);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002020 if (DEBUG) Slog.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002021 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07002022 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002023 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002024 final Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07002025 if (isOpRestrictedLocked(uid, code, packageName)) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002026 scheduleOpNotedIfNeededLocked(code, uid, packageName,
2027 AppOpsManager.MODE_IGNORED);
Jason Monk62062992014-05-06 09:55:28 -04002028 return AppOpsManager.MODE_IGNORED;
2029 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002030 final UidState uidState = ops.uidState;
Svet Ganovaf189e32019-02-15 18:45:29 -08002031 if (op.running) {
2032 final OpEntry entry = new OpEntry(op.op, op.running, op.mode, op.mAccessTimes,
2033 op.mRejectTimes, op.mDurations, op.mProxyUids, op.mProxyPackageNames);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002034 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
Svet Ganovaf189e32019-02-15 18:45:29 -08002035 + " code " + code + " time=" + entry.getLastAccessTime(uidState.state,
2036 uidState.state, flags) + " duration=" + entry.getLastDuration(
2037 uidState.state, uidState.state, flags));
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002038 }
Svet Ganovaf189e32019-02-15 18:45:29 -08002039
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002040 final int switchCode = AppOpsManager.opToSwitch(code);
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07002041 // If there is a non-default per UID policy (we set UID op mode only if
2042 // non-default) it takes over, otherwise use the per package policy.
2043 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002044 final int uidMode = uidState.evalMode(code, uidState.opModes.get(switchCode));
Svet Ganov2af57082015-07-30 08:44:20 -07002045 if (uidMode != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002046 if (DEBUG) Slog.d(TAG, "noteOperation: uid reject #" + uidMode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07002047 + switchCode + " (" + code + ") uid " + uid + " package "
2048 + packageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08002049 op.rejected(System.currentTimeMillis(), proxyUid, proxyPackageName,
2050 uidState.state, flags);
2051 mHistoricalRegistry.incrementOpRejected(code, uid, packageName,
2052 uidState.state, flags);
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002053 scheduleOpNotedIfNeededLocked(code, uid, packageName, uidMode);
Svet Ganov2af57082015-07-30 08:44:20 -07002054 return uidMode;
2055 }
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07002056 } else {
2057 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
Svet Ganovaf189e32019-02-15 18:45:29 -08002058 final int mode = switchOp.evalMode();
2059 if (switchOp.mode != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002060 if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + mode + " for code "
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07002061 + switchCode + " (" + code + ") uid " + uid + " package "
2062 + packageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08002063 op.rejected(System.currentTimeMillis(), proxyUid, proxyPackageName,
2064 uidState.state, flags);
2065 mHistoricalRegistry.incrementOpRejected(code, uid, packageName,
2066 uidState.state, flags);
2067 scheduleOpNotedIfNeededLocked(code, uid, packageName, mode);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002068 return mode;
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07002069 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002070 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002071 if (DEBUG) Slog.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002072 + " package " + packageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08002073 op.accessed(System.currentTimeMillis(), proxyUid, proxyPackageName,
2074 uidState.state, flags);
Svet Ganov8455ba22019-01-02 13:05:56 -08002075 mHistoricalRegistry.incrementOpAccessedCount(op.op, uid, packageName,
Svet Ganovaf189e32019-02-15 18:45:29 -08002076 uidState.state, flags);
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002077 scheduleOpNotedIfNeededLocked(code, uid, packageName,
2078 AppOpsManager.MODE_ALLOWED);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002079 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002080 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002081 }
2082
2083 @Override
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002084 public void startWatchingActive(int[] ops, IAppOpsActiveCallback callback) {
Svet Ganovf7b47252018-02-26 11:11:27 -08002085 int watchedUid = -1;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002086 final int callingUid = Binder.getCallingUid();
2087 final int callingPid = Binder.getCallingPid();
Svet Ganovf7b47252018-02-26 11:11:27 -08002088 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
2089 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002090 watchedUid = callingUid;
Svet Ganovf7b47252018-02-26 11:11:27 -08002091 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002092 if (ops != null) {
2093 Preconditions.checkArrayElementsInRange(ops, 0,
2094 AppOpsManager._NUM_OP - 1, "Invalid op code in: " + Arrays.toString(ops));
2095 }
2096 if (callback == null) {
2097 return;
2098 }
2099 synchronized (this) {
2100 SparseArray<ActiveCallback> callbacks = mActiveWatchers.get(callback.asBinder());
2101 if (callbacks == null) {
2102 callbacks = new SparseArray<>();
2103 mActiveWatchers.put(callback.asBinder(), callbacks);
2104 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002105 final ActiveCallback activeCallback = new ActiveCallback(callback, watchedUid,
2106 callingUid, callingPid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002107 for (int op : ops) {
2108 callbacks.put(op, activeCallback);
2109 }
2110 }
2111 }
2112
2113 @Override
2114 public void stopWatchingActive(IAppOpsActiveCallback callback) {
2115 if (callback == null) {
2116 return;
2117 }
2118 synchronized (this) {
2119 final SparseArray<ActiveCallback> activeCallbacks =
2120 mActiveWatchers.remove(callback.asBinder());
2121 if (activeCallbacks == null) {
2122 return;
2123 }
2124 final int callbackCount = activeCallbacks.size();
2125 for (int i = 0; i < callbackCount; i++) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002126 activeCallbacks.valueAt(i).destroy();
2127 }
2128 }
2129 }
2130
2131 @Override
2132 public void startWatchingNoted(@NonNull int[] ops, @NonNull IAppOpsNotedCallback callback) {
2133 int watchedUid = Process.INVALID_UID;
2134 final int callingUid = Binder.getCallingUid();
2135 final int callingPid = Binder.getCallingPid();
2136 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
2137 != PackageManager.PERMISSION_GRANTED) {
2138 watchedUid = callingUid;
2139 }
2140 Preconditions.checkArgument(!ArrayUtils.isEmpty(ops), "Ops cannot be null or empty");
2141 Preconditions.checkArrayElementsInRange(ops, 0, AppOpsManager._NUM_OP - 1,
2142 "Invalid op code in: " + Arrays.toString(ops));
2143 Preconditions.checkNotNull(callback, "Callback cannot be null");
2144 synchronized (this) {
2145 SparseArray<NotedCallback> callbacks = mNotedWatchers.get(callback.asBinder());
2146 if (callbacks == null) {
2147 callbacks = new SparseArray<>();
2148 mNotedWatchers.put(callback.asBinder(), callbacks);
2149 }
2150 final NotedCallback notedCallback = new NotedCallback(callback, watchedUid,
2151 callingUid, callingPid);
2152 for (int op : ops) {
2153 callbacks.put(op, notedCallback);
2154 }
2155 }
2156 }
2157
2158 @Override
2159 public void stopWatchingNoted(IAppOpsNotedCallback callback) {
2160 Preconditions.checkNotNull(callback, "Callback cannot be null");
2161 synchronized (this) {
2162 final SparseArray<NotedCallback> notedCallbacks =
2163 mNotedWatchers.remove(callback.asBinder());
2164 if (notedCallbacks == null) {
2165 return;
2166 }
2167 final int callbackCount = notedCallbacks.size();
2168 for (int i = 0; i < callbackCount; i++) {
2169 notedCallbacks.valueAt(i).destroy();
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002170 }
2171 }
2172 }
2173
2174 @Override
Svet Ganovf7b47252018-02-26 11:11:27 -08002175 public int startOperation(IBinder token, int code, int uid, String packageName,
2176 boolean startIfModeDefault) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002177 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08002178 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002179 String resolvedPackageName = resolvePackageName(uid, packageName);
2180 if (resolvedPackageName == null) {
2181 return AppOpsManager.MODE_IGNORED;
2182 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002183 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002184 synchronized (this) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002185 final Ops ops = getOpsRawLocked(uid, resolvedPackageName, true /* edit */,
Yohei Yukawaa965d652017-10-12 15:02:26 -07002186 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002187 if (ops == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002188 if (DEBUG) Slog.d(TAG, "startOperation: no op for code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002189 + " package " + resolvedPackageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07002190 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002191 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002192 final Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07002193 if (isOpRestrictedLocked(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -04002194 return AppOpsManager.MODE_IGNORED;
2195 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002196 final int switchCode = AppOpsManager.opToSwitch(code);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002197 final UidState uidState = ops.uidState;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002198 // If there is a non-default per UID policy (we set UID op mode only if
2199 // non-default) it takes over, otherwise use the per package policy.
Svet Ganovaf189e32019-02-15 18:45:29 -08002200 final int opCode = op.op;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002201 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002202 final int uidMode = uidState.evalMode(code, uidState.opModes.get(switchCode));
Svet Ganovf7b47252018-02-26 11:11:27 -08002203 if (uidMode != AppOpsManager.MODE_ALLOWED
2204 && (!startIfModeDefault || uidMode != AppOpsManager.MODE_DEFAULT)) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002205 if (DEBUG) Slog.d(TAG, "noteOperation: uid reject #" + uidMode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07002206 + switchCode + " (" + code + ") uid " + uid + " package "
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002207 + resolvedPackageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08002208 // We don't support proxy long running ops (start/stop)
2209 op.rejected(System.currentTimeMillis(), -1 /*proxyUid*/,
2210 null /*proxyPackage*/, uidState.state, AppOpsManager.OP_FLAG_SELF);
2211 mHistoricalRegistry.incrementOpRejected(opCode, uid, packageName,
2212 uidState.state, AppOpsManager.OP_FLAG_SELF);
Svet Ganov2af57082015-07-30 08:44:20 -07002213 return uidMode;
2214 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002215 } else {
2216 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
Svet Ganovaf189e32019-02-15 18:45:29 -08002217 final int mode = switchOp.evalMode();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002218 if (mode != AppOpsManager.MODE_ALLOWED
2219 && (!startIfModeDefault || mode != AppOpsManager.MODE_DEFAULT)) {
2220 if (DEBUG) Slog.d(TAG, "startOperation: reject #" + mode + " for code "
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002221 + switchCode + " (" + code + ") uid " + uid + " package "
2222 + resolvedPackageName);
Svet Ganovaf189e32019-02-15 18:45:29 -08002223 // We don't support proxy long running ops (start/stop)
2224 op.rejected(System.currentTimeMillis(), -1 /*proxyUid*/,
2225 null /*proxyPackage*/, uidState.state, AppOpsManager.OP_FLAG_SELF);
2226 mHistoricalRegistry.incrementOpRejected(opCode, uid, packageName,
2227 uidState.state, AppOpsManager.OP_FLAG_SELF);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002228 return mode;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002229 }
Svet Ganov2af57082015-07-30 08:44:20 -07002230 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002231 if (DEBUG) Slog.d(TAG, "startOperation: allowing code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002232 + " package " + resolvedPackageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002233 if (op.startNesting == 0) {
2234 op.startRealtime = SystemClock.elapsedRealtime();
Svet Ganovaf189e32019-02-15 18:45:29 -08002235 // We don't support proxy long running ops (start/stop)
2236 op.started(System.currentTimeMillis(), uidState.state,
2237 AppOpsManager.OP_FLAG_SELF);
2238 mHistoricalRegistry.incrementOpAccessedCount(opCode, uid, packageName,
2239 uidState.state, AppOpsManager.OP_FLAG_SELF);
2240
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002241 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002242 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002243 op.startNesting++;
2244 uidState.startNesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002245 if (client.mStartedOps != null) {
2246 client.mStartedOps.add(op);
2247 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002248 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002249
2250 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002251 }
2252
2253 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002254 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002255 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08002256 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002257 String resolvedPackageName = resolvePackageName(uid, packageName);
2258 if (resolvedPackageName == null) {
2259 return;
2260 }
2261 if (!(token instanceof ClientState)) {
2262 return;
2263 }
2264 ClientState client = (ClientState) token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002265 synchronized (this) {
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07002266 Op op = getOpLocked(code, uid, resolvedPackageName, true, true, false);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002267 if (op == null) {
2268 return;
2269 }
Svet Ganovf7b47252018-02-26 11:11:27 -08002270 if (!client.mStartedOps.remove(op)) {
Svet Ganovf5d5af12018-03-18 11:51:17 -07002271 // We finish ops when packages get removed to guarantee no dangling
2272 // started ops. However, some part of the system may asynchronously
2273 // finish ops for an already gone package. Hence, finishing an op
2274 // for a non existing package is fine and we don't log as a wtf.
2275 final long identity = Binder.clearCallingIdentity();
2276 try {
2277 if (LocalServices.getService(PackageManagerInternal.class).getPackageUid(
2278 resolvedPackageName, 0, UserHandle.getUserId(uid)) < 0) {
2279 Slog.i(TAG, "Finishing op=" + AppOpsManager.opToName(code)
2280 + " for non-existing package=" + resolvedPackageName
2281 + " in uid=" + uid);
2282 return;
2283 }
2284 } finally {
2285 Binder.restoreCallingIdentity(identity);
2286 }
Svet Ganovaf189e32019-02-15 18:45:29 -08002287 Slog.wtf(TAG, "Operation not started: uid=" + op.uidState.uid + " pkg="
Svet Ganovf5d5af12018-03-18 11:51:17 -07002288 + op.packageName + " op=" + AppOpsManager.opToName(op.op));
Svet Ganov31d83ae2018-03-15 10:45:56 -07002289 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002290 }
Svet Ganova7a0db62018-02-27 20:08:01 -08002291 finishOperationLocked(op, /*finishNested*/ false);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002292 if (op.startNesting <= 0) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002293 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, false);
2294 }
2295 }
2296 }
2297
2298 private void scheduleOpActiveChangedIfNeededLocked(int code, int uid, String packageName,
2299 boolean active) {
2300 ArraySet<ActiveCallback> dispatchedCallbacks = null;
2301 final int callbackListCount = mActiveWatchers.size();
2302 for (int i = 0; i < callbackListCount; i++) {
2303 final SparseArray<ActiveCallback> callbacks = mActiveWatchers.valueAt(i);
2304 ActiveCallback callback = callbacks.get(code);
2305 if (callback != null) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002306 if (callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
Svet Ganovf7b47252018-02-26 11:11:27 -08002307 continue;
2308 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002309 if (dispatchedCallbacks == null) {
2310 dispatchedCallbacks = new ArraySet<>();
2311 }
2312 dispatchedCallbacks.add(callback);
2313 }
2314 }
2315 if (dispatchedCallbacks == null) {
2316 return;
2317 }
2318 mHandler.sendMessage(PooledLambda.obtainMessage(
2319 AppOpsService::notifyOpActiveChanged,
2320 this, dispatchedCallbacks, code, uid, packageName, active));
2321 }
2322
2323 private void notifyOpActiveChanged(ArraySet<ActiveCallback> callbacks,
2324 int code, int uid, String packageName, boolean active) {
2325 // There are components watching for mode changes such as window manager
2326 // and location manager which are in our process. The callbacks in these
2327 // components may require permissions our remote caller does not have.
2328 final long identity = Binder.clearCallingIdentity();
2329 try {
2330 final int callbackCount = callbacks.size();
2331 for (int i = 0; i < callbackCount; i++) {
2332 final ActiveCallback callback = callbacks.valueAt(i);
2333 try {
2334 callback.mCallback.opActiveChanged(code, uid, packageName, active);
2335 } catch (RemoteException e) {
2336 /* do nothing */
2337 }
2338 }
2339 } finally {
2340 Binder.restoreCallingIdentity(identity);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002341 }
2342 }
2343
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002344 private void scheduleOpNotedIfNeededLocked(int code, int uid, String packageName,
2345 int result) {
2346 ArraySet<NotedCallback> dispatchedCallbacks = null;
2347 final int callbackListCount = mNotedWatchers.size();
2348 for (int i = 0; i < callbackListCount; i++) {
2349 final SparseArray<NotedCallback> callbacks = mNotedWatchers.valueAt(i);
2350 final NotedCallback callback = callbacks.get(code);
2351 if (callback != null) {
2352 if (callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
2353 continue;
2354 }
2355 if (dispatchedCallbacks == null) {
2356 dispatchedCallbacks = new ArraySet<>();
2357 }
2358 dispatchedCallbacks.add(callback);
2359 }
2360 }
2361 if (dispatchedCallbacks == null) {
2362 return;
2363 }
2364 mHandler.sendMessage(PooledLambda.obtainMessage(
2365 AppOpsService::notifyOpChecked,
2366 this, dispatchedCallbacks, code, uid, packageName, result));
2367 }
2368
2369 private void notifyOpChecked(ArraySet<NotedCallback> callbacks,
2370 int code, int uid, String packageName, int result) {
2371 // There are components watching for checks in our process. The callbacks in
2372 // these components may require permissions our remote caller does not have.
2373 final long identity = Binder.clearCallingIdentity();
2374 try {
2375 final int callbackCount = callbacks.size();
2376 for (int i = 0; i < callbackCount; i++) {
2377 final NotedCallback callback = callbacks.valueAt(i);
2378 try {
2379 callback.mCallback.opNoted(code, uid, packageName, result);
2380 } catch (RemoteException e) {
2381 /* do nothing */
2382 }
2383 }
2384 } finally {
2385 Binder.restoreCallingIdentity(identity);
2386 }
2387 }
2388
Svet Ganovb9d71a62015-04-30 10:38:13 -07002389 @Override
2390 public int permissionToOpCode(String permission) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002391 if (permission == null) {
2392 return AppOpsManager.OP_NONE;
2393 }
Svet Ganovb9d71a62015-04-30 10:38:13 -07002394 return AppOpsManager.permissionToOpCode(permission);
2395 }
2396
Svet Ganova7a0db62018-02-27 20:08:01 -08002397 void finishOperationLocked(Op op, boolean finishNested) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002398 final int opCode = op.op;
2399 final int uid = op.uidState.uid;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002400 if (op.startNesting <= 1 || finishNested) {
2401 if (op.startNesting == 1 || finishNested) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002402 // We don't support proxy long running ops (start/stop)
2403 final long duration = SystemClock.elapsedRealtime() - op.startRealtime;
2404 op.finished(System.currentTimeMillis(), duration, op.uidState.state,
2405 AppOpsManager.OP_FLAG_SELF);
2406 mHistoricalRegistry.increaseOpAccessDuration(opCode, uid, op.packageName,
2407 op.uidState.state, AppOpsManager.OP_FLAG_SELF, duration);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002408 } else {
Svet Ganovaf189e32019-02-15 18:45:29 -08002409 final OpEntry entry = new OpEntry(op.op, op.running, op.mode, op.mAccessTimes,
2410 op.mRejectTimes, op.mDurations, op.mProxyUids, op.mProxyPackageNames);
2411 Slog.w(TAG, "Finishing op nesting under-run: uid " + uid + " pkg "
2412 + op.packageName + " code " + opCode + " time="
2413 + entry.getLastAccessTime(OP_FLAGS_ALL)
2414 + " duration=" + entry.getLastDuration(MAX_PRIORITY_UID_STATE,
2415 MIN_PRIORITY_UID_STATE, OP_FLAGS_ALL) + " nesting=" + op.startNesting);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002416 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002417 if (op.startNesting >= 1) {
2418 op.uidState.startNesting -= op.startNesting;
2419 }
2420 op.startNesting = 0;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002421 } else {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002422 op.startNesting--;
2423 op.uidState.startNesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002424 }
2425 }
2426
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002427 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002428 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002429 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002430 }
2431 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002432 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002433 }
2434 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
2435 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002436 }
2437
Dianne Hackborn961321f2013-02-05 17:22:41 -08002438 private void verifyIncomingOp(int op) {
2439 if (op >= 0 && op < AppOpsManager._NUM_OP) {
2440 return;
2441 }
2442 throw new IllegalArgumentException("Bad operation #" + op);
2443 }
2444
Philip P. Moltmann724150d2019-03-11 17:01:05 -07002445 private @Nullable UidState getUidStateLocked(int uid, boolean edit) {
Svet Ganov2af57082015-07-30 08:44:20 -07002446 UidState uidState = mUidStates.get(uid);
2447 if (uidState == null) {
2448 if (!edit) {
2449 return null;
2450 }
2451 uidState = new UidState(uid);
2452 mUidStates.put(uid, uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002453 } else {
2454 if (uidState.pendingStateCommitTime != 0) {
Dianne Hackborn9fb93502018-06-18 12:29:44 -07002455 if (uidState.pendingStateCommitTime < mLastRealtime) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002456 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002457 } else {
Dianne Hackborn9fb93502018-06-18 12:29:44 -07002458 mLastRealtime = SystemClock.elapsedRealtime();
2459 if (uidState.pendingStateCommitTime < mLastRealtime) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002460 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002461 }
2462 }
2463 }
Svet Ganov2af57082015-07-30 08:44:20 -07002464 }
2465 return uidState;
2466 }
2467
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002468 private void commitUidPendingStateLocked(UidState uidState) {
Wei Wange1f864e2019-03-28 18:12:18 -07002469 if (uidState.hasForegroundWatchers) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002470 for (int fgi = uidState.foregroundOps.size() - 1; fgi >= 0; fgi--) {
2471 if (!uidState.foregroundOps.valueAt(fgi)) {
2472 continue;
2473 }
2474 final int code = uidState.foregroundOps.keyAt(fgi);
Svet Ganovaf189e32019-02-15 18:45:29 -08002475 // For location ops we consider fg state only if the fg service
2476 // is of location type, for all other ops any fg service will do.
Wei Wang711eb662019-03-21 18:24:17 -07002477 final long firstUnrestrictedUidState = resolveFirstUnrestrictedUidState(code);
2478 final boolean resolvedLastFg = uidState.state <= firstUnrestrictedUidState;
2479 final boolean resolvedNowFg = uidState.pendingState <= firstUnrestrictedUidState;
2480 if (resolvedLastFg == resolvedNowFg) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002481 continue;
2482 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002483 final ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
2484 if (callbacks != null) {
2485 for (int cbi = callbacks.size() - 1; cbi >= 0; cbi--) {
2486 final ModeCallback callback = callbacks.valueAt(cbi);
2487 if ((callback.mFlags & AppOpsManager.WATCH_FOREGROUND_CHANGES) == 0
2488 || !callback.isWatchingUid(uidState.uid)) {
2489 continue;
2490 }
2491 boolean doAllPackages = uidState.opModes != null
Hai Zhang2b98fb32018-09-21 15:18:46 -07002492 && uidState.opModes.indexOfKey(code) >= 0
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002493 && uidState.opModes.get(code) == AppOpsManager.MODE_FOREGROUND;
2494 if (uidState.pkgOps != null) {
2495 for (int pkgi = uidState.pkgOps.size() - 1; pkgi >= 0; pkgi--) {
2496 final Op op = uidState.pkgOps.valueAt(pkgi).get(code);
Svet Ganovaf189e32019-02-15 18:45:29 -08002497 if (op == null) {
2498 continue;
2499 }
2500 if (doAllPackages || op.mode == AppOpsManager.MODE_FOREGROUND) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002501 mHandler.sendMessage(PooledLambda.obtainMessage(
2502 AppOpsService::notifyOpChanged,
2503 this, callback, code, uidState.uid,
2504 uidState.pkgOps.keyAt(pkgi)));
2505 }
2506 }
2507 }
2508 }
2509 }
2510 }
2511 }
Wei Wang711eb662019-03-21 18:24:17 -07002512 uidState.state = uidState.pendingState;
2513 uidState.pendingStateCommitTime = 0;
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002514 }
2515
Yohei Yukawaa965d652017-10-12 15:02:26 -07002516 private Ops getOpsRawLocked(int uid, String packageName, boolean edit,
2517 boolean uidMismatchExpected) {
Svet Ganov2af57082015-07-30 08:44:20 -07002518 UidState uidState = getUidStateLocked(uid, edit);
2519 if (uidState == null) {
2520 return null;
2521 }
2522
2523 if (uidState.pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002524 if (!edit) {
2525 return null;
2526 }
Svet Ganov2af57082015-07-30 08:44:20 -07002527 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002528 }
Svet Ganov2af57082015-07-30 08:44:20 -07002529
2530 Ops ops = uidState.pkgOps.get(packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002531 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002532 if (!edit) {
2533 return null;
2534 }
Jason Monk1c7c3192014-06-26 12:52:18 -04002535 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002536 // This is the first time we have seen this package name under this uid,
2537 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -08002538 if (uid != 0) {
2539 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002540 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -08002541 int pkgUid = -1;
2542 try {
Jason Monk1c7c3192014-06-26 12:52:18 -04002543 ApplicationInfo appInfo = ActivityThread.getPackageManager()
Jeff Sharkeycd654482016-01-08 17:42:11 -07002544 .getApplicationInfo(packageName,
Svet Ganovad0a49b2018-10-29 10:07:08 -07002545 PackageManager.MATCH_DIRECT_BOOT_AWARE
Svet Ganov8455ba22019-01-02 13:05:56 -08002546 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkeycd654482016-01-08 17:42:11 -07002547 UserHandle.getUserId(uid));
Jason Monk1c7c3192014-06-26 12:52:18 -04002548 if (appInfo != null) {
2549 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002550 isPrivileged = (appInfo.privateFlags
2551 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04002552 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08002553 pkgUid = resolveUid(packageName);
2554 if (pkgUid >= 0) {
Chien-Yu Chen75cade02016-01-11 10:56:21 -08002555 isPrivileged = false;
Jason Monk1c7c3192014-06-26 12:52:18 -04002556 }
Dianne Hackborn713df152013-05-17 11:27:57 -07002557 }
Jason Monk1c7c3192014-06-26 12:52:18 -04002558 } catch (RemoteException e) {
2559 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08002560 }
2561 if (pkgUid != uid) {
2562 // Oops! The package name is not valid for the uid they are calling
2563 // under. Abort.
Yohei Yukawaa965d652017-10-12 15:02:26 -07002564 if (!uidMismatchExpected) {
2565 RuntimeException ex = new RuntimeException("here");
2566 ex.fillInStackTrace();
2567 Slog.w(TAG, "Bad call: specified package " + packageName
2568 + " under uid " + uid + " but it is really " + pkgUid, ex);
2569 }
Dianne Hackborn514074f2013-02-11 10:52:46 -08002570 return null;
2571 }
2572 } finally {
2573 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002574 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002575 }
Svet Ganov2af57082015-07-30 08:44:20 -07002576 ops = new Ops(packageName, uidState, isPrivileged);
2577 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002578 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08002579 return ops;
2580 }
2581
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07002582 /**
2583 * Get the state of all ops for a package, <b>don't verify that package belongs to uid</b>.
2584 *
2585 * <p>Usually callers should use {@link #getOpLocked} and not call this directly.
2586 *
2587 * @param uid The uid the of the package
2588 * @param packageName The package name for which to get the state for
2589 * @param edit Iff {@code true} create the {@link Ops} object if not yet created
2590 * @param isPrivileged Whether the package is privileged or not
2591 *
2592 * @return The {@link Ops state} of all ops for the package
2593 */
2594 private @Nullable Ops getOpsRawNoVerifyLocked(int uid, @NonNull String packageName,
2595 boolean edit, boolean isPrivileged) {
2596 UidState uidState = getUidStateLocked(uid, edit);
2597 if (uidState == null) {
2598 return null;
2599 }
2600
2601 if (uidState.pkgOps == null) {
2602 if (!edit) {
2603 return null;
2604 }
2605 uidState.pkgOps = new ArrayMap<>();
2606 }
2607
2608 Ops ops = uidState.pkgOps.get(packageName);
2609 if (ops == null) {
2610 if (!edit) {
2611 return null;
2612 }
2613 ops = new Ops(packageName, uidState, isPrivileged);
2614 uidState.pkgOps.put(packageName, ops);
2615 }
2616 return ops;
2617 }
2618
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002619 private void scheduleWriteLocked() {
2620 if (!mWriteScheduled) {
2621 mWriteScheduled = true;
2622 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
2623 }
2624 }
2625
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002626 private void scheduleFastWriteLocked() {
2627 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002628 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002629 mFastWriteScheduled = true;
2630 mHandler.removeCallbacks(mWriteRunner);
2631 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002632 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002633 }
2634
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07002635 /**
2636 * Get the state of an op for a uid.
2637 *
2638 * @param code The code of the op
2639 * @param uid The uid the of the package
2640 * @param packageName The package name for which to get the state for
2641 * @param edit Iff {@code true} create the {@link Op} object if not yet created
2642 * @param verifyUid Iff {@code true} check that the package belongs to the uid
2643 * @param isPrivileged Whether the package is privileged or not (only used if {@code verifyUid
2644 * == false})
2645 *
2646 * @return The {@link Op state} of the op
2647 */
2648 private @Nullable Op getOpLocked(int code, int uid, @NonNull String packageName, boolean edit,
2649 boolean verifyUid, boolean isPrivileged) {
2650 Ops ops;
2651
2652 if (verifyUid) {
2653 ops = getOpsRawLocked(uid, packageName, edit, false /* uidMismatchExpected */);
2654 } else {
2655 ops = getOpsRawNoVerifyLocked(uid, packageName, edit, isPrivileged);
2656 }
2657
Dianne Hackborn72e39832013-01-18 18:36:09 -08002658 if (ops == null) {
2659 return null;
2660 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002661 return getOpLocked(ops, code, edit);
2662 }
2663
2664 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002665 Op op = ops.get(code);
2666 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002667 if (!edit) {
2668 return null;
2669 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002670 op = new Op(ops.uidState, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002671 ops.put(code, op);
2672 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002673 if (edit) {
2674 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002675 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002676 return op;
2677 }
2678
Suprabh Shukla873e19f2019-09-16 13:20:22 -07002679 private boolean isOpRestrictedDueToSuspend(int code, String packageName, int uid) {
2680 if (!ArrayUtils.contains(OPS_RESTRICTED_ON_SUSPEND, code)) {
2681 return false;
2682 }
2683 final PackageManagerInternal pmi = LocalServices.getService(PackageManagerInternal.class);
2684 return pmi.isPackageSuspended(packageName, UserHandle.getUserId(uid));
2685 }
2686
Svet Ganov442ed572016-08-17 17:29:43 -07002687 private boolean isOpRestrictedLocked(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04002688 int userHandle = UserHandle.getUserId(uid);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002689 final int restrictionSetCount = mOpUserRestrictions.size();
Ruben Brunk29931bc2016-03-11 00:24:26 -08002690
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002691 for (int i = 0; i < restrictionSetCount; i++) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002692 // For each client, check that the given op is not restricted, or that the given
2693 // package is exempt from the restriction.
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002694 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07002695 if (restrictionState.hasRestriction(code, packageName, userHandle)) {
2696 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
2697 // If we are the system, bypass user restrictions for certain codes
2698 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07002699 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
2700 false /* uidMismatchExpected */);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07002701 if ((ops != null) && ops.isPrivileged) {
2702 return false;
2703 }
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002704 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002705 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002706 return true;
Jason Monk1c7c3192014-06-26 12:52:18 -04002707 }
Jason Monk62062992014-05-06 09:55:28 -04002708 }
2709 return false;
2710 }
2711
Dianne Hackborn35654b62013-01-14 17:38:02 -08002712 void readState() {
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002713 int oldVersion = NO_VERSION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08002714 synchronized (mFile) {
2715 synchronized (this) {
2716 FileInputStream stream;
2717 try {
2718 stream = mFile.openRead();
2719 } catch (FileNotFoundException e) {
2720 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
2721 return;
2722 }
2723 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002724 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002725 try {
2726 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002727 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08002728 int type;
2729 while ((type = parser.next()) != XmlPullParser.START_TAG
2730 && type != XmlPullParser.END_DOCUMENT) {
2731 ;
2732 }
2733
2734 if (type != XmlPullParser.START_TAG) {
2735 throw new IllegalStateException("no start tag found");
2736 }
2737
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002738 final String versionString = parser.getAttributeValue(null, "v");
2739 if (versionString != null) {
2740 oldVersion = Integer.parseInt(versionString);
2741 }
2742
Dianne Hackborn35654b62013-01-14 17:38:02 -08002743 int outerDepth = parser.getDepth();
2744 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2745 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2746 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2747 continue;
2748 }
2749
2750 String tagName = parser.getName();
2751 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00002752 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07002753 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07002754 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002755 } else {
2756 Slog.w(TAG, "Unknown element under <app-ops>: "
2757 + parser.getName());
2758 XmlUtils.skipCurrentTag(parser);
2759 }
2760 }
2761 success = true;
2762 } catch (IllegalStateException e) {
2763 Slog.w(TAG, "Failed parsing " + e);
2764 } catch (NullPointerException e) {
2765 Slog.w(TAG, "Failed parsing " + e);
2766 } catch (NumberFormatException e) {
2767 Slog.w(TAG, "Failed parsing " + e);
2768 } catch (XmlPullParserException e) {
2769 Slog.w(TAG, "Failed parsing " + e);
2770 } catch (IOException e) {
2771 Slog.w(TAG, "Failed parsing " + e);
2772 } catch (IndexOutOfBoundsException e) {
2773 Slog.w(TAG, "Failed parsing " + e);
2774 } finally {
2775 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07002776 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002777 }
2778 try {
2779 stream.close();
2780 } catch (IOException e) {
2781 }
2782 }
2783 }
2784 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002785 synchronized (this) {
2786 upgradeLocked(oldVersion);
2787 }
2788 }
2789
2790 private void upgradeRunAnyInBackgroundLocked() {
2791 for (int i = 0; i < mUidStates.size(); i++) {
2792 final UidState uidState = mUidStates.valueAt(i);
2793 if (uidState == null) {
2794 continue;
2795 }
2796 if (uidState.opModes != null) {
2797 final int idx = uidState.opModes.indexOfKey(AppOpsManager.OP_RUN_IN_BACKGROUND);
2798 if (idx >= 0) {
2799 uidState.opModes.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND,
Svet Ganovaf189e32019-02-15 18:45:29 -08002800 uidState.opModes.valueAt(idx));
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002801 }
2802 }
2803 if (uidState.pkgOps == null) {
2804 continue;
2805 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002806 boolean changed = false;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002807 for (int j = 0; j < uidState.pkgOps.size(); j++) {
2808 Ops ops = uidState.pkgOps.valueAt(j);
2809 if (ops != null) {
2810 final Op op = ops.get(AppOpsManager.OP_RUN_IN_BACKGROUND);
2811 if (op != null && op.mode != AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002812 final Op copy = new Op(op.uidState, op.packageName,
Svet Ganovaf189e32019-02-15 18:45:29 -08002813 AppOpsManager.OP_RUN_ANY_IN_BACKGROUND);
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002814 copy.mode = op.mode;
2815 ops.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, copy);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002816 changed = true;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002817 }
2818 }
2819 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002820 if (changed) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002821 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002822 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002823 }
2824 }
2825
2826 private void upgradeLocked(int oldVersion) {
2827 if (oldVersion >= CURRENT_VERSION) {
2828 return;
2829 }
2830 Slog.d(TAG, "Upgrading app-ops xml from version " + oldVersion + " to " + CURRENT_VERSION);
2831 switch (oldVersion) {
2832 case NO_VERSION:
2833 upgradeRunAnyInBackgroundLocked();
2834 // fall through
2835 case 1:
2836 // for future upgrades
2837 }
2838 scheduleFastWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002839 }
2840
Svet Ganovaf189e32019-02-15 18:45:29 -08002841 private void readUidOps(XmlPullParser parser) throws NumberFormatException,
Svet Ganov2af57082015-07-30 08:44:20 -07002842 XmlPullParserException, IOException {
2843 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
2844 int outerDepth = parser.getDepth();
2845 int type;
2846 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2847 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2848 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2849 continue;
2850 }
2851
2852 String tagName = parser.getName();
2853 if (tagName.equals("op")) {
2854 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
2855 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
2856 UidState uidState = getUidStateLocked(uid, true);
2857 if (uidState.opModes == null) {
2858 uidState.opModes = new SparseIntArray();
2859 }
2860 uidState.opModes.put(code, mode);
2861 } else {
2862 Slog.w(TAG, "Unknown element under <uid-ops>: "
2863 + parser.getName());
2864 XmlUtils.skipCurrentTag(parser);
2865 }
2866 }
2867 }
2868
Svet Ganovaf189e32019-02-15 18:45:29 -08002869 private void readPackage(XmlPullParser parser)
2870 throws NumberFormatException, XmlPullParserException, IOException {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002871 String pkgName = parser.getAttributeValue(null, "n");
2872 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 }
2879
2880 String tagName = parser.getName();
2881 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00002882 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002883 } else {
2884 Slog.w(TAG, "Unknown element under <pkg>: "
2885 + parser.getName());
2886 XmlUtils.skipCurrentTag(parser);
2887 }
2888 }
2889 }
2890
Svet Ganovaf189e32019-02-15 18:45:29 -08002891 private void readUid(XmlPullParser parser, String pkgName)
2892 throws NumberFormatException, XmlPullParserException, IOException {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002893 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Svet Ganovaf189e32019-02-15 18:45:29 -08002894 final UidState uidState = getUidStateLocked(uid, true);
Jason Monk1c7c3192014-06-26 12:52:18 -04002895 String isPrivilegedString = parser.getAttributeValue(null, "p");
2896 boolean isPrivileged = false;
2897 if (isPrivilegedString == null) {
2898 try {
2899 IPackageManager packageManager = ActivityThread.getPackageManager();
2900 if (packageManager != null) {
2901 ApplicationInfo appInfo = ActivityThread.getPackageManager()
2902 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
2903 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002904 isPrivileged = (appInfo.privateFlags
2905 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04002906 }
2907 } else {
2908 // Could not load data, don't add to cache so it will be loaded later.
2909 return;
2910 }
2911 } catch (RemoteException e) {
2912 Slog.w(TAG, "Could not contact PackageManager", e);
2913 }
2914 } else {
2915 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
2916 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002917 int outerDepth = parser.getDepth();
2918 int type;
2919 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2920 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2921 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2922 continue;
2923 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002924 String tagName = parser.getName();
2925 if (tagName.equals("op")) {
Svet Ganovaf189e32019-02-15 18:45:29 -08002926 readOp(parser, uidState, pkgName, isPrivileged);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002927 } else {
2928 Slog.w(TAG, "Unknown element under <pkg>: "
2929 + parser.getName());
2930 XmlUtils.skipCurrentTag(parser);
2931 }
2932 }
Svet Ganovaf189e32019-02-15 18:45:29 -08002933 uidState.evalForegroundOps(mOpModeWatchers);
2934 }
2935
2936 private void readOp(XmlPullParser parser, @NonNull UidState uidState,
2937 @NonNull String pkgName, boolean isPrivileged) throws NumberFormatException,
2938 XmlPullParserException, IOException {
2939 Op op = new Op(uidState, pkgName,
2940 Integer.parseInt(parser.getAttributeValue(null, "n")));
2941
2942 final int mode = XmlUtils.readIntAttribute(parser, "m",
2943 AppOpsManager.opToDefaultMode(op.op));
2944 op.mode = mode;
2945
2946 int outerDepth = parser.getDepth();
2947 int type;
2948 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2949 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2950 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2951 continue;
2952 }
2953 String tagName = parser.getName();
2954 if (tagName.equals("st")) {
2955 final long key = XmlUtils.readLongAttribute(parser, "n");
2956
2957 final int flags = AppOpsManager.extractFlagsFromKey(key);
2958 final int state = AppOpsManager.extractUidStateFromKey(key);
2959
2960 final long accessTime = XmlUtils.readLongAttribute(parser, "t", 0);
2961 final long rejectTime = XmlUtils.readLongAttribute(parser, "r", 0);
2962 final long accessDuration = XmlUtils.readLongAttribute(parser, "d", 0);
2963 final String proxyPkg = XmlUtils.readStringAttribute(parser, "pp");
2964 final int proxyUid = XmlUtils.readIntAttribute(parser, "pu", 0);
2965
2966 if (accessTime > 0) {
2967 op.accessed(accessTime, proxyUid, proxyPkg, state, flags);
2968 }
2969 if (rejectTime > 0) {
2970 op.rejected(rejectTime, proxyUid, proxyPkg, state, flags);
2971 }
2972 if (accessDuration > 0) {
2973 op.running(accessTime, accessDuration, state, flags);
2974 }
2975 } else {
2976 Slog.w(TAG, "Unknown element under <op>: "
2977 + parser.getName());
2978 XmlUtils.skipCurrentTag(parser);
2979 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002980 }
Svet Ganovaf189e32019-02-15 18:45:29 -08002981
2982 if (uidState.pkgOps == null) {
2983 uidState.pkgOps = new ArrayMap<>();
2984 }
2985 Ops ops = uidState.pkgOps.get(pkgName);
2986 if (ops == null) {
2987 ops = new Ops(pkgName, uidState, isPrivileged);
2988 uidState.pkgOps.put(pkgName, ops);
2989 }
2990 ops.put(op.op, op);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002991 }
2992
2993 void writeState() {
2994 synchronized (mFile) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002995 FileOutputStream stream;
2996 try {
2997 stream = mFile.startWrite();
2998 } catch (IOException e) {
2999 Slog.w(TAG, "Failed to write state: " + e);
3000 return;
3001 }
3002
Dianne Hackborne17b4452018-01-10 13:15:40 -08003003 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
3004
Dianne Hackborn35654b62013-01-14 17:38:02 -08003005 try {
3006 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003007 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08003008 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003009 out.startTag(null, "app-ops");
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07003010 out.attribute(null, "v", String.valueOf(CURRENT_VERSION));
Svet Ganov2af57082015-07-30 08:44:20 -07003011
Eugene Susla3454f3e2019-08-28 14:28:32 -07003012 SparseArray<SparseIntArray> uidStatesClone;
3013 synchronized (this) {
3014 uidStatesClone = new SparseArray<>(mUidStates.size());
3015
3016 final int uidStateCount = mUidStates.size();
3017 for (int uidStateNum = 0; uidStateNum < uidStateCount; uidStateNum++) {
3018 UidState uidState = mUidStates.valueAt(uidStateNum);
3019 int uid = mUidStates.keyAt(uidStateNum);
3020
3021 SparseIntArray opModes = uidState.opModes;
3022 if (opModes != null && opModes.size() > 0) {
3023 uidStatesClone.put(uid, new SparseIntArray(opModes.size()));
3024
3025 final int opCount = opModes.size();
3026 for (int opCountNum = 0; opCountNum < opCount; opCountNum++) {
3027 uidStatesClone.get(uid).put(
3028 opModes.keyAt(opCountNum),
3029 opModes.valueAt(opCountNum));
3030 }
3031 }
3032 }
3033 }
3034
3035 final int uidStateCount = uidStatesClone.size();
3036 for (int uidStateNum = 0; uidStateNum < uidStateCount; uidStateNum++) {
3037 SparseIntArray opModes = uidStatesClone.valueAt(uidStateNum);
3038 if (opModes != null && opModes.size() > 0) {
Svet Ganov2af57082015-07-30 08:44:20 -07003039 out.startTag(null, "uid");
Eugene Susla3454f3e2019-08-28 14:28:32 -07003040 out.attribute(null, "n",
3041 Integer.toString(uidStatesClone.keyAt(uidStateNum)));
3042 final int opCount = opModes.size();
3043 for (int opCountNum = 0; opCountNum < opCount; opCountNum++) {
3044 final int op = opModes.keyAt(opCountNum);
3045 final int mode = opModes.valueAt(opCountNum);
Svet Ganov2af57082015-07-30 08:44:20 -07003046 out.startTag(null, "op");
3047 out.attribute(null, "n", Integer.toString(op));
3048 out.attribute(null, "m", Integer.toString(mode));
3049 out.endTag(null, "op");
3050 }
3051 out.endTag(null, "uid");
3052 }
3053 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08003054
3055 if (allOps != null) {
3056 String lastPkg = null;
3057 for (int i=0; i<allOps.size(); i++) {
3058 AppOpsManager.PackageOps pkg = allOps.get(i);
3059 if (!pkg.getPackageName().equals(lastPkg)) {
3060 if (lastPkg != null) {
3061 out.endTag(null, "pkg");
3062 }
3063 lastPkg = pkg.getPackageName();
3064 out.startTag(null, "pkg");
3065 out.attribute(null, "n", lastPkg);
3066 }
3067 out.startTag(null, "uid");
3068 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04003069 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07003070 Ops ops = getOpsRawLocked(pkg.getUid(), pkg.getPackageName(),
3071 false /* edit */, false /* uidMismatchExpected */);
Jason Monk1c7c3192014-06-26 12:52:18 -04003072 // Should always be present as the list of PackageOps is generated
3073 // from Ops.
3074 if (ops != null) {
3075 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
3076 } else {
3077 out.attribute(null, "p", Boolean.toString(false));
3078 }
3079 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08003080 List<AppOpsManager.OpEntry> ops = pkg.getOps();
3081 for (int j=0; j<ops.size(); j++) {
3082 AppOpsManager.OpEntry op = ops.get(j);
3083 out.startTag(null, "op");
3084 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07003085 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003086 out.attribute(null, "m", Integer.toString(op.getMode()));
3087 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003088
3089 final LongSparseArray keys = op.collectKeys();
3090 if (keys == null || keys.size() <= 0) {
Svet Ganov8e5bf962019-03-19 23:59:03 -07003091 out.endTag(null, "op");
Svet Ganovaf189e32019-02-15 18:45:29 -08003092 continue;
3093 }
3094
3095 final int keyCount = keys.size();
3096 for (int k = 0; k < keyCount; k++) {
3097 final long key = keys.keyAt(k);
3098
3099 final int uidState = AppOpsManager.extractUidStateFromKey(key);
3100 final int flags = AppOpsManager.extractFlagsFromKey(key);
3101
3102 final long accessTime = op.getLastAccessTime(
3103 uidState, uidState, flags);
3104 final long rejectTime = op.getLastRejectTime(
3105 uidState, uidState, flags);
3106 final long accessDuration = op.getLastDuration(
3107 uidState, uidState, flags);
3108 final String proxyPkg = op.getProxyPackageName(uidState, flags);
3109 final int proxyUid = op.getProxyUid(uidState, flags);
3110
3111 if (accessTime <= 0 && rejectTime <= 0 && accessDuration <= 0
3112 && proxyPkg == null && proxyUid < 0) {
3113 continue;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003114 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003115
3116 out.startTag(null, "st");
3117 out.attribute(null, "n", Long.toString(key));
3118 if (accessTime > 0) {
3119 out.attribute(null, "t", Long.toString(accessTime));
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003120 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003121 if (rejectTime > 0) {
3122 out.attribute(null, "r", Long.toString(rejectTime));
3123 }
3124 if (accessDuration > 0) {
3125 out.attribute(null, "d", Long.toString(accessDuration));
3126 }
3127 if (proxyPkg != null) {
3128 out.attribute(null, "pp", proxyPkg);
3129 }
3130 if (proxyUid >= 0) {
3131 out.attribute(null, "pu", Integer.toString(proxyUid));
3132 }
3133 out.endTag(null, "st");
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003134 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003135
Dianne Hackborn35654b62013-01-14 17:38:02 -08003136 out.endTag(null, "op");
3137 }
3138 out.endTag(null, "uid");
3139 }
3140 if (lastPkg != null) {
3141 out.endTag(null, "pkg");
3142 }
3143 }
3144
3145 out.endTag(null, "app-ops");
3146 out.endDocument();
3147 mFile.finishWrite(stream);
3148 } catch (IOException e) {
3149 Slog.w(TAG, "Failed to write state, restoring backup.", e);
3150 mFile.failWrite(stream);
3151 }
3152 }
3153 }
3154
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003155 static class Shell extends ShellCommand {
3156 final IAppOpsService mInterface;
3157 final AppOpsService mInternal;
3158
3159 int userId = UserHandle.USER_SYSTEM;
3160 String packageName;
3161 String opStr;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003162 String modeStr;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003163 int op;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003164 int mode;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003165 int packageUid;
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003166 int nonpackageUid;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003167 final static Binder sBinder = new Binder();
3168 IBinder mToken;
Svet Ganovd563e932019-04-14 13:07:41 -07003169 boolean targetsUid;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003170
3171 Shell(IAppOpsService iface, AppOpsService internal) {
3172 mInterface = iface;
3173 mInternal = internal;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003174 try {
3175 mToken = mInterface.getToken(sBinder);
3176 } catch (RemoteException e) {
3177 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003178 }
3179
3180 @Override
3181 public int onCommand(String cmd) {
3182 return onShellCommand(this, cmd);
3183 }
3184
3185 @Override
3186 public void onHelp() {
3187 PrintWriter pw = getOutPrintWriter();
3188 dumpCommandHelp(pw);
3189 }
3190
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003191 static private int strOpToOp(String op, PrintWriter err) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003192 try {
3193 return AppOpsManager.strOpToOp(op);
3194 } catch (IllegalArgumentException e) {
3195 }
3196 try {
3197 return Integer.parseInt(op);
3198 } catch (NumberFormatException e) {
3199 }
3200 try {
3201 return AppOpsManager.strDebugOpToOp(op);
3202 } catch (IllegalArgumentException e) {
3203 err.println("Error: " + e.getMessage());
3204 return -1;
3205 }
3206 }
3207
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003208 static int strModeToMode(String modeStr, PrintWriter err) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003209 for (int i = AppOpsManager.MODE_NAMES.length - 1; i >= 0; i--) {
3210 if (AppOpsManager.MODE_NAMES[i].equals(modeStr)) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003211 return i;
3212 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003213 }
3214 try {
3215 return Integer.parseInt(modeStr);
3216 } catch (NumberFormatException e) {
3217 }
3218 err.println("Error: Mode " + modeStr + " is not valid");
3219 return -1;
3220 }
3221
3222 int parseUserOpMode(int defMode, PrintWriter err) throws RemoteException {
3223 userId = UserHandle.USER_CURRENT;
3224 opStr = null;
3225 modeStr = null;
3226 for (String argument; (argument = getNextArg()) != null;) {
3227 if ("--user".equals(argument)) {
3228 userId = UserHandle.parseUserArg(getNextArgRequired());
3229 } else {
3230 if (opStr == null) {
3231 opStr = argument;
3232 } else if (modeStr == null) {
3233 modeStr = argument;
3234 break;
3235 }
3236 }
3237 }
3238 if (opStr == null) {
3239 err.println("Error: Operation not specified.");
3240 return -1;
3241 }
3242 op = strOpToOp(opStr, err);
3243 if (op < 0) {
3244 return -1;
3245 }
3246 if (modeStr != null) {
3247 if ((mode=strModeToMode(modeStr, err)) < 0) {
3248 return -1;
3249 }
3250 } else {
3251 mode = defMode;
3252 }
3253 return 0;
3254 }
3255
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003256 int parseUserPackageOp(boolean reqOp, PrintWriter err) throws RemoteException {
3257 userId = UserHandle.USER_CURRENT;
3258 packageName = null;
3259 opStr = null;
3260 for (String argument; (argument = getNextArg()) != null;) {
3261 if ("--user".equals(argument)) {
3262 userId = UserHandle.parseUserArg(getNextArgRequired());
Svet Ganovd563e932019-04-14 13:07:41 -07003263 } else if ("--uid".equals(argument)) {
3264 targetsUid = true;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003265 } else {
3266 if (packageName == null) {
3267 packageName = argument;
3268 } else if (opStr == null) {
3269 opStr = argument;
3270 break;
3271 }
3272 }
3273 }
3274 if (packageName == null) {
3275 err.println("Error: Package name not specified.");
3276 return -1;
3277 } else if (opStr == null && reqOp) {
3278 err.println("Error: Operation not specified.");
3279 return -1;
3280 }
3281 if (opStr != null) {
3282 op = strOpToOp(opStr, err);
3283 if (op < 0) {
3284 return -1;
3285 }
3286 } else {
3287 op = AppOpsManager.OP_NONE;
3288 }
3289 if (userId == UserHandle.USER_CURRENT) {
3290 userId = ActivityManager.getCurrentUser();
3291 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003292 nonpackageUid = -1;
3293 try {
3294 nonpackageUid = Integer.parseInt(packageName);
3295 } catch (NumberFormatException e) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003296 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003297 if (nonpackageUid == -1 && packageName.length() > 1 && packageName.charAt(0) == 'u'
3298 && packageName.indexOf('.') < 0) {
3299 int i = 1;
3300 while (i < packageName.length() && packageName.charAt(i) >= '0'
3301 && packageName.charAt(i) <= '9') {
3302 i++;
3303 }
3304 if (i > 1 && i < packageName.length()) {
3305 String userStr = packageName.substring(1, i);
3306 try {
3307 int user = Integer.parseInt(userStr);
3308 char type = packageName.charAt(i);
3309 i++;
3310 int startTypeVal = i;
3311 while (i < packageName.length() && packageName.charAt(i) >= '0'
3312 && packageName.charAt(i) <= '9') {
3313 i++;
3314 }
3315 if (i > startTypeVal) {
3316 String typeValStr = packageName.substring(startTypeVal, i);
3317 try {
3318 int typeVal = Integer.parseInt(typeValStr);
3319 if (type == 'a') {
3320 nonpackageUid = UserHandle.getUid(user,
3321 typeVal + Process.FIRST_APPLICATION_UID);
3322 } else if (type == 's') {
3323 nonpackageUid = UserHandle.getUid(user, typeVal);
3324 }
3325 } catch (NumberFormatException e) {
3326 }
3327 }
3328 } catch (NumberFormatException e) {
3329 }
3330 }
3331 }
3332 if (nonpackageUid != -1) {
3333 packageName = null;
3334 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08003335 packageUid = resolveUid(packageName);
3336 if (packageUid < 0) {
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003337 packageUid = AppGlobals.getPackageManager().getPackageUid(packageName,
3338 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
3339 }
3340 if (packageUid < 0) {
3341 err.println("Error: No UID for " + packageName + " in user " + userId);
3342 return -1;
3343 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003344 }
3345 return 0;
3346 }
3347 }
3348
3349 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003350 FileDescriptor err, String[] args, ShellCallback callback,
3351 ResultReceiver resultReceiver) {
3352 (new Shell(this, this)).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003353 }
3354
3355 static void dumpCommandHelp(PrintWriter pw) {
3356 pw.println("AppOps service (appops) commands:");
3357 pw.println(" help");
3358 pw.println(" Print this help text.");
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003359 pw.println(" start [--user <USER_ID>] <PACKAGE | UID> <OP> ");
3360 pw.println(" Starts a given operation for a particular application.");
3361 pw.println(" stop [--user <USER_ID>] <PACKAGE | UID> <OP> ");
3362 pw.println(" Stops a given operation for a particular application.");
Svet Ganovb687fad2019-04-30 17:32:44 -07003363 pw.println(" set [--user <USER_ID>] <[--uid] PACKAGE | UID> <OP> <MODE>");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003364 pw.println(" Set the mode for a particular application and operation.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003365 pw.println(" get [--user <USER_ID>] <PACKAGE | UID> [<OP>]");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003366 pw.println(" Return the mode for a particular application and optional operation.");
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003367 pw.println(" query-op [--user <USER_ID>] <OP> [<MODE>]");
3368 pw.println(" Print all packages that currently have the given op in the given mode.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003369 pw.println(" reset [--user <USER_ID>] [<PACKAGE>]");
3370 pw.println(" Reset the given application or all applications to default modes.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003371 pw.println(" write-settings");
3372 pw.println(" Immediately write pending changes to storage.");
3373 pw.println(" read-settings");
3374 pw.println(" Read the last written settings, replacing current state in RAM.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003375 pw.println(" options:");
Svet Ganovb687fad2019-04-30 17:32:44 -07003376 pw.println(" <PACKAGE> an Android package name or its UID if prefixed by --uid");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003377 pw.println(" <OP> an AppOps operation.");
3378 pw.println(" <MODE> one of allow, ignore, deny, or default");
3379 pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
3380 pw.println(" specified, the current user is assumed.");
3381 }
3382
3383 static int onShellCommand(Shell shell, String cmd) {
3384 if (cmd == null) {
3385 return shell.handleDefaultCommands(cmd);
3386 }
3387 PrintWriter pw = shell.getOutPrintWriter();
3388 PrintWriter err = shell.getErrPrintWriter();
3389 try {
3390 switch (cmd) {
3391 case "set": {
3392 int res = shell.parseUserPackageOp(true, err);
3393 if (res < 0) {
3394 return res;
3395 }
3396 String modeStr = shell.getNextArg();
3397 if (modeStr == null) {
3398 err.println("Error: Mode not specified.");
3399 return -1;
3400 }
3401
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003402 final int mode = shell.strModeToMode(modeStr, err);
3403 if (mode < 0) {
3404 return -1;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003405 }
3406
Svet Ganovd563e932019-04-14 13:07:41 -07003407 if (!shell.targetsUid && shell.packageName != null) {
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003408 shell.mInterface.setMode(shell.op, shell.packageUid, shell.packageName,
3409 mode);
Svet Ganovd563e932019-04-14 13:07:41 -07003410 } else if (shell.targetsUid && shell.packageName != null) {
3411 try {
3412 final int uid = shell.mInternal.mContext.getPackageManager()
3413 .getPackageUid(shell.packageName, shell.userId);
3414 shell.mInterface.setUidMode(shell.op, uid, mode);
3415 } catch (PackageManager.NameNotFoundException e) {
3416 return -1;
3417 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003418 } else {
3419 shell.mInterface.setUidMode(shell.op, shell.nonpackageUid, mode);
3420 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003421 return 0;
3422 }
3423 case "get": {
3424 int res = shell.parseUserPackageOp(false, err);
3425 if (res < 0) {
3426 return res;
3427 }
3428
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003429 List<AppOpsManager.PackageOps> ops = new ArrayList<>();
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003430 if (shell.packageName != null) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003431 // Uid mode overrides package mode, so make sure it's also reported
3432 List<AppOpsManager.PackageOps> r = shell.mInterface.getUidOps(
3433 shell.packageUid,
3434 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
3435 if (r != null) {
3436 ops.addAll(r);
3437 }
3438 r = shell.mInterface.getOpsForPackage(
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003439 shell.packageUid, shell.packageName,
3440 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003441 if (r != null) {
3442 ops.addAll(r);
3443 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003444 } else {
3445 ops = shell.mInterface.getUidOps(
3446 shell.nonpackageUid,
3447 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
3448 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003449 if (ops == null || ops.size() <= 0) {
3450 pw.println("No operations.");
Svet Ganov82f09bc2018-01-12 22:08:40 -08003451 if (shell.op > AppOpsManager.OP_NONE && shell.op < AppOpsManager._NUM_OP) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003452 pw.println("Default mode: " + AppOpsManager.modeToName(
Svet Ganov82f09bc2018-01-12 22:08:40 -08003453 AppOpsManager.opToDefaultMode(shell.op)));
3454 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003455 return 0;
3456 }
3457 final long now = System.currentTimeMillis();
3458 for (int i=0; i<ops.size(); i++) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003459 AppOpsManager.PackageOps packageOps = ops.get(i);
3460 if (packageOps.getPackageName() == null) {
3461 pw.print("Uid mode: ");
3462 }
3463 List<AppOpsManager.OpEntry> entries = packageOps.getOps();
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003464 for (int j=0; j<entries.size(); j++) {
3465 AppOpsManager.OpEntry ent = entries.get(j);
3466 pw.print(AppOpsManager.opToName(ent.getOp()));
3467 pw.print(": ");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003468 pw.print(AppOpsManager.modeToName(ent.getMode()));
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003469 if (ent.getTime() != 0) {
3470 pw.print("; time=");
3471 TimeUtils.formatDuration(now - ent.getTime(), pw);
3472 pw.print(" ago");
3473 }
3474 if (ent.getRejectTime() != 0) {
3475 pw.print("; rejectTime=");
3476 TimeUtils.formatDuration(now - ent.getRejectTime(), pw);
3477 pw.print(" ago");
3478 }
3479 if (ent.getDuration() == -1) {
3480 pw.print(" (running)");
3481 } else if (ent.getDuration() != 0) {
3482 pw.print("; duration=");
3483 TimeUtils.formatDuration(ent.getDuration(), pw);
3484 }
3485 pw.println();
3486 }
3487 }
3488 return 0;
3489 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003490 case "query-op": {
3491 int res = shell.parseUserOpMode(AppOpsManager.MODE_IGNORED, err);
3492 if (res < 0) {
3493 return res;
3494 }
3495 List<AppOpsManager.PackageOps> ops = shell.mInterface.getPackagesForOps(
3496 new int[] {shell.op});
3497 if (ops == null || ops.size() <= 0) {
3498 pw.println("No operations.");
3499 return 0;
3500 }
3501 for (int i=0; i<ops.size(); i++) {
3502 final AppOpsManager.PackageOps pkg = ops.get(i);
3503 boolean hasMatch = false;
3504 final List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
3505 for (int j=0; j<entries.size(); j++) {
3506 AppOpsManager.OpEntry ent = entries.get(j);
3507 if (ent.getOp() == shell.op && ent.getMode() == shell.mode) {
3508 hasMatch = true;
3509 break;
3510 }
3511 }
3512 if (hasMatch) {
3513 pw.println(pkg.getPackageName());
3514 }
3515 }
3516 return 0;
3517 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003518 case "reset": {
3519 String packageName = null;
3520 int userId = UserHandle.USER_CURRENT;
3521 for (String argument; (argument = shell.getNextArg()) != null;) {
3522 if ("--user".equals(argument)) {
3523 String userStr = shell.getNextArgRequired();
3524 userId = UserHandle.parseUserArg(userStr);
3525 } else {
3526 if (packageName == null) {
3527 packageName = argument;
3528 } else {
3529 err.println("Error: Unsupported argument: " + argument);
3530 return -1;
3531 }
3532 }
3533 }
3534
3535 if (userId == UserHandle.USER_CURRENT) {
3536 userId = ActivityManager.getCurrentUser();
3537 }
3538
3539 shell.mInterface.resetAllModes(userId, packageName);
3540 pw.print("Reset all modes for: ");
3541 if (userId == UserHandle.USER_ALL) {
3542 pw.print("all users");
3543 } else {
3544 pw.print("user "); pw.print(userId);
3545 }
3546 pw.print(", ");
3547 if (packageName == null) {
3548 pw.println("all packages");
3549 } else {
3550 pw.print("package "); pw.println(packageName);
3551 }
3552 return 0;
3553 }
3554 case "write-settings": {
Dianne Hackbornd5254412018-05-11 18:02:58 -07003555 shell.mInternal.enforceManageAppOpsModes(Binder.getCallingPid(),
3556 Binder.getCallingUid(), -1);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003557 long token = Binder.clearCallingIdentity();
3558 try {
3559 synchronized (shell.mInternal) {
3560 shell.mInternal.mHandler.removeCallbacks(shell.mInternal.mWriteRunner);
3561 }
3562 shell.mInternal.writeState();
3563 pw.println("Current settings written.");
3564 } finally {
3565 Binder.restoreCallingIdentity(token);
3566 }
3567 return 0;
3568 }
3569 case "read-settings": {
Dianne Hackbornd5254412018-05-11 18:02:58 -07003570 shell.mInternal.enforceManageAppOpsModes(Binder.getCallingPid(),
3571 Binder.getCallingUid(), -1);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003572 long token = Binder.clearCallingIdentity();
3573 try {
3574 shell.mInternal.readState();
3575 pw.println("Last settings read.");
3576 } finally {
3577 Binder.restoreCallingIdentity(token);
3578 }
3579 return 0;
3580 }
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003581 case "start": {
3582 int res = shell.parseUserPackageOp(true, err);
3583 if (res < 0) {
3584 return res;
3585 }
3586
3587 if (shell.packageName != null) {
3588 shell.mInterface.startOperation(shell.mToken,
3589 shell.op, shell.packageUid, shell.packageName, true);
3590 } else {
3591 return -1;
3592 }
3593 return 0;
3594 }
3595 case "stop": {
3596 int res = shell.parseUserPackageOp(true, err);
3597 if (res < 0) {
3598 return res;
3599 }
3600
3601 if (shell.packageName != null) {
3602 shell.mInterface.finishOperation(shell.mToken,
3603 shell.op, shell.packageUid, shell.packageName);
3604 } else {
3605 return -1;
3606 }
3607 return 0;
3608 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003609 default:
3610 return shell.handleDefaultCommands(cmd);
3611 }
3612 } catch (RemoteException e) {
3613 pw.println("Remote exception: " + e);
3614 }
3615 return -1;
3616 }
3617
3618 private void dumpHelp(PrintWriter pw) {
3619 pw.println("AppOps service (appops) dump options:");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003620 pw.println(" -h");
3621 pw.println(" Print this help text.");
3622 pw.println(" --op [OP]");
3623 pw.println(" Limit output to data associated with the given app op code.");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003624 pw.println(" --mode [MODE]");
3625 pw.println(" Limit output to data associated with the given app op mode.");
3626 pw.println(" --package [PACKAGE]");
3627 pw.println(" Limit output to data associated with the given package name.");
Dianne Hackborn125dc532019-01-09 13:31:48 -08003628 pw.println(" --watchers");
3629 pw.println(" Only output the watcher sections.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003630 }
3631
Svet Ganovaf189e32019-02-15 18:45:29 -08003632 private void dumpStatesLocked(@NonNull PrintWriter pw, @NonNull Op op,
3633 long now, @NonNull SimpleDateFormat sdf, @NonNull Date date, @NonNull String prefix) {
3634
3635 final OpEntry entry = new OpEntry(op.op, op.running, op.mode, op.mAccessTimes,
3636 op.mRejectTimes, op.mDurations, op.mProxyUids, op.mProxyPackageNames);
3637
3638 final LongSparseArray keys = entry.collectKeys();
3639 if (keys == null || keys.size() <= 0) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003640 return;
3641 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003642
3643 final int keyCount = keys.size();
3644 for (int k = 0; k < keyCount; k++) {
3645 final long key = keys.keyAt(k);
3646
3647 final int uidState = AppOpsManager.extractUidStateFromKey(key);
3648 final int flags = AppOpsManager.extractFlagsFromKey(key);
3649
3650 final long accessTime = entry.getLastAccessTime(
3651 uidState, uidState, flags);
3652 final long rejectTime = entry.getLastRejectTime(
3653 uidState, uidState, flags);
3654 final long accessDuration = entry.getLastDuration(
3655 uidState, uidState, flags);
3656 final String proxyPkg = entry.getProxyPackageName(uidState, flags);
3657 final int proxyUid = entry.getProxyUid(uidState, flags);
3658
3659 if (accessTime > 0) {
3660 pw.print(prefix);
3661 pw.print("Access: ");
3662 pw.print(AppOpsManager.keyToString(key));
3663 pw.print(" ");
3664 date.setTime(accessTime);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003665 pw.print(sdf.format(date));
3666 pw.print(" (");
Svet Ganovaf189e32019-02-15 18:45:29 -08003667 TimeUtils.formatDuration(accessTime - now, pw);
3668 pw.print(")");
3669 if (accessDuration > 0) {
3670 pw.print(" duration=");
3671 TimeUtils.formatDuration(accessDuration, pw);
3672 }
3673 if (proxyUid >= 0) {
3674 pw.print(" proxy[");
3675 pw.print("uid=");
3676 pw.print(proxyUid);
3677 pw.print(", pkg=");
3678 pw.print(proxyPkg);
3679 pw.print("]");
3680 }
3681 pw.println();
3682 }
3683
3684 if (rejectTime > 0) {
3685 pw.print(prefix);
3686 pw.print("Reject: ");
3687 pw.print(AppOpsManager.keyToString(key));
3688 date.setTime(rejectTime);
3689 pw.print(sdf.format(date));
3690 pw.print(" (");
3691 TimeUtils.formatDuration(rejectTime - now, pw);
3692 pw.print(")");
3693 if (proxyUid >= 0) {
3694 pw.print(" proxy[");
3695 pw.print("uid=");
3696 pw.print(proxyUid);
3697 pw.print(", pkg=");
3698 pw.print(proxyPkg);
3699 pw.print("]");
3700 }
3701 pw.println();
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003702 }
3703 }
3704 }
3705
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003706 @Override
3707 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06003708 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003709
Svet Ganov8455ba22019-01-02 13:05:56 -08003710 int dumpOp = OP_NONE;
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003711 String dumpPackage = null;
Svet Ganov8455ba22019-01-02 13:05:56 -08003712 int dumpUid = Process.INVALID_UID;
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003713 int dumpMode = -1;
Dianne Hackborn125dc532019-01-09 13:31:48 -08003714 boolean dumpWatchers = false;
Svet Ganovaf189e32019-02-15 18:45:29 -08003715 boolean dumpHistory = false;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003716
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003717 if (args != null) {
3718 for (int i=0; i<args.length; i++) {
3719 String arg = args[i];
3720 if ("-h".equals(arg)) {
3721 dumpHelp(pw);
3722 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07003723 } else if ("-a".equals(arg)) {
3724 // dump all data
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003725 } else if ("--op".equals(arg)) {
3726 i++;
3727 if (i >= args.length) {
3728 pw.println("No argument for --op option");
3729 return;
3730 }
3731 dumpOp = Shell.strOpToOp(args[i], pw);
3732 if (dumpOp < 0) {
3733 return;
3734 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003735 } else if ("--package".equals(arg)) {
3736 i++;
3737 if (i >= args.length) {
3738 pw.println("No argument for --package option");
3739 return;
3740 }
3741 dumpPackage = args[i];
3742 try {
3743 dumpUid = AppGlobals.getPackageManager().getPackageUid(dumpPackage,
3744 PackageManager.MATCH_KNOWN_PACKAGES | PackageManager.MATCH_INSTANT,
3745 0);
3746 } catch (RemoteException e) {
3747 }
3748 if (dumpUid < 0) {
3749 pw.println("Unknown package: " + dumpPackage);
3750 return;
3751 }
3752 dumpUid = UserHandle.getAppId(dumpUid);
3753 } else if ("--mode".equals(arg)) {
3754 i++;
3755 if (i >= args.length) {
3756 pw.println("No argument for --mode option");
3757 return;
3758 }
3759 dumpMode = Shell.strModeToMode(args[i], pw);
3760 if (dumpMode < 0) {
3761 return;
3762 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08003763 } else if ("--watchers".equals(arg)) {
3764 dumpWatchers = true;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003765 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
3766 pw.println("Unknown option: " + arg);
3767 return;
3768 } else {
3769 pw.println("Unknown command: " + arg);
3770 return;
3771 }
3772 }
3773 }
3774
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003775 synchronized (this) {
3776 pw.println("Current AppOps Service state:");
Svet Ganovaf189e32019-02-15 18:45:29 -08003777 if (!dumpHistory && !dumpWatchers) {
3778 mConstants.dump(pw);
3779 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003780 pw.println();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003781 final long now = System.currentTimeMillis();
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003782 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003783 final long nowUptime = SystemClock.uptimeMillis();
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003784 final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
3785 final Date date = new Date();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003786 boolean needSep = false;
Dianne Hackborn125dc532019-01-09 13:31:48 -08003787 if (dumpOp < 0 && dumpMode < 0 && dumpPackage == null && mProfileOwners != null
Svet Ganovaf189e32019-02-15 18:45:29 -08003788 && !dumpWatchers && !dumpHistory) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07003789 pw.println(" Profile owners:");
3790 for (int poi = 0; poi < mProfileOwners.size(); poi++) {
3791 pw.print(" User #");
3792 pw.print(mProfileOwners.keyAt(poi));
3793 pw.print(": ");
3794 UserHandle.formatUid(pw, mProfileOwners.valueAt(poi));
3795 pw.println();
3796 }
3797 pw.println();
3798 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003799 if (mOpModeWatchers.size() > 0 && !dumpHistory) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003800 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003801 for (int i=0; i<mOpModeWatchers.size(); i++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003802 if (dumpOp >= 0 && dumpOp != mOpModeWatchers.keyAt(i)) {
3803 continue;
3804 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003805 boolean printedOpHeader = false;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003806 ArraySet<ModeCallback> callbacks = mOpModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003807 for (int j=0; j<callbacks.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003808 final ModeCallback cb = callbacks.valueAt(j);
Dianne Hackborn125dc532019-01-09 13:31:48 -08003809 if (dumpPackage != null
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003810 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3811 continue;
3812 }
3813 needSep = true;
3814 if (!printedHeader) {
3815 pw.println(" Op mode watchers:");
3816 printedHeader = true;
3817 }
3818 if (!printedOpHeader) {
3819 pw.print(" Op ");
3820 pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
3821 pw.println(":");
3822 printedOpHeader = true;
3823 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003824 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003825 pw.println(cb);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003826 }
3827 }
3828 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003829 if (mPackageModeWatchers.size() > 0 && dumpOp < 0 && !dumpHistory) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003830 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003831 for (int i=0; i<mPackageModeWatchers.size(); i++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003832 if (dumpPackage != null && !dumpPackage.equals(mPackageModeWatchers.keyAt(i))) {
3833 continue;
3834 }
3835 needSep = true;
3836 if (!printedHeader) {
3837 pw.println(" Package mode watchers:");
3838 printedHeader = true;
3839 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003840 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
3841 pw.println(":");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003842 ArraySet<ModeCallback> callbacks = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003843 for (int j=0; j<callbacks.size(); j++) {
3844 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08003845 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003846 }
3847 }
3848 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003849 if (mModeWatchers.size() > 0 && dumpOp < 0 && !dumpHistory) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003850 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003851 for (int i=0; i<mModeWatchers.size(); i++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003852 final ModeCallback cb = mModeWatchers.valueAt(i);
Dianne Hackborn125dc532019-01-09 13:31:48 -08003853 if (dumpPackage != null
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003854 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3855 continue;
3856 }
3857 needSep = true;
3858 if (!printedHeader) {
3859 pw.println(" All op mode watchers:");
3860 printedHeader = true;
3861 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003862 pw.print(" ");
3863 pw.print(Integer.toHexString(System.identityHashCode(mModeWatchers.keyAt(i))));
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003864 pw.print(": "); pw.println(cb);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003865 }
3866 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003867 if (mActiveWatchers.size() > 0 && dumpMode < 0) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003868 needSep = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003869 boolean printedHeader = false;
Philip P. Moltmannba136462019-05-21 10:20:38 -07003870 for (int watcherNum = 0; watcherNum < mActiveWatchers.size(); watcherNum++) {
3871 final SparseArray<ActiveCallback> activeWatchers =
3872 mActiveWatchers.valueAt(watcherNum);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003873 if (activeWatchers.size() <= 0) {
3874 continue;
3875 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003876 final ActiveCallback cb = activeWatchers.valueAt(0);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003877 if (dumpOp >= 0 && activeWatchers.indexOfKey(dumpOp) < 0) {
3878 continue;
3879 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08003880 if (dumpPackage != null
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003881 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3882 continue;
3883 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003884 if (!printedHeader) {
3885 pw.println(" All op active watchers:");
3886 printedHeader = true;
3887 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003888 pw.print(" ");
3889 pw.print(Integer.toHexString(System.identityHashCode(
Philip P. Moltmannba136462019-05-21 10:20:38 -07003890 mActiveWatchers.keyAt(watcherNum))));
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003891 pw.println(" ->");
3892 pw.print(" [");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003893 final int opCount = activeWatchers.size();
Philip P. Moltmannba136462019-05-21 10:20:38 -07003894 for (int opNum = 0; opNum < opCount; opNum++) {
3895 if (opNum > 0) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003896 pw.print(' ');
3897 }
Philip P. Moltmannba136462019-05-21 10:20:38 -07003898 pw.print(AppOpsManager.opToName(activeWatchers.keyAt(opNum)));
3899 if (opNum < opCount - 1) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003900 pw.print(',');
3901 }
3902 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003903 pw.println("]");
3904 pw.print(" ");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003905 pw.println(cb);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003906 }
3907 }
Svet Ganovb3d2ae22018-12-17 22:06:15 -08003908 if (mNotedWatchers.size() > 0 && dumpMode < 0) {
3909 needSep = true;
3910 boolean printedHeader = false;
3911 for (int i = 0; i < mNotedWatchers.size(); i++) {
3912 final SparseArray<NotedCallback> notedWatchers = mNotedWatchers.valueAt(i);
3913 if (notedWatchers.size() <= 0) {
3914 continue;
3915 }
3916 final NotedCallback cb = notedWatchers.valueAt(0);
3917 if (dumpOp >= 0 && notedWatchers.indexOfKey(dumpOp) < 0) {
3918 continue;
3919 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08003920 if (dumpPackage != null
Svet Ganovb3d2ae22018-12-17 22:06:15 -08003921 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3922 continue;
3923 }
3924 if (!printedHeader) {
3925 pw.println(" All op noted watchers:");
3926 printedHeader = true;
3927 }
3928 pw.print(" ");
3929 pw.print(Integer.toHexString(System.identityHashCode(
3930 mNotedWatchers.keyAt(i))));
3931 pw.println(" ->");
3932 pw.print(" [");
3933 final int opCount = notedWatchers.size();
3934 for (i = 0; i < opCount; i++) {
3935 if (i > 0) {
3936 pw.print(' ');
3937 }
3938 pw.print(AppOpsManager.opToName(notedWatchers.keyAt(i)));
3939 if (i < opCount - 1) {
3940 pw.print(',');
3941 }
3942 }
3943 pw.println("]");
3944 pw.print(" ");
3945 pw.println(cb);
3946 }
3947 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003948 if (mClients.size() > 0 && dumpMode < 0 && !dumpWatchers && !dumpHistory) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003949 needSep = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003950 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003951 for (int i=0; i<mClients.size(); i++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003952 boolean printedClient = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003953 ClientState cs = mClients.valueAt(i);
Svet Ganovf7b47252018-02-26 11:11:27 -08003954 if (cs.mStartedOps.size() > 0) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003955 boolean printedStarted = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003956 for (int j=0; j<cs.mStartedOps.size(); j++) {
3957 Op op = cs.mStartedOps.get(j);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003958 if (dumpOp >= 0 && op.op != dumpOp) {
3959 continue;
3960 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003961 if (dumpPackage != null && !dumpPackage.equals(op.packageName)) {
3962 continue;
3963 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003964 if (!printedHeader) {
3965 pw.println(" Clients:");
3966 printedHeader = true;
3967 }
3968 if (!printedClient) {
3969 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
3970 pw.print(" "); pw.println(cs);
3971 printedClient = true;
3972 }
3973 if (!printedStarted) {
3974 pw.println(" Started ops:");
3975 printedStarted = true;
3976 }
Svet Ganovaf189e32019-02-15 18:45:29 -08003977 pw.print(" "); pw.print("uid="); pw.print(op.uidState.uid);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003978 pw.print(" pkg="); pw.print(op.packageName);
3979 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
3980 }
3981 }
3982 }
3983 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003984 if (mAudioRestrictions.size() > 0 && dumpOp < 0 && dumpPackage != null
Svet Ganovaf189e32019-02-15 18:45:29 -08003985 && dumpMode < 0 && !dumpWatchers && !dumpWatchers) {
John Spurlock1af30c72014-03-10 08:33:35 -04003986 boolean printedHeader = false;
3987 for (int o=0; o<mAudioRestrictions.size(); o++) {
3988 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
3989 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
3990 for (int i=0; i<restrictions.size(); i++) {
3991 if (!printedHeader){
3992 pw.println(" Audio Restrictions:");
3993 printedHeader = true;
3994 needSep = true;
3995 }
John Spurlock7b414672014-07-18 13:02:39 -04003996 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04003997 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04003998 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04003999 Restriction r = restrictions.valueAt(i);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004000 pw.print(": mode="); pw.println(AppOpsManager.modeToName(r.mode));
John Spurlock1af30c72014-03-10 08:33:35 -04004001 if (!r.exceptionPackages.isEmpty()) {
4002 pw.println(" Exceptions:");
4003 for (int j=0; j<r.exceptionPackages.size(); j++) {
4004 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
4005 }
4006 }
4007 }
4008 }
4009 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07004010 if (needSep) {
4011 pw.println();
4012 }
Svet Ganov2af57082015-07-30 08:44:20 -07004013 for (int i=0; i<mUidStates.size(); i++) {
4014 UidState uidState = mUidStates.valueAt(i);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004015 final SparseIntArray opModes = uidState.opModes;
4016 final ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
4017
Svet Ganovaf189e32019-02-15 18:45:29 -08004018 if (dumpWatchers || dumpHistory) {
Dianne Hackborn125dc532019-01-09 13:31:48 -08004019 continue;
4020 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004021 if (dumpOp >= 0 || dumpPackage != null || dumpMode >= 0) {
4022 boolean hasOp = dumpOp < 0 || (uidState.opModes != null
4023 && uidState.opModes.indexOfKey(dumpOp) >= 0);
4024 boolean hasPackage = dumpPackage == null;
4025 boolean hasMode = dumpMode < 0;
4026 if (!hasMode && opModes != null) {
4027 for (int opi = 0; !hasMode && opi < opModes.size(); opi++) {
4028 if (opModes.valueAt(opi) == dumpMode) {
4029 hasMode = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004030 }
4031 }
4032 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004033 if (pkgOps != null) {
4034 for (int pkgi = 0;
Svet Ganov8455ba22019-01-02 13:05:56 -08004035 (!hasOp || !hasPackage || !hasMode) && pkgi < pkgOps.size();
4036 pkgi++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004037 Ops ops = pkgOps.valueAt(pkgi);
4038 if (!hasOp && ops != null && ops.indexOfKey(dumpOp) >= 0) {
4039 hasOp = true;
4040 }
4041 if (!hasMode) {
4042 for (int opi = 0; !hasMode && opi < ops.size(); opi++) {
4043 if (ops.valueAt(opi).mode == dumpMode) {
4044 hasMode = true;
4045 }
4046 }
4047 }
4048 if (!hasPackage && dumpPackage.equals(ops.packageName)) {
4049 hasPackage = true;
4050 }
4051 }
4052 }
4053 if (uidState.foregroundOps != null && !hasOp) {
4054 if (uidState.foregroundOps.indexOfKey(dumpOp) > 0) {
4055 hasOp = true;
4056 }
4057 }
4058 if (!hasOp || !hasPackage || !hasMode) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004059 continue;
4060 }
4061 }
Svet Ganov2af57082015-07-30 08:44:20 -07004062
4063 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07004064 pw.print(" state=");
Svet Ganovaf189e32019-02-15 18:45:29 -08004065 pw.println(AppOpsManager.getUidStateName(uidState.state));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004066 if (uidState.state != uidState.pendingState) {
4067 pw.print(" pendingState=");
Svet Ganovaf189e32019-02-15 18:45:29 -08004068 pw.println(AppOpsManager.getUidStateName(uidState.pendingState));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004069 }
4070 if (uidState.pendingStateCommitTime != 0) {
4071 pw.print(" pendingStateCommitTime=");
Dianne Hackborn9fb93502018-06-18 12:29:44 -07004072 TimeUtils.formatDuration(uidState.pendingStateCommitTime, nowElapsed, pw);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004073 pw.println();
4074 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07004075 if (uidState.startNesting != 0) {
4076 pw.print(" startNesting=");
4077 pw.println(uidState.startNesting);
4078 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004079 if (uidState.foregroundOps != null && (dumpMode < 0
4080 || dumpMode == AppOpsManager.MODE_FOREGROUND)) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004081 pw.println(" foregroundOps:");
4082 for (int j = 0; j < uidState.foregroundOps.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004083 if (dumpOp >= 0 && dumpOp != uidState.foregroundOps.keyAt(j)) {
4084 continue;
4085 }
4086 pw.print(" ");
4087 pw.print(AppOpsManager.opToName(uidState.foregroundOps.keyAt(j)));
4088 pw.print(": ");
4089 pw.println(uidState.foregroundOps.valueAt(j) ? "WATCHER" : "SILENT");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004090 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004091 pw.print(" hasForegroundWatchers=");
4092 pw.println(uidState.hasForegroundWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004093 }
Svet Ganovee438d42017-01-19 18:04:38 -08004094 needSep = true;
Svet Ganov2af57082015-07-30 08:44:20 -07004095
Svet Ganov2af57082015-07-30 08:44:20 -07004096 if (opModes != null) {
4097 final int opModeCount = opModes.size();
4098 for (int j = 0; j < opModeCount; j++) {
4099 final int code = opModes.keyAt(j);
4100 final int mode = opModes.valueAt(j);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004101 if (dumpOp >= 0 && dumpOp != code) {
4102 continue;
4103 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004104 if (dumpMode >= 0 && dumpMode != mode) {
4105 continue;
4106 }
Svet Ganov2af57082015-07-30 08:44:20 -07004107 pw.print(" "); pw.print(AppOpsManager.opToName(code));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004108 pw.print(": mode="); pw.println(AppOpsManager.modeToName(mode));
Svet Ganov2af57082015-07-30 08:44:20 -07004109 }
4110 }
4111
Svet Ganov2af57082015-07-30 08:44:20 -07004112 if (pkgOps == null) {
4113 continue;
4114 }
4115
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004116 for (int pkgi = 0; pkgi < pkgOps.size(); pkgi++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004117 final Ops ops = pkgOps.valueAt(pkgi);
4118 if (dumpPackage != null && !dumpPackage.equals(ops.packageName)) {
4119 continue;
4120 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004121 boolean printedPackage = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004122 for (int j=0; j<ops.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004123 final Op op = ops.valueAt(j);
Svet Ganovaf189e32019-02-15 18:45:29 -08004124 final int opCode = op.op;
4125 if (dumpOp >= 0 && dumpOp != opCode) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004126 continue;
4127 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004128 if (dumpMode >= 0 && dumpMode != op.mode) {
4129 continue;
4130 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004131 if (!printedPackage) {
4132 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
4133 printedPackage = true;
4134 }
Svet Ganovaf189e32019-02-15 18:45:29 -08004135 pw.print(" "); pw.print(AppOpsManager.opToName(opCode));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004136 pw.print(" ("); pw.print(AppOpsManager.modeToName(op.mode));
Svet Ganovaf189e32019-02-15 18:45:29 -08004137 final int switchOp = AppOpsManager.opToSwitch(opCode);
4138 if (switchOp != opCode) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004139 pw.print(" / switch ");
4140 pw.print(AppOpsManager.opToName(switchOp));
4141 final Op switchObj = ops.get(switchOp);
Svet Ganovaf189e32019-02-15 18:45:29 -08004142 int mode = switchObj != null ? switchObj.mode
4143 : AppOpsManager.opToDefaultMode(switchOp);
Dianne Hackborn65a4f252018-05-08 17:30:48 -07004144 pw.print("="); pw.print(AppOpsManager.modeToName(mode));
4145 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07004146 pw.println("): ");
Svet Ganovaf189e32019-02-15 18:45:29 -08004147 dumpStatesLocked(pw, op, now, sdf, date, " ");
4148 if (op.running) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07004149 pw.print(" Running start at: ");
4150 TimeUtils.formatDuration(nowElapsed-op.startRealtime, pw);
4151 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004152 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07004153 if (op.startNesting != 0) {
4154 pw.print(" startNesting=");
4155 pw.println(op.startNesting);
4156 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004157 }
4158 }
4159 }
Svet Ganovee438d42017-01-19 18:04:38 -08004160 if (needSep) {
4161 pw.println();
4162 }
4163
4164 final int userRestrictionCount = mOpUserRestrictions.size();
4165 for (int i = 0; i < userRestrictionCount; i++) {
4166 IBinder token = mOpUserRestrictions.keyAt(i);
4167 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
Dianne Hackborn125dc532019-01-09 13:31:48 -08004168 boolean printedTokenHeader = false;
4169
Svet Ganovaf189e32019-02-15 18:45:29 -08004170 if (dumpMode >= 0 || dumpWatchers || dumpHistory) {
Dianne Hackborn125dc532019-01-09 13:31:48 -08004171 continue;
4172 }
Svet Ganovee438d42017-01-19 18:04:38 -08004173
4174 final int restrictionCount = restrictionState.perUserRestrictions != null
4175 ? restrictionState.perUserRestrictions.size() : 0;
Dianne Hackborn125dc532019-01-09 13:31:48 -08004176 if (restrictionCount > 0 && dumpPackage == null) {
4177 boolean printedOpsHeader = false;
Svet Ganovee438d42017-01-19 18:04:38 -08004178 for (int j = 0; j < restrictionCount; j++) {
4179 int userId = restrictionState.perUserRestrictions.keyAt(j);
4180 boolean[] restrictedOps = restrictionState.perUserRestrictions.valueAt(j);
4181 if (restrictedOps == null) {
4182 continue;
4183 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08004184 if (dumpOp >= 0 && (dumpOp >= restrictedOps.length
4185 || !restrictedOps[dumpOp])) {
4186 continue;
4187 }
4188 if (!printedTokenHeader) {
4189 pw.println(" User restrictions for token " + token + ":");
4190 printedTokenHeader = true;
4191 }
4192 if (!printedOpsHeader) {
4193 pw.println(" Restricted ops:");
4194 printedOpsHeader = true;
4195 }
Svet Ganovee438d42017-01-19 18:04:38 -08004196 StringBuilder restrictedOpsValue = new StringBuilder();
4197 restrictedOpsValue.append("[");
4198 final int restrictedOpCount = restrictedOps.length;
4199 for (int k = 0; k < restrictedOpCount; k++) {
4200 if (restrictedOps[k]) {
4201 if (restrictedOpsValue.length() > 1) {
4202 restrictedOpsValue.append(", ");
4203 }
4204 restrictedOpsValue.append(AppOpsManager.opToName(k));
4205 }
4206 }
4207 restrictedOpsValue.append("]");
4208 pw.print(" "); pw.print("user: "); pw.print(userId);
4209 pw.print(" restricted ops: "); pw.println(restrictedOpsValue);
4210 }
4211 }
4212
4213 final int excludedPackageCount = restrictionState.perUserExcludedPackages != null
4214 ? restrictionState.perUserExcludedPackages.size() : 0;
Dianne Hackborn125dc532019-01-09 13:31:48 -08004215 if (excludedPackageCount > 0 && dumpOp < 0) {
4216 boolean printedPackagesHeader = false;
Svet Ganovee438d42017-01-19 18:04:38 -08004217 for (int j = 0; j < excludedPackageCount; j++) {
4218 int userId = restrictionState.perUserExcludedPackages.keyAt(j);
4219 String[] packageNames = restrictionState.perUserExcludedPackages.valueAt(j);
Dianne Hackborn125dc532019-01-09 13:31:48 -08004220 if (packageNames == null) {
4221 continue;
4222 }
4223 boolean hasPackage;
4224 if (dumpPackage != null) {
4225 hasPackage = false;
4226 for (String pkg : packageNames) {
4227 if (dumpPackage.equals(pkg)) {
4228 hasPackage = true;
4229 break;
4230 }
4231 }
4232 } else {
4233 hasPackage = true;
4234 }
4235 if (!hasPackage) {
4236 continue;
4237 }
4238 if (!printedTokenHeader) {
4239 pw.println(" User restrictions for token " + token + ":");
4240 printedTokenHeader = true;
4241 }
4242 if (!printedPackagesHeader) {
4243 pw.println(" Excluded packages:");
4244 printedPackagesHeader = true;
4245 }
Svet Ganovee438d42017-01-19 18:04:38 -08004246 pw.print(" "); pw.print("user: "); pw.print(userId);
4247 pw.print(" packages: "); pw.println(Arrays.toString(packageNames));
4248 }
4249 }
4250 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004251 }
Svet Ganov8455ba22019-01-02 13:05:56 -08004252
4253 // Must not hold the appops lock
Svet Ganovaf189e32019-02-15 18:45:29 -08004254 if (dumpHistory && !dumpWatchers) {
4255 mHistoricalRegistry.dump(" ", pw, dumpUid, dumpPackage, dumpOp);
4256 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004257 }
John Spurlock1af30c72014-03-10 08:33:35 -04004258
4259 private static final class Restriction {
4260 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
4261 int mode;
4262 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
4263 }
Jason Monk62062992014-05-06 09:55:28 -04004264
4265 @Override
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004266 public void setUserRestrictions(Bundle restrictions, IBinder token, int userHandle) {
Jason Monk62062992014-05-06 09:55:28 -04004267 checkSystemUid("setUserRestrictions");
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004268 Preconditions.checkNotNull(restrictions);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004269 Preconditions.checkNotNull(token);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004270 for (int i = 0; i < AppOpsManager._NUM_OP; i++) {
Jason Monk62062992014-05-06 09:55:28 -04004271 String restriction = AppOpsManager.opToRestriction(i);
Suprabh Shukla64e0dcb2016-05-24 16:23:11 -07004272 if (restriction != null) {
4273 setUserRestrictionNoCheck(i, restrictions.getBoolean(restriction, false), token,
4274 userHandle, null);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004275 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004276 }
4277 }
4278
4279 @Override
Ruben Brunk29931bc2016-03-11 00:24:26 -08004280 public void setUserRestriction(int code, boolean restricted, IBinder token, int userHandle,
4281 String[] exceptionPackages) {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004282 if (Binder.getCallingPid() != Process.myPid()) {
4283 mContext.enforcePermission(Manifest.permission.MANAGE_APP_OPS_RESTRICTIONS,
4284 Binder.getCallingPid(), Binder.getCallingUid(), null);
4285 }
4286 if (userHandle != UserHandle.getCallingUserId()) {
4287 if (mContext.checkCallingOrSelfPermission(Manifest.permission
4288 .INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
4289 && mContext.checkCallingOrSelfPermission(Manifest.permission
4290 .INTERACT_ACROSS_USERS) != PackageManager.PERMISSION_GRANTED) {
4291 throw new SecurityException("Need INTERACT_ACROSS_USERS_FULL or"
4292 + " INTERACT_ACROSS_USERS to interact cross user ");
Jason Monk62062992014-05-06 09:55:28 -04004293 }
4294 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004295 verifyIncomingOp(code);
4296 Preconditions.checkNotNull(token);
Ruben Brunk29931bc2016-03-11 00:24:26 -08004297 setUserRestrictionNoCheck(code, restricted, token, userHandle, exceptionPackages);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004298 }
4299
4300 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
Ruben Brunk29931bc2016-03-11 00:24:26 -08004301 int userHandle, String[] exceptionPackages) {
Svet Ganov442ed572016-08-17 17:29:43 -07004302 synchronized (AppOpsService.this) {
4303 ClientRestrictionState restrictionState = mOpUserRestrictions.get(token);
4304
4305 if (restrictionState == null) {
4306 try {
4307 restrictionState = new ClientRestrictionState(token);
4308 } catch (RemoteException e) {
4309 return;
4310 }
4311 mOpUserRestrictions.put(token, restrictionState);
Ruben Brunk29931bc2016-03-11 00:24:26 -08004312 }
Svet Ganov442ed572016-08-17 17:29:43 -07004313
4314 if (restrictionState.setRestriction(code, restricted, exceptionPackages, userHandle)) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004315 mHandler.sendMessage(PooledLambda.obtainMessage(
Svet Ganov3a95f832018-03-23 17:44:30 -07004316 AppOpsService::notifyWatchersOfChange, this, code, UID_ANY));
Svet Ganov442ed572016-08-17 17:29:43 -07004317 }
4318
4319 if (restrictionState.isDefault()) {
4320 mOpUserRestrictions.remove(token);
4321 restrictionState.destroy();
4322 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08004323 }
Julia Reynoldsbb21c252016-04-05 16:01:49 -04004324 }
4325
Svet Ganov3a95f832018-03-23 17:44:30 -07004326 private void notifyWatchersOfChange(int code, int uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004327 final ArraySet<ModeCallback> clonedCallbacks;
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004328 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004329 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004330 if (callbacks == null) {
4331 return;
4332 }
Dianne Hackborn68d76552017-02-27 15:32:03 -08004333 clonedCallbacks = new ArraySet<>(callbacks);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004334 }
4335
Svet Ganov3a95f832018-03-23 17:44:30 -07004336 notifyOpChanged(clonedCallbacks, code, uid, null);
Jason Monk62062992014-05-06 09:55:28 -04004337 }
4338
4339 @Override
4340 public void removeUser(int userHandle) throws RemoteException {
4341 checkSystemUid("removeUser");
Svet Ganov442ed572016-08-17 17:29:43 -07004342 synchronized (AppOpsService.this) {
4343 final int tokenCount = mOpUserRestrictions.size();
4344 for (int i = tokenCount - 1; i >= 0; i--) {
4345 ClientRestrictionState opRestrictions = mOpUserRestrictions.valueAt(i);
4346 opRestrictions.removeUser(userHandle);
4347 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07004348 removeUidsForUserLocked(userHandle);
4349 }
4350 }
4351
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004352 @Override
4353 public boolean isOperationActive(int code, int uid, String packageName) {
Svet Ganovf7b47252018-02-26 11:11:27 -08004354 if (Binder.getCallingUid() != uid) {
4355 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
4356 != PackageManager.PERMISSION_GRANTED) {
4357 return false;
4358 }
4359 }
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004360 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004361 final String resolvedPackageName = resolvePackageName(uid, packageName);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004362 if (resolvedPackageName == null) {
4363 return false;
4364 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004365 synchronized (AppOpsService.this) {
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004366 for (int i = mClients.size() - 1; i >= 0; i--) {
4367 final ClientState client = mClients.valueAt(i);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004368 for (int j = client.mStartedOps.size() - 1; j >= 0; j--) {
4369 final Op op = client.mStartedOps.get(j);
Svet Ganovaf189e32019-02-15 18:45:29 -08004370 if (op.op == code && op.uidState.uid == uid) return true;
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004371 }
4372 }
4373 }
4374 return false;
4375 }
4376
Svet Ganov8455ba22019-01-02 13:05:56 -08004377 @Override
4378 public void setHistoryParameters(@AppOpsManager.HistoricalMode int mode,
4379 long baseSnapshotInterval, int compressionStep) {
4380 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4381 "setHistoryParameters");
4382 // Must not hold the appops lock
4383 mHistoricalRegistry.setHistoryParameters(mode, baseSnapshotInterval, compressionStep);
4384 }
4385
4386 @Override
4387 public void offsetHistory(long offsetMillis) {
4388 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4389 "offsetHistory");
4390 // Must not hold the appops lock
4391 mHistoricalRegistry.offsetHistory(offsetMillis);
4392 }
4393
4394 @Override
4395 public void addHistoricalOps(HistoricalOps ops) {
4396 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4397 "addHistoricalOps");
4398 // Must not hold the appops lock
4399 mHistoricalRegistry.addHistoricalOps(ops);
4400 }
4401
4402 @Override
4403 public void resetHistoryParameters() {
4404 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4405 "resetHistoryParameters");
4406 // Must not hold the appops lock
4407 mHistoricalRegistry.resetHistoryParameters();
4408 }
4409
4410 @Override
4411 public void clearHistory() {
4412 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4413 "clearHistory");
4414 // Must not hold the appops lock
4415 mHistoricalRegistry.clearHistory();
4416 }
4417
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07004418 private void removeUidsForUserLocked(int userHandle) {
4419 for (int i = mUidStates.size() - 1; i >= 0; --i) {
4420 final int uid = mUidStates.keyAt(i);
4421 if (UserHandle.getUserId(uid) == userHandle) {
4422 mUidStates.removeAt(i);
4423 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004424 }
4425 }
4426
Jason Monk62062992014-05-06 09:55:28 -04004427 private void checkSystemUid(String function) {
4428 int uid = Binder.getCallingUid();
4429 if (uid != Process.SYSTEM_UID) {
4430 throw new SecurityException(function + " must by called by the system");
4431 }
4432 }
4433
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004434 private static String resolvePackageName(int uid, String packageName) {
Svet Ganov82f09bc2018-01-12 22:08:40 -08004435 if (uid == Process.ROOT_UID) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004436 return "root";
4437 } else if (uid == Process.SHELL_UID) {
4438 return "com.android.shell";
Svet Ganov82f09bc2018-01-12 22:08:40 -08004439 } else if (uid == Process.MEDIA_UID) {
4440 return "media";
4441 } else if (uid == Process.AUDIOSERVER_UID) {
4442 return "audioserver";
4443 } else if (uid == Process.CAMERASERVER_UID) {
4444 return "cameraserver";
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004445 } else if (uid == Process.SYSTEM_UID && packageName == null) {
4446 return "android";
4447 }
4448 return packageName;
4449 }
4450
Svet Ganov82f09bc2018-01-12 22:08:40 -08004451 private static int resolveUid(String packageName) {
4452 if (packageName == null) {
4453 return -1;
4454 }
4455 switch (packageName) {
4456 case "root":
4457 return Process.ROOT_UID;
4458 case "shell":
4459 return Process.SHELL_UID;
4460 case "media":
4461 return Process.MEDIA_UID;
4462 case "audioserver":
4463 return Process.AUDIOSERVER_UID;
4464 case "cameraserver":
4465 return Process.CAMERASERVER_UID;
4466 }
4467 return -1;
4468 }
4469
Svet Ganov2af57082015-07-30 08:44:20 -07004470 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07004471 String[] packageNames = null;
Philip P. Moltmann159d98b2018-12-20 08:30:53 -08004472
4473 // Very early during boot the package manager is not yet or not yet fully started. At this
4474 // time there are no packages yet.
4475 if (AppGlobals.getPackageManager() != null) {
4476 try {
4477 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
4478 } catch (RemoteException e) {
4479 /* ignore - local call */
4480 }
Svet Ganov2af57082015-07-30 08:44:20 -07004481 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07004482 if (packageNames == null) {
4483 return EmptyArray.STRING;
4484 }
4485 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07004486 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004487
4488 private final class ClientRestrictionState implements DeathRecipient {
4489 private final IBinder token;
4490 SparseArray<boolean[]> perUserRestrictions;
4491 SparseArray<String[]> perUserExcludedPackages;
4492
4493 public ClientRestrictionState(IBinder token)
4494 throws RemoteException {
4495 token.linkToDeath(this, 0);
4496 this.token = token;
4497 }
4498
4499 public boolean setRestriction(int code, boolean restricted,
4500 String[] excludedPackages, int userId) {
4501 boolean changed = false;
4502
4503 if (perUserRestrictions == null && restricted) {
4504 perUserRestrictions = new SparseArray<>();
4505 }
4506
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004507 int[] users;
4508 if (userId == UserHandle.USER_ALL) {
4509 List<UserInfo> liveUsers = UserManager.get(mContext).getUsers(false);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004510
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004511 users = new int[liveUsers.size()];
4512 for (int i = 0; i < liveUsers.size(); i++) {
4513 users[i] = liveUsers.get(i).id;
4514 }
4515 } else {
4516 users = new int[]{userId};
4517 }
4518
4519 if (perUserRestrictions != null) {
4520 int numUsers = users.length;
4521
4522 for (int i = 0; i < numUsers; i++) {
4523 int thisUserId = users[i];
4524
4525 boolean[] userRestrictions = perUserRestrictions.get(thisUserId);
4526 if (userRestrictions == null && restricted) {
4527 userRestrictions = new boolean[AppOpsManager._NUM_OP];
4528 perUserRestrictions.put(thisUserId, userRestrictions);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004529 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004530 if (userRestrictions != null && userRestrictions[code] != restricted) {
4531 userRestrictions[code] = restricted;
4532 if (!restricted && isDefault(userRestrictions)) {
4533 perUserRestrictions.remove(thisUserId);
4534 userRestrictions = null;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004535 }
4536 changed = true;
4537 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004538
4539 if (userRestrictions != null) {
4540 final boolean noExcludedPackages = ArrayUtils.isEmpty(excludedPackages);
4541 if (perUserExcludedPackages == null && !noExcludedPackages) {
4542 perUserExcludedPackages = new SparseArray<>();
4543 }
4544 if (perUserExcludedPackages != null && !Arrays.equals(excludedPackages,
4545 perUserExcludedPackages.get(thisUserId))) {
4546 if (noExcludedPackages) {
4547 perUserExcludedPackages.remove(thisUserId);
4548 if (perUserExcludedPackages.size() <= 0) {
4549 perUserExcludedPackages = null;
4550 }
4551 } else {
4552 perUserExcludedPackages.put(thisUserId, excludedPackages);
4553 }
4554 changed = true;
4555 }
4556 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004557 }
4558 }
4559
4560 return changed;
4561 }
4562
4563 public boolean hasRestriction(int restriction, String packageName, int userId) {
4564 if (perUserRestrictions == null) {
4565 return false;
4566 }
4567 boolean[] restrictions = perUserRestrictions.get(userId);
4568 if (restrictions == null) {
4569 return false;
4570 }
4571 if (!restrictions[restriction]) {
4572 return false;
4573 }
4574 if (perUserExcludedPackages == null) {
4575 return true;
4576 }
4577 String[] perUserExclusions = perUserExcludedPackages.get(userId);
4578 if (perUserExclusions == null) {
4579 return true;
4580 }
4581 return !ArrayUtils.contains(perUserExclusions, packageName);
4582 }
4583
4584 public void removeUser(int userId) {
4585 if (perUserExcludedPackages != null) {
4586 perUserExcludedPackages.remove(userId);
4587 if (perUserExcludedPackages.size() <= 0) {
4588 perUserExcludedPackages = null;
4589 }
4590 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07004591 if (perUserRestrictions != null) {
4592 perUserRestrictions.remove(userId);
4593 if (perUserRestrictions.size() <= 0) {
4594 perUserRestrictions = null;
4595 }
4596 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004597 }
4598
4599 public boolean isDefault() {
4600 return perUserRestrictions == null || perUserRestrictions.size() <= 0;
4601 }
4602
4603 @Override
4604 public void binderDied() {
4605 synchronized (AppOpsService.this) {
4606 mOpUserRestrictions.remove(token);
4607 if (perUserRestrictions == null) {
4608 return;
4609 }
4610 final int userCount = perUserRestrictions.size();
4611 for (int i = 0; i < userCount; i++) {
4612 final boolean[] restrictions = perUserRestrictions.valueAt(i);
4613 final int restrictionCount = restrictions.length;
4614 for (int j = 0; j < restrictionCount; j++) {
4615 if (restrictions[j]) {
4616 final int changedCode = j;
Svet Ganov3a95f832018-03-23 17:44:30 -07004617 mHandler.post(() -> notifyWatchersOfChange(changedCode, UID_ANY));
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004618 }
4619 }
4620 }
4621 destroy();
4622 }
4623 }
4624
4625 public void destroy() {
4626 token.unlinkToDeath(this, 0);
4627 }
4628
4629 private boolean isDefault(boolean[] array) {
4630 if (ArrayUtils.isEmpty(array)) {
4631 return true;
4632 }
4633 for (boolean value : array) {
4634 if (value) {
4635 return false;
4636 }
4637 }
4638 return true;
4639 }
4640 }
Dianne Hackbornd5254412018-05-11 18:02:58 -07004641
4642 private final class AppOpsManagerInternalImpl extends AppOpsManagerInternal {
4643 @Override public void setDeviceAndProfileOwners(SparseIntArray owners) {
4644 synchronized (AppOpsService.this) {
4645 mProfileOwners = owners;
4646 }
4647 }
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07004648
4649 @Override
Philip P. Moltmann159d98b2018-12-20 08:30:53 -08004650 public void setUidMode(int code, int uid, int mode) {
4651 AppOpsService.this.setUidMode(code, uid, mode);
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07004652 }
Philip P. Moltmanndde07852019-01-25 16:42:36 -08004653
4654 @Override
4655 public void setAllPkgModesToDefault(int code, int uid) {
4656 AppOpsService.this.setAllPkgModesToDefault(code, uid);
4657 }
Philip P. Moltmann724150d2019-03-11 17:01:05 -07004658
4659 @Override
4660 public @Mode int checkOperationUnchecked(int code, int uid, @NonNull String packageName) {
4661 return AppOpsService.this.checkOperationUnchecked(code, uid, packageName, true, false);
4662 }
Dianne Hackbornd5254412018-05-11 18:02:58 -07004663 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004664}