blob: 70c28a854512cdb80a39276a0e5a1e4e7e750eb5 [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 Ganov8455ba22019-01-02 13:05:56 -080019import static android.app.AppOpsManager.OP_NONE;
Philip P. Moltmanndde07852019-01-25 16:42:36 -080020import static android.app.AppOpsManager.OP_PLAY_AUDIO;
Hai Zhang2b98fb32018-09-21 15:18:46 -070021import static android.app.AppOpsManager.UID_STATE_BACKGROUND;
22import static android.app.AppOpsManager.UID_STATE_CACHED;
23import static android.app.AppOpsManager.UID_STATE_FOREGROUND;
24import static android.app.AppOpsManager.UID_STATE_FOREGROUND_SERVICE;
Amith Yamasania0a30a12019-01-22 11:38:06 -080025import static android.app.AppOpsManager.UID_STATE_FOREGROUND_SERVICE_LOCATION;
Hai Zhang2b98fb32018-09-21 15:18:46 -070026import static android.app.AppOpsManager.UID_STATE_LAST_NON_RESTRICTED;
27import static android.app.AppOpsManager.UID_STATE_PERSISTENT;
28import static android.app.AppOpsManager.UID_STATE_TOP;
29import static android.app.AppOpsManager._NUM_UID_STATE;
Eugene Suslae4ee2c22018-11-05 12:23:30 -080030import static android.app.AppOpsManager.modeToName;
31import static android.app.AppOpsManager.opToName;
Hai Zhang2b98fb32018-09-21 15:18:46 -070032
Philip P. Moltmanne683f192017-06-23 14:05:04 -070033import android.Manifest;
Svet Ganovad0a49b2018-10-29 10:07:08 -070034import android.annotation.NonNull;
35import android.annotation.Nullable;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070036import android.app.ActivityManager;
37import android.app.ActivityThread;
38import android.app.AppGlobals;
39import android.app.AppOpsManager;
Svet Ganov8455ba22019-01-02 13:05:56 -080040import android.app.AppOpsManager.HistoricalOps;
Svet Ganov23c88db2019-01-22 20:38:11 -080041import android.app.AppOpsManager.HistoricalOpsRequest;
Dianne Hackbornd5254412018-05-11 18:02:58 -070042import android.app.AppOpsManagerInternal;
Svet Ganovd873ae62018-06-25 16:39:23 -070043import android.app.AppOpsManagerInternal.CheckOpsDelegate;
Suprabh Shukla3017fe42018-11-08 19:00:01 -080044import android.content.BroadcastReceiver;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070045import android.content.ContentResolver;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070046import android.content.Context;
Suprabh Shukla3017fe42018-11-08 19:00:01 -080047import android.content.Intent;
48import android.content.IntentFilter;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070049import android.content.pm.ApplicationInfo;
50import android.content.pm.IPackageManager;
51import android.content.pm.PackageManager;
52import android.content.pm.PackageManagerInternal;
53import android.content.pm.UserInfo;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070054import android.database.ContentObserver;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070055import android.media.AudioAttributes;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070056import android.net.Uri;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070057import android.os.AsyncTask;
58import android.os.Binder;
59import android.os.Bundle;
60import android.os.Handler;
61import android.os.IBinder;
62import android.os.Process;
Svet Ganov8455ba22019-01-02 13:05:56 -080063import android.os.RemoteCallback;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070064import android.os.RemoteException;
65import android.os.ResultReceiver;
66import android.os.ServiceManager;
67import android.os.ShellCallback;
68import android.os.ShellCommand;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -070069import android.os.SystemClock;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070070import android.os.UserHandle;
71import android.os.UserManager;
Sudheer Shanka98cb3f02018-08-17 16:10:29 -070072import android.os.storage.StorageManager;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070073import android.os.storage.StorageManagerInternal;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070074import android.provider.Settings;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070075import android.util.ArrayMap;
76import android.util.ArraySet;
77import android.util.AtomicFile;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070078import android.util.KeyValueListParser;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070079import android.util.Slog;
80import android.util.SparseArray;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -070081import android.util.SparseBooleanArray;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070082import android.util.SparseIntArray;
83import android.util.TimeUtils;
84import android.util.Xml;
85
Todd Kennedy556efba2018-11-15 07:43:55 -080086import com.android.internal.annotations.GuardedBy;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070087import com.android.internal.annotations.VisibleForTesting;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -080088import com.android.internal.app.IAppOpsActiveCallback;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070089import com.android.internal.app.IAppOpsCallback;
Svet Ganovb3d2ae22018-12-17 22:06:15 -080090import com.android.internal.app.IAppOpsNotedCallback;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070091import com.android.internal.app.IAppOpsService;
92import com.android.internal.os.Zygote;
93import com.android.internal.util.ArrayUtils;
94import com.android.internal.util.DumpUtils;
95import com.android.internal.util.FastXmlSerializer;
96import com.android.internal.util.Preconditions;
97import com.android.internal.util.XmlUtils;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -080098import com.android.internal.util.function.pooled.PooledLambda;
Svet Ganov8455ba22019-01-02 13:05:56 -080099import com.android.server.LocalServices;
100import com.android.server.LockGuard;
Philip P. Moltmanndde07852019-01-25 16:42:36 -0800101
Philip P. Moltmanne683f192017-06-23 14:05:04 -0700102import libcore.util.EmptyArray;
103
104import org.xmlpull.v1.XmlPullParser;
105import org.xmlpull.v1.XmlPullParserException;
106import org.xmlpull.v1.XmlSerializer;
107
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800108import java.io.File;
109import java.io.FileDescriptor;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800110import java.io.FileInputStream;
111import java.io.FileNotFoundException;
112import java.io.FileOutputStream;
113import java.io.IOException;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800114import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100115import java.nio.charset.StandardCharsets;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700116import java.text.SimpleDateFormat;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800117import java.util.ArrayList;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -0700118import java.util.Arrays;
Svetoslav215b44a2015-08-04 19:03:40 -0700119import java.util.Collections;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700120import java.util.Date;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800121import java.util.HashMap;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800122import java.util.Iterator;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800123import java.util.List;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700124import java.util.Map;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800125
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800126public class AppOpsService extends IAppOpsService.Stub {
127 static final String TAG = "AppOps";
Dianne Hackborn35654b62013-01-14 17:38:02 -0800128 static final boolean DEBUG = false;
129
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700130 private static final int NO_VERSION = -1;
131 /** Increment by one every time and add the corresponding upgrade logic in
132 * {@link #upgradeLocked(int)} below. The first version was 1 */
133 private static final int CURRENT_VERSION = 1;
134
Dianne Hackborn35654b62013-01-14 17:38:02 -0800135 // Write at most every 30 minutes.
136 static final long WRITE_DELAY = DEBUG ? 1000 : 30*60*1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800137
Svet Ganov3a95f832018-03-23 17:44:30 -0700138 // Constant meaning that any UID should be matched when dispatching callbacks
139 private static final int UID_ANY = -2;
140
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700141 // Map from process states to the uid states we track.
142 private static final int[] PROCESS_STATE_TO_UID_STATE = new int[] {
143 UID_STATE_PERSISTENT, // ActivityManager.PROCESS_STATE_PERSISTENT
144 UID_STATE_PERSISTENT, // ActivityManager.PROCESS_STATE_PERSISTENT_UI
145 UID_STATE_TOP, // ActivityManager.PROCESS_STATE_TOP
Amith Yamasania0a30a12019-01-22 11:38:06 -0800146 UID_STATE_FOREGROUND_SERVICE_LOCATION,
147 // ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE_LOCATION
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700148 UID_STATE_FOREGROUND_SERVICE, // ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
149 UID_STATE_FOREGROUND, // ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
150 UID_STATE_FOREGROUND, // ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND
151 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND
152 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_TRANSIENT_BACKGROUND
153 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_BACKUP
154 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_SERVICE
155 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_RECEIVER
156 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_TOP_SLEEPING
157 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_HEAVY_WEIGHT
158 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_HOME
159 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_LAST_ACTIVITY
160 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY
161 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT
162 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_RECENT
163 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_EMPTY
164 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_NONEXISTENT
165 };
166
167 static final String[] UID_STATE_NAMES = new String[] {
168 "pers ", // UID_STATE_PERSISTENT
169 "top ", // UID_STATE_TOP
Amith Yamasania0a30a12019-01-22 11:38:06 -0800170 "fgsvcl", // UID_STATE_FOREGROUND_SERVICE_LOCATION
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700171 "fgsvc", // UID_STATE_FOREGROUND_SERVICE
172 "fg ", // UID_STATE_FOREGROUND
173 "bg ", // UID_STATE_BACKGROUND
174 "cch ", // UID_STATE_CACHED
175 };
176
177 static final String[] UID_STATE_TIME_ATTRS = new String[] {
178 "tp", // UID_STATE_PERSISTENT
179 "tt", // UID_STATE_TOP
Amith Yamasania0a30a12019-01-22 11:38:06 -0800180 "tfsl", // UID_STATE_FOREGROUND_SERVICE_LOCATION
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700181 "tfs", // UID_STATE_FOREGROUND_SERVICE
182 "tf", // UID_STATE_FOREGROUND
183 "tb", // UID_STATE_BACKGROUND
184 "tc", // UID_STATE_CACHED
185 };
186
187 static final String[] UID_STATE_REJECT_ATTRS = new String[] {
188 "rp", // UID_STATE_PERSISTENT
189 "rt", // UID_STATE_TOP
Amith Yamasania0a30a12019-01-22 11:38:06 -0800190 "rfsl", // UID_STATE_FOREGROUND_SERVICE_LOCATION
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700191 "rfs", // UID_STATE_FOREGROUND_SERVICE
192 "rf", // UID_STATE_FOREGROUND
193 "rb", // UID_STATE_BACKGROUND
194 "rc", // UID_STATE_CACHED
195 };
196
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800197 Context mContext;
198 final AtomicFile mFile;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800199 final Handler mHandler;
200
Dianne Hackbornd5254412018-05-11 18:02:58 -0700201 private final AppOpsManagerInternalImpl mAppOpsManagerInternal
202 = new AppOpsManagerInternalImpl();
203
Dianne Hackborn35654b62013-01-14 17:38:02 -0800204 boolean mWriteScheduled;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800205 boolean mFastWriteScheduled;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800206 final Runnable mWriteRunner = new Runnable() {
207 public void run() {
208 synchronized (AppOpsService.this) {
209 mWriteScheduled = false;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800210 mFastWriteScheduled = false;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800211 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
212 @Override protected Void doInBackground(Void... params) {
213 writeState();
214 return null;
215 }
216 };
217 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
218 }
219 }
220 };
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800221
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700222 @VisibleForTesting
223 final SparseArray<UidState> mUidStates = new SparseArray<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800224
Svet Ganov8455ba22019-01-02 13:05:56 -0800225 private final HistoricalRegistry mHistoricalRegistry = new HistoricalRegistry(this);
226
Dianne Hackborn9fb93502018-06-18 12:29:44 -0700227 long mLastRealtime;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700228
Ruben Brunk29931bc2016-03-11 00:24:26 -0800229 /*
230 * These are app op restrictions imposed per user from various parties.
Ruben Brunk29931bc2016-03-11 00:24:26 -0800231 */
Svetoslav Ganova8bbd762016-05-13 17:08:16 -0700232 private final ArrayMap<IBinder, ClientRestrictionState> mOpUserRestrictions = new ArrayMap<>();
Jason Monk62062992014-05-06 09:55:28 -0400233
Dianne Hackbornd5254412018-05-11 18:02:58 -0700234 SparseIntArray mProfileOwners;
235
Todd Kennedy556efba2018-11-15 07:43:55 -0800236 @GuardedBy("this")
Svet Ganovd873ae62018-06-25 16:39:23 -0700237 private CheckOpsDelegate mCheckOpsDelegate;
238
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700239 /**
240 * All times are in milliseconds. These constants are kept synchronized with the system
241 * global Settings. Any access to this class or its fields should be done while
242 * holding the AppOpsService lock.
243 */
244 private final class Constants extends ContentObserver {
245 // Key names stored in the settings value.
Dianne Hackborne93ab412018-05-14 17:52:30 -0700246 private static final String KEY_TOP_STATE_SETTLE_TIME = "top_state_settle_time";
247 private static final String KEY_FG_SERVICE_STATE_SETTLE_TIME
248 = "fg_service_state_settle_time";
249 private static final String KEY_BG_STATE_SETTLE_TIME = "bg_state_settle_time";
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700250
251 /**
Dianne Hackborne93ab412018-05-14 17:52:30 -0700252 * How long we want for a drop in uid state from top to settle before applying it.
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700253 * @see Settings.Global#APP_OPS_CONSTANTS
Dianne Hackborne93ab412018-05-14 17:52:30 -0700254 * @see #KEY_TOP_STATE_SETTLE_TIME
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700255 */
Dianne Hackborne93ab412018-05-14 17:52:30 -0700256 public long TOP_STATE_SETTLE_TIME;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700257
Dianne Hackborne93ab412018-05-14 17:52:30 -0700258 /**
259 * How long we want for a drop in uid state from foreground to settle before applying it.
260 * @see Settings.Global#APP_OPS_CONSTANTS
261 * @see #KEY_FG_SERVICE_STATE_SETTLE_TIME
262 */
263 public long FG_SERVICE_STATE_SETTLE_TIME;
264
265 /**
266 * How long we want for a drop in uid state from background to settle before applying it.
267 * @see Settings.Global#APP_OPS_CONSTANTS
268 * @see #KEY_BG_STATE_SETTLE_TIME
269 */
270 public long BG_STATE_SETTLE_TIME;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700271
272 private final KeyValueListParser mParser = new KeyValueListParser(',');
273 private ContentResolver mResolver;
274
275 public Constants(Handler handler) {
276 super(handler);
277 updateConstants();
278 }
279
280 public void startMonitoring(ContentResolver resolver) {
281 mResolver = resolver;
282 mResolver.registerContentObserver(
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700283 Settings.Global.getUriFor(Settings.Global.APP_OPS_CONSTANTS),
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700284 false, this);
285 updateConstants();
286 }
287
288 @Override
289 public void onChange(boolean selfChange, Uri uri) {
290 updateConstants();
291 }
292
293 private void updateConstants() {
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700294 String value = mResolver != null ? Settings.Global.getString(mResolver,
295 Settings.Global.APP_OPS_CONSTANTS) : "";
296
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700297 synchronized (AppOpsService.this) {
298 try {
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700299 mParser.setString(value);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700300 } catch (IllegalArgumentException e) {
301 // Failed to parse the settings string, log this and move on
302 // with defaults.
303 Slog.e(TAG, "Bad app ops settings", e);
304 }
Dianne Hackborne93ab412018-05-14 17:52:30 -0700305 TOP_STATE_SETTLE_TIME = mParser.getDurationMillis(
306 KEY_TOP_STATE_SETTLE_TIME, 30 * 1000L);
307 FG_SERVICE_STATE_SETTLE_TIME = mParser.getDurationMillis(
308 KEY_FG_SERVICE_STATE_SETTLE_TIME, 10 * 1000L);
309 BG_STATE_SETTLE_TIME = mParser.getDurationMillis(
310 KEY_BG_STATE_SETTLE_TIME, 1 * 1000L);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700311 }
312 }
313
314 void dump(PrintWriter pw) {
315 pw.println(" Settings:");
316
Dianne Hackborne93ab412018-05-14 17:52:30 -0700317 pw.print(" "); pw.print(KEY_TOP_STATE_SETTLE_TIME); pw.print("=");
318 TimeUtils.formatDuration(TOP_STATE_SETTLE_TIME, pw);
Dianne Hackbornb94d82f2018-05-16 17:03:01 -0700319 pw.println();
Dianne Hackborne93ab412018-05-14 17:52:30 -0700320 pw.print(" "); pw.print(KEY_FG_SERVICE_STATE_SETTLE_TIME); pw.print("=");
321 TimeUtils.formatDuration(FG_SERVICE_STATE_SETTLE_TIME, pw);
Dianne Hackbornb94d82f2018-05-16 17:03:01 -0700322 pw.println();
Dianne Hackborne93ab412018-05-14 17:52:30 -0700323 pw.print(" "); pw.print(KEY_BG_STATE_SETTLE_TIME); pw.print("=");
324 TimeUtils.formatDuration(BG_STATE_SETTLE_TIME, pw);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700325 pw.println();
326 }
327 }
328
329 private final Constants mConstants;
330
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700331 @VisibleForTesting
332 static final class UidState {
Svet Ganov2af57082015-07-30 08:44:20 -0700333 public final int uid;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700334
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700335 public int state = UID_STATE_CACHED;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700336 public int pendingState = UID_STATE_CACHED;
337 public long pendingStateCommitTime;
338
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700339 public int startNesting;
Svet Ganov2af57082015-07-30 08:44:20 -0700340 public ArrayMap<String, Ops> pkgOps;
341 public SparseIntArray opModes;
342
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700343 // true indicates there is an interested observer, false there isn't but it has such an op
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700344 public SparseBooleanArray foregroundOps;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700345 public boolean hasForegroundWatchers;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700346
Svet Ganov2af57082015-07-30 08:44:20 -0700347 public UidState(int uid) {
348 this.uid = uid;
349 }
350
351 public void clear() {
352 pkgOps = null;
353 opModes = null;
354 }
355
356 public boolean isDefault() {
357 return (pkgOps == null || pkgOps.isEmpty())
358 && (opModes == null || opModes.size() <= 0);
359 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700360
361 int evalMode(int mode) {
362 if (mode == AppOpsManager.MODE_FOREGROUND) {
Dianne Hackborne93ab412018-05-14 17:52:30 -0700363 return state <= UID_STATE_LAST_NON_RESTRICTED
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700364 ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED;
365 }
366 return mode;
367 }
368
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700369 private void evalForegroundWatchers(int op, SparseArray<ArraySet<ModeCallback>> watchers,
370 SparseBooleanArray which) {
371 boolean curValue = which.get(op, false);
372 ArraySet<ModeCallback> callbacks = watchers.get(op);
373 if (callbacks != null) {
374 for (int cbi = callbacks.size() - 1; !curValue && cbi >= 0; cbi--) {
375 if ((callbacks.valueAt(cbi).mFlags
376 & AppOpsManager.WATCH_FOREGROUND_CHANGES) != 0) {
377 hasForegroundWatchers = true;
378 curValue = true;
379 }
380 }
381 }
382 which.put(op, curValue);
383 }
384
385 public void evalForegroundOps(SparseArray<ArraySet<ModeCallback>> watchers) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700386 SparseBooleanArray which = null;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700387 hasForegroundWatchers = false;
388 if (opModes != null) {
389 for (int i = opModes.size() - 1; i >= 0; i--) {
390 if (opModes.valueAt(i) == AppOpsManager.MODE_FOREGROUND) {
391 if (which == null) {
392 which = new SparseBooleanArray();
393 }
394 evalForegroundWatchers(opModes.keyAt(i), watchers, which);
395 }
396 }
397 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700398 if (pkgOps != null) {
399 for (int i = pkgOps.size() - 1; i >= 0; i--) {
400 Ops ops = pkgOps.valueAt(i);
401 for (int j = ops.size() - 1; j >= 0; j--) {
402 if (ops.valueAt(j).mode == AppOpsManager.MODE_FOREGROUND) {
403 if (which == null) {
404 which = new SparseBooleanArray();
405 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700406 evalForegroundWatchers(ops.keyAt(j), watchers, which);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700407 }
408 }
409 }
410 }
411 foregroundOps = which;
412 }
Svet Ganov2af57082015-07-30 08:44:20 -0700413 }
414
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700415 final static class Ops extends SparseArray<Op> {
416 final String packageName;
417 final UidState uidState;
418 final boolean isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800419
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700420 Ops(String _packageName, UidState _uidState, boolean _isPrivileged) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800421 packageName = _packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700422 uidState = _uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400423 isPrivileged = _isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800424 }
425 }
426
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700427 final static class Op {
428 final UidState uidState;
429 final int uid;
430 final String packageName;
431 final int op;
432 int proxyUid = -1;
433 String proxyPackageName;
434 int mode;
435 int duration;
436 long time[] = new long[_NUM_UID_STATE];
437 long rejectTime[] = new long[_NUM_UID_STATE];
438 int startNesting;
439 long startRealtime;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800440
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700441 Op(UidState _uidState, String _packageName, int _op) {
442 uidState = _uidState;
443 uid = _uidState.uid;
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700444 packageName = _packageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800445 op = _op;
David Braunf5d83192013-09-16 13:43:51 -0700446 mode = AppOpsManager.opToDefaultMode(op);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800447 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700448
449 boolean hasAnyTime() {
450 for (int i = 0; i < AppOpsManager._NUM_UID_STATE; i++) {
451 if (time[i] != 0) {
452 return true;
453 }
454 if (rejectTime[i] != 0) {
455 return true;
456 }
457 }
458 return false;
459 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700460
461 int getMode() {
462 return uidState.evalMode(mode);
463 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800464 }
465
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800466 final SparseArray<ArraySet<ModeCallback>> mOpModeWatchers = new SparseArray<>();
467 final ArrayMap<String, ArraySet<ModeCallback>> mPackageModeWatchers = new ArrayMap<>();
468 final ArrayMap<IBinder, ModeCallback> mModeWatchers = new ArrayMap<>();
469 final ArrayMap<IBinder, SparseArray<ActiveCallback>> mActiveWatchers = new ArrayMap<>();
Svet Ganovb3d2ae22018-12-17 22:06:15 -0800470 final ArrayMap<IBinder, SparseArray<NotedCallback>> mNotedWatchers = new ArrayMap<>();
Dianne Hackborn68d76552017-02-27 15:32:03 -0800471 final SparseArray<SparseArray<Restriction>> mAudioRestrictions = new SparseArray<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800472
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700473 final class ModeCallback implements DeathRecipient {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800474 final IAppOpsCallback mCallback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700475 final int mWatchingUid;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700476 final int mFlags;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700477 final int mCallingUid;
478 final int mCallingPid;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800479
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700480 ModeCallback(IAppOpsCallback callback, int watchingUid, int flags, int callingUid,
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700481 int callingPid) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800482 mCallback = callback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700483 mWatchingUid = watchingUid;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700484 mFlags = flags;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700485 mCallingUid = callingUid;
486 mCallingPid = callingPid;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800487 try {
488 mCallback.asBinder().linkToDeath(this, 0);
489 } catch (RemoteException e) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -0800490 /*ignored*/
Dianne Hackbornc2293022013-02-06 23:14:49 -0800491 }
492 }
493
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700494 public boolean isWatchingUid(int uid) {
495 return uid == UID_ANY || mWatchingUid < 0 || mWatchingUid == uid;
496 }
497
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700498 @Override
499 public String toString() {
500 StringBuilder sb = new StringBuilder(128);
501 sb.append("ModeCallback{");
502 sb.append(Integer.toHexString(System.identityHashCode(this)));
503 sb.append(" watchinguid=");
504 UserHandle.formatUid(sb, mWatchingUid);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700505 sb.append(" flags=0x");
506 sb.append(Integer.toHexString(mFlags));
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700507 sb.append(" from uid=");
508 UserHandle.formatUid(sb, mCallingUid);
509 sb.append(" pid=");
510 sb.append(mCallingPid);
511 sb.append('}');
512 return sb.toString();
513 }
514
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700515 void unlinkToDeath() {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800516 mCallback.asBinder().unlinkToDeath(this, 0);
517 }
518
519 @Override
520 public void binderDied() {
521 stopWatchingMode(mCallback);
522 }
523 }
524
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700525 final class ActiveCallback implements DeathRecipient {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800526 final IAppOpsActiveCallback mCallback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700527 final int mWatchingUid;
528 final int mCallingUid;
529 final int mCallingPid;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800530
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700531 ActiveCallback(IAppOpsActiveCallback callback, int watchingUid, int callingUid,
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700532 int callingPid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800533 mCallback = callback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700534 mWatchingUid = watchingUid;
535 mCallingUid = callingUid;
536 mCallingPid = callingPid;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800537 try {
538 mCallback.asBinder().linkToDeath(this, 0);
539 } catch (RemoteException e) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -0800540 /*ignored*/
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800541 }
542 }
543
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700544 @Override
545 public String toString() {
546 StringBuilder sb = new StringBuilder(128);
547 sb.append("ActiveCallback{");
548 sb.append(Integer.toHexString(System.identityHashCode(this)));
549 sb.append(" watchinguid=");
550 UserHandle.formatUid(sb, mWatchingUid);
551 sb.append(" from uid=");
552 UserHandle.formatUid(sb, mCallingUid);
553 sb.append(" pid=");
554 sb.append(mCallingPid);
555 sb.append('}');
556 return sb.toString();
557 }
558
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700559 void destroy() {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800560 mCallback.asBinder().unlinkToDeath(this, 0);
561 }
562
563 @Override
564 public void binderDied() {
565 stopWatchingActive(mCallback);
566 }
567 }
568
Svet Ganovb3d2ae22018-12-17 22:06:15 -0800569 final class NotedCallback implements DeathRecipient {
570 final IAppOpsNotedCallback mCallback;
571 final int mWatchingUid;
572 final int mCallingUid;
573 final int mCallingPid;
574
575 NotedCallback(IAppOpsNotedCallback callback, int watchingUid, int callingUid,
576 int callingPid) {
577 mCallback = callback;
578 mWatchingUid = watchingUid;
579 mCallingUid = callingUid;
580 mCallingPid = callingPid;
581 try {
582 mCallback.asBinder().linkToDeath(this, 0);
583 } catch (RemoteException e) {
584 /*ignored*/
585 }
586 }
587
588 @Override
589 public String toString() {
590 StringBuilder sb = new StringBuilder(128);
591 sb.append("NotedCallback{");
592 sb.append(Integer.toHexString(System.identityHashCode(this)));
593 sb.append(" watchinguid=");
594 UserHandle.formatUid(sb, mWatchingUid);
595 sb.append(" from uid=");
596 UserHandle.formatUid(sb, mCallingUid);
597 sb.append(" pid=");
598 sb.append(mCallingPid);
599 sb.append('}');
600 return sb.toString();
601 }
602
603 void destroy() {
604 mCallback.asBinder().unlinkToDeath(this, 0);
605 }
606
607 @Override
608 public void binderDied() {
609 stopWatchingNoted(mCallback);
610 }
611 }
612
Svet Ganova7a0db62018-02-27 20:08:01 -0800613 final ArrayMap<IBinder, ClientState> mClients = new ArrayMap<>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700614
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700615 final class ClientState extends Binder implements DeathRecipient {
Svet Ganovf7b47252018-02-26 11:11:27 -0800616 final ArrayList<Op> mStartedOps = new ArrayList<>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700617 final IBinder mAppToken;
618 final int mPid;
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700619
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700620 ClientState(IBinder appToken) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700621 mAppToken = appToken;
622 mPid = Binder.getCallingPid();
Svet Ganovf7b47252018-02-26 11:11:27 -0800623 // Watch only for remote processes dying
624 if (!(appToken instanceof Binder)) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700625 try {
626 mAppToken.linkToDeath(this, 0);
627 } catch (RemoteException e) {
Svet Ganovf7b47252018-02-26 11:11:27 -0800628 /* do nothing */
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700629 }
630 }
631 }
632
633 @Override
634 public String toString() {
635 return "ClientState{" +
636 "mAppToken=" + mAppToken +
Svet Ganovf7b47252018-02-26 11:11:27 -0800637 ", " + "pid=" + mPid +
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700638 '}';
639 }
640
641 @Override
642 public void binderDied() {
643 synchronized (AppOpsService.this) {
644 for (int i=mStartedOps.size()-1; i>=0; i--) {
Svet Ganova7a0db62018-02-27 20:08:01 -0800645 finishOperationLocked(mStartedOps.get(i), /*finishNested*/ true);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700646 }
647 mClients.remove(mAppToken);
648 }
649 }
650 }
651
Jeff Brown6f357d32014-01-15 20:40:55 -0800652 public AppOpsService(File storagePath, Handler handler) {
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600653 LockGuard.installLock(this, LockGuard.INDEX_APP_OPS);
Dianne Hackborne17b4452018-01-10 13:15:40 -0800654 mFile = new AtomicFile(storagePath, "appops");
Jeff Brown6f357d32014-01-15 20:40:55 -0800655 mHandler = handler;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700656 mConstants = new Constants(mHandler);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800657 readState();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800658 }
David Braunf5d83192013-09-16 13:43:51 -0700659
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800660 public void publish(Context context) {
661 mContext = context;
662 ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
Dianne Hackbornd5254412018-05-11 18:02:58 -0700663 LocalServices.addService(AppOpsManagerInternal.class, mAppOpsManagerInternal);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800664 }
665
Dianne Hackborn514074f2013-02-11 10:52:46 -0800666 public void systemReady() {
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700667 mConstants.startMonitoring(mContext.getContentResolver());
Svet Ganov8455ba22019-01-02 13:05:56 -0800668 mHistoricalRegistry.systemReady(mContext.getContentResolver());
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700669
Dianne Hackborn514074f2013-02-11 10:52:46 -0800670 synchronized (this) {
671 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700672 for (int i = mUidStates.size() - 1; i >= 0; i--) {
673 UidState uidState = mUidStates.valueAt(i);
674
675 String[] packageNames = getPackagesForUid(uidState.uid);
676 if (ArrayUtils.isEmpty(packageNames)) {
677 uidState.clear();
678 mUidStates.removeAt(i);
679 changed = true;
680 continue;
681 }
682
683 ArrayMap<String, Ops> pkgs = uidState.pkgOps;
684 if (pkgs == null) {
685 continue;
686 }
687
Dianne Hackborn514074f2013-02-11 10:52:46 -0800688 Iterator<Ops> it = pkgs.values().iterator();
689 while (it.hasNext()) {
690 Ops ops = it.next();
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700691 int curUid = -1;
Dianne Hackborn514074f2013-02-11 10:52:46 -0800692 try {
Jeff Sharkeycd654482016-01-08 17:42:11 -0700693 curUid = AppGlobals.getPackageManager().getPackageUid(ops.packageName,
694 PackageManager.MATCH_UNINSTALLED_PACKAGES,
Svet Ganov2af57082015-07-30 08:44:20 -0700695 UserHandle.getUserId(ops.uidState.uid));
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700696 } catch (RemoteException ignored) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800697 }
Svet Ganov2af57082015-07-30 08:44:20 -0700698 if (curUid != ops.uidState.uid) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800699 Slog.i(TAG, "Pruning old package " + ops.packageName
Svet Ganov2af57082015-07-30 08:44:20 -0700700 + "/" + ops.uidState + ": new uid=" + curUid);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800701 it.remove();
702 changed = true;
703 }
704 }
Svet Ganov2af57082015-07-30 08:44:20 -0700705
706 if (uidState.isDefault()) {
707 mUidStates.removeAt(i);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800708 }
709 }
710 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800711 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800712 }
713 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700714
Suprabh Shukla3017fe42018-11-08 19:00:01 -0800715 final IntentFilter packageSuspendFilter = new IntentFilter();
716 packageSuspendFilter.addAction(Intent.ACTION_PACKAGES_UNSUSPENDED);
717 packageSuspendFilter.addAction(Intent.ACTION_PACKAGES_SUSPENDED);
718 mContext.registerReceiver(new BroadcastReceiver() {
719 @Override
720 public void onReceive(Context context, Intent intent) {
721 final int[] changedUids = intent.getIntArrayExtra(Intent.EXTRA_CHANGED_UID_LIST);
722 final String[] changedPkgs = intent.getStringArrayExtra(
723 Intent.EXTRA_CHANGED_PACKAGE_LIST);
724 final ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(OP_PLAY_AUDIO);
725 for (int i = 0; i < changedUids.length; i++) {
726 final int changedUid = changedUids[i];
727 final String changedPkg = changedPkgs[i];
728 // We trust packagemanager to insert matching uid and packageNames in the extras
729 mHandler.sendMessage(PooledLambda.obtainMessage(AppOpsService::notifyOpChanged,
730 AppOpsService.this, callbacks, OP_PLAY_AUDIO, changedUid, changedPkg));
731 }
732 }
733 }, packageSuspendFilter);
734
Suprabh Shuklaaef25132017-01-23 18:09:03 -0800735 PackageManagerInternal packageManagerInternal = LocalServices.getService(
736 PackageManagerInternal.class);
737 packageManagerInternal.setExternalSourcesPolicy(
738 new PackageManagerInternal.ExternalSourcesPolicy() {
739 @Override
740 public int getPackageTrustedToInstallApps(String packageName, int uid) {
741 int appOpMode = checkOperation(AppOpsManager.OP_REQUEST_INSTALL_PACKAGES,
742 uid, packageName);
743 switch (appOpMode) {
744 case AppOpsManager.MODE_ALLOWED:
745 return PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
746 case AppOpsManager.MODE_ERRORED:
747 return PackageManagerInternal.ExternalSourcesPolicy.USER_BLOCKED;
748 default:
749 return PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT;
750 }
751 }
752 });
753
Jeff Sharkey10ec9d82018-11-28 14:52:45 -0700754 if (!StorageManager.hasIsolatedStorage()) {
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700755 StorageManagerInternal storageManagerInternal = LocalServices.getService(
756 StorageManagerInternal.class);
757 storageManagerInternal.addExternalStoragePolicy(
758 new StorageManagerInternal.ExternalStorageMountPolicy() {
759 @Override
760 public int getMountMode(int uid, String packageName) {
761 if (Process.isIsolated(uid)) {
762 return Zygote.MOUNT_EXTERNAL_NONE;
763 }
764 if (noteOperation(AppOpsManager.OP_READ_EXTERNAL_STORAGE, uid,
765 packageName) != AppOpsManager.MODE_ALLOWED) {
766 return Zygote.MOUNT_EXTERNAL_NONE;
767 }
768 if (noteOperation(AppOpsManager.OP_WRITE_EXTERNAL_STORAGE, uid,
769 packageName) != AppOpsManager.MODE_ALLOWED) {
770 return Zygote.MOUNT_EXTERNAL_READ;
771 }
772 return Zygote.MOUNT_EXTERNAL_WRITE;
Svet Ganov6ee871e2015-07-10 14:29:33 -0700773 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700774
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700775 @Override
776 public boolean hasExternalStorage(int uid, String packageName) {
777 final int mountMode = getMountMode(uid, packageName);
778 return mountMode == Zygote.MOUNT_EXTERNAL_READ
779 || mountMode == Zygote.MOUNT_EXTERNAL_WRITE;
780 }
781 });
782 }
Dianne Hackborn514074f2013-02-11 10:52:46 -0800783 }
784
785 public void packageRemoved(int uid, String packageName) {
786 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700787 UidState uidState = mUidStates.get(uid);
788 if (uidState == null) {
789 return;
790 }
791
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800792 Ops ops = null;
Svet Ganov2af57082015-07-30 08:44:20 -0700793
794 // Remove any package state if such.
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800795 if (uidState.pkgOps != null) {
796 ops = uidState.pkgOps.remove(packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700797 }
798
799 // If we just nuked the last package state check if the UID is valid.
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800800 if (ops != null && uidState.pkgOps.isEmpty()
Svet Ganov2af57082015-07-30 08:44:20 -0700801 && getPackagesForUid(uid).length <= 0) {
802 mUidStates.remove(uid);
803 }
804
Svet Ganova7a0db62018-02-27 20:08:01 -0800805 // Finish ops other packages started on behalf of the package.
806 final int clientCount = mClients.size();
807 for (int i = 0; i < clientCount; i++) {
808 final ClientState client = mClients.valueAt(i);
809 if (client.mStartedOps == null) {
810 continue;
811 }
812 final int opCount = client.mStartedOps.size();
813 for (int j = opCount - 1; j >= 0; j--) {
814 final Op op = client.mStartedOps.get(j);
815 if (uid == op.uid && packageName.equals(op.packageName)) {
816 finishOperationLocked(op, /*finishNested*/ true);
817 client.mStartedOps.remove(j);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700818 if (op.startNesting <= 0) {
Svet Ganova7a0db62018-02-27 20:08:01 -0800819 scheduleOpActiveChangedIfNeededLocked(op.op,
820 uid, packageName, false);
821 }
822 }
823 }
824 }
825
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800826 if (ops != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700827 scheduleFastWriteLocked();
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800828
829 final int opCount = ops.size();
830 for (int i = 0; i < opCount; i++) {
831 final Op op = ops.valueAt(i);
832 if (op.duration == -1) {
833 scheduleOpActiveChangedIfNeededLocked(
834 op.op, op.uid, op.packageName, false);
835 }
836 }
Dianne Hackborn514074f2013-02-11 10:52:46 -0800837 }
838 }
839 }
840
841 public void uidRemoved(int uid) {
842 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700843 if (mUidStates.indexOfKey(uid) >= 0) {
844 mUidStates.remove(uid);
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800845 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800846 }
847 }
848 }
849
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700850 public void updateUidProcState(int uid, int procState) {
851 synchronized (this) {
852 final UidState uidState = getUidStateLocked(uid, true);
Amith Yamasania0a30a12019-01-22 11:38:06 -0800853 int newState = PROCESS_STATE_TO_UID_STATE[procState];
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700854 if (uidState != null && uidState.pendingState != newState) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700855 final int oldPendingState = uidState.pendingState;
856 uidState.pendingState = newState;
Dianne Hackborne93ab412018-05-14 17:52:30 -0700857 if (newState < uidState.state || newState <= UID_STATE_LAST_NON_RESTRICTED) {
858 // We are moving to a more important state, or the new state is in the
859 // foreground, then always do it immediately.
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700860 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700861 } else if (uidState.pendingStateCommitTime == 0) {
862 // We are moving to a less important state for the first time,
863 // delay the application for a bit.
Dianne Hackborne93ab412018-05-14 17:52:30 -0700864 final long settleTime;
865 if (uidState.state <= UID_STATE_TOP) {
866 settleTime = mConstants.TOP_STATE_SETTLE_TIME;
867 } else if (uidState.state <= UID_STATE_FOREGROUND_SERVICE) {
868 settleTime = mConstants.FG_SERVICE_STATE_SETTLE_TIME;
869 } else {
870 settleTime = mConstants.BG_STATE_SETTLE_TIME;
871 }
Dianne Hackborn9fb93502018-06-18 12:29:44 -0700872 uidState.pendingStateCommitTime = SystemClock.elapsedRealtime() + settleTime;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700873 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700874 if (uidState.startNesting != 0) {
875 // There is some actively running operation... need to find it
876 // and appropriately update its state.
877 final long now = System.currentTimeMillis();
878 for (int i = uidState.pkgOps.size() - 1; i >= 0; i--) {
879 final Ops ops = uidState.pkgOps.valueAt(i);
880 for (int j = ops.size() - 1; j >= 0; j--) {
881 final Op op = ops.valueAt(j);
882 if (op.startNesting > 0) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700883 op.time[oldPendingState] = now;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700884 op.time[newState] = now;
885 }
886 }
887 }
888 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700889 }
890 }
891 }
892
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800893 public void shutdown() {
894 Slog.w(TAG, "Writing app ops before shutdown...");
Dianne Hackborn35654b62013-01-14 17:38:02 -0800895 boolean doWrite = false;
896 synchronized (this) {
897 if (mWriteScheduled) {
898 mWriteScheduled = false;
899 doWrite = true;
900 }
901 }
902 if (doWrite) {
903 writeState();
904 }
905 }
906
Dianne Hackborn72e39832013-01-18 18:36:09 -0800907 private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
908 ArrayList<AppOpsManager.OpEntry> resOps = null;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700909 final long elapsedNow = SystemClock.elapsedRealtime();
Dianne Hackborn72e39832013-01-18 18:36:09 -0800910 if (ops == null) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700911 resOps = new ArrayList<>();
Dianne Hackborn72e39832013-01-18 18:36:09 -0800912 for (int j=0; j<pkgOps.size(); j++) {
913 Op curOp = pkgOps.valueAt(j);
Amith Yamasania1ce9632018-05-28 20:50:48 -0700914 final boolean running = curOp.duration == -1;
915 long duration = running
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700916 ? (elapsedNow - curOp.startRealtime)
917 : curOp.duration;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800918 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Amith Yamasania1ce9632018-05-28 20:50:48 -0700919 curOp.rejectTime, (int) duration, running, curOp.proxyUid,
Svet Ganov99b60432015-06-27 13:15:22 -0700920 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800921 }
922 } else {
923 for (int j=0; j<ops.length; j++) {
924 Op curOp = pkgOps.get(ops[j]);
925 if (curOp != null) {
926 if (resOps == null) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700927 resOps = new ArrayList<>();
Dianne Hackborn72e39832013-01-18 18:36:09 -0800928 }
Amith Yamasania1ce9632018-05-28 20:50:48 -0700929 final boolean running = curOp.duration == -1;
930 final long duration = running
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700931 ? (elapsedNow - curOp.startRealtime)
932 : curOp.duration;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800933 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Amith Yamasania1ce9632018-05-28 20:50:48 -0700934 curOp.rejectTime, (int) duration, running, curOp.proxyUid,
Svet Ganov99b60432015-06-27 13:15:22 -0700935 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800936 }
937 }
938 }
939 return resOps;
940 }
941
Dianne Hackbornc7214a32017-04-11 13:32:47 -0700942 private ArrayList<AppOpsManager.OpEntry> collectOps(SparseIntArray uidOps, int[] ops) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -0800943 if (uidOps == null) {
944 return null;
945 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -0700946 ArrayList<AppOpsManager.OpEntry> resOps = null;
947 if (ops == null) {
948 resOps = new ArrayList<>();
949 for (int j=0; j<uidOps.size(); j++) {
950 resOps.add(new AppOpsManager.OpEntry(uidOps.keyAt(j), uidOps.valueAt(j),
951 0, 0, 0, -1, null));
952 }
953 } else {
954 for (int j=0; j<ops.length; j++) {
955 int index = uidOps.indexOfKey(ops[j]);
956 if (index >= 0) {
957 if (resOps == null) {
958 resOps = new ArrayList<>();
959 }
960 resOps.add(new AppOpsManager.OpEntry(uidOps.keyAt(index), uidOps.valueAt(index),
961 0, 0, 0, -1, null));
962 }
963 }
964 }
965 return resOps;
966 }
967
Dianne Hackborn35654b62013-01-14 17:38:02 -0800968 @Override
969 public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
970 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
971 Binder.getCallingPid(), Binder.getCallingUid(), null);
972 ArrayList<AppOpsManager.PackageOps> res = null;
973 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700974 final int uidStateCount = mUidStates.size();
975 for (int i = 0; i < uidStateCount; i++) {
976 UidState uidState = mUidStates.valueAt(i);
977 if (uidState.pkgOps == null || uidState.pkgOps.isEmpty()) {
978 continue;
979 }
980 ArrayMap<String, Ops> packages = uidState.pkgOps;
981 final int packageCount = packages.size();
982 for (int j = 0; j < packageCount; j++) {
983 Ops pkgOps = packages.valueAt(j);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800984 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800985 if (resOps != null) {
986 if (res == null) {
987 res = new ArrayList<AppOpsManager.PackageOps>();
988 }
989 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700990 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800991 res.add(resPackage);
992 }
993 }
994 }
995 }
996 return res;
997 }
998
999 @Override
Dianne Hackborn72e39832013-01-18 18:36:09 -08001000 public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
1001 int[] ops) {
1002 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
1003 Binder.getCallingPid(), Binder.getCallingUid(), null);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001004 String resolvedPackageName = resolvePackageName(uid, packageName);
1005 if (resolvedPackageName == null) {
1006 return Collections.emptyList();
1007 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08001008 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001009 Ops pkgOps = getOpsRawLocked(uid, resolvedPackageName, false /* edit */,
1010 false /* uidMismatchExpected */);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001011 if (pkgOps == null) {
1012 return null;
1013 }
1014 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
1015 if (resOps == null) {
1016 return null;
1017 }
1018 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
1019 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -07001020 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001021 res.add(resPackage);
1022 return res;
1023 }
1024 }
1025
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001026 @Override
Svet Ganov8455ba22019-01-02 13:05:56 -08001027 public void getHistoricalOps(int uid, @NonNull String packageName,
Svet Ganov23c88db2019-01-22 20:38:11 -08001028 @Nullable List<String> opNames, long beginTimeMillis, long endTimeMillis,
Svet Ganov8455ba22019-01-02 13:05:56 -08001029 @NonNull RemoteCallback callback) {
Svet Ganov23c88db2019-01-22 20:38:11 -08001030 // Use the builder to validate arguments.
1031 final HistoricalOpsRequest request = new HistoricalOpsRequest.Builder(
1032 beginTimeMillis, endTimeMillis)
1033 .setUid(uid)
1034 .setPackageName(packageName)
1035 .setOpNames(opNames)
1036 .build();
Svet Ganov8455ba22019-01-02 13:05:56 -08001037 Preconditions.checkNotNull(callback, "callback cannot be null");
Svet Ganovad0a49b2018-10-29 10:07:08 -07001038
1039 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
Svet Ganov8455ba22019-01-02 13:05:56 -08001040 Binder.getCallingPid(), Binder.getCallingUid(), "getHistoricalOps");
Svet Ganovad0a49b2018-10-29 10:07:08 -07001041
Svet Ganov23c88db2019-01-22 20:38:11 -08001042 final String[] opNamesArray = (opNames != null)
1043 ? opNames.toArray(new String[opNames.size()]) : null;
Svet Ganov8455ba22019-01-02 13:05:56 -08001044 if (mHistoricalRegistry.getMode() == AppOpsManager.HISTORICAL_MODE_DISABLED) {
1045 // TODO (bug:122218838): Remove once the feature fully enabled.
Svet Ganov23c88db2019-01-22 20:38:11 -08001046 getHistoricalPackagesOpsCompat(uid, packageName, opNamesArray, beginTimeMillis,
Svet Ganov8455ba22019-01-02 13:05:56 -08001047 endTimeMillis, callback);
1048 } else {
1049 // Must not hold the appops lock
Svet Ganov23c88db2019-01-22 20:38:11 -08001050 mHistoricalRegistry.getHistoricalOps(uid, packageName, opNamesArray,
Svet Ganov8455ba22019-01-02 13:05:56 -08001051 beginTimeMillis, endTimeMillis, callback);
Svet Ganovad0a49b2018-10-29 10:07:08 -07001052 }
Svet Ganovad0a49b2018-10-29 10:07:08 -07001053 }
1054
Svet Ganov8455ba22019-01-02 13:05:56 -08001055 private void getHistoricalPackagesOpsCompat(int uid, @NonNull String packageName,
1056 @Nullable String[] opNames, long beginTimeMillis, long endTimeMillis,
1057 @NonNull RemoteCallback callback) {
1058 synchronized (AppOpsService.this) {
1059 final HistoricalOps ops = new HistoricalOps(beginTimeMillis, endTimeMillis);
1060 if (opNames == null) {
1061 opNames = AppOpsManager.getOpStrs();
1062 }
1063 final int uidStateCount = mUidStates.size();
1064 for (int uidIdx = 0; uidIdx < uidStateCount; uidIdx++) {
1065 final UidState uidState = mUidStates.valueAt(uidIdx);
1066 if (uidState.pkgOps == null || uidState.pkgOps.isEmpty()
1067 || (uid != Process.INVALID_UID && uid != uidState.uid)) {
1068 continue;
1069 }
1070 final ArrayMap<String, Ops> packages = uidState.pkgOps;
1071 final int packageCount = packages.size();
1072 for (int pkgIdx = 0; pkgIdx < packageCount; pkgIdx++) {
1073 final Ops pkgOps = packages.valueAt(pkgIdx);
1074 if (packageName != null && !packageName.equals(pkgOps.packageName)) {
1075 continue;
1076 }
1077 final int opCount = opNames.length;
1078 for (int opIdx = 0; opIdx < opCount; opIdx++) {
1079 final String opName = opNames[opIdx];
1080 if (!ArrayUtils.contains(opNames, opName)) {
1081 continue;
1082 }
1083 final int opCode = AppOpsManager.strOpToOp(opName);
1084 final Op op = pkgOps.get(opCode);
1085 if (op == null) {
1086 continue;
1087 }
1088 final int stateCount = AppOpsManager._NUM_UID_STATE;
1089 for (int stateIdx = 0; stateIdx < stateCount; stateIdx++) {
1090 if (op.rejectTime[stateIdx] != 0) {
1091 ops.increaseRejectCount(opCode, uidState.uid,
1092 pkgOps.packageName, stateIdx, 1);
1093 } else if (op.time[stateIdx] != 0) {
1094 ops.increaseAccessCount(opCode, uidState.uid,
1095 pkgOps.packageName, stateIdx, 1);
1096 }
1097 }
1098 }
1099 }
1100 }
1101 final Bundle payload = new Bundle();
1102 payload.putParcelable(AppOpsManager.KEY_HISTORICAL_OPS, ops);
1103 callback.sendResult(payload);
Svet Ganovad0a49b2018-10-29 10:07:08 -07001104 }
Svet Ganovad0a49b2018-10-29 10:07:08 -07001105 }
1106
1107 @Override
Svet Ganov8455ba22019-01-02 13:05:56 -08001108 public void getHistoricalOpsFromDiskRaw(int uid, @NonNull String packageName,
Svet Ganov23c88db2019-01-22 20:38:11 -08001109 @Nullable List<String> opNames, long beginTimeMillis, long endTimeMillis,
Svet Ganov8455ba22019-01-02 13:05:56 -08001110 @NonNull RemoteCallback callback) {
Svet Ganov23c88db2019-01-22 20:38:11 -08001111 // Use the builder to validate arguments.
1112 final HistoricalOpsRequest request = new HistoricalOpsRequest.Builder(
1113 beginTimeMillis, endTimeMillis)
1114 .setUid(uid)
1115 .setPackageName(packageName)
1116 .setOpNames(opNames)
1117 .build();
Svet Ganov8455ba22019-01-02 13:05:56 -08001118 Preconditions.checkNotNull(callback, "callback cannot be null");
Svet Ganovad0a49b2018-10-29 10:07:08 -07001119
1120 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
Svet Ganov8455ba22019-01-02 13:05:56 -08001121 Binder.getCallingPid(), Binder.getCallingUid(), "getHistoricalOps");
Svet Ganovad0a49b2018-10-29 10:07:08 -07001122
Svet Ganov23c88db2019-01-22 20:38:11 -08001123 final String[] opNamesArray = (opNames != null)
1124 ? opNames.toArray(new String[opNames.size()]) : null;
1125
Svet Ganov8455ba22019-01-02 13:05:56 -08001126 // Must not hold the appops lock
Svet Ganov23c88db2019-01-22 20:38:11 -08001127 mHistoricalRegistry.getHistoricalOpsFromDiskRaw(uid, packageName, opNamesArray,
Svet Ganov8455ba22019-01-02 13:05:56 -08001128 beginTimeMillis, endTimeMillis, callback);
Svet Ganovad0a49b2018-10-29 10:07:08 -07001129 }
1130
1131 @Override
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001132 public List<AppOpsManager.PackageOps> getUidOps(int uid, int[] ops) {
1133 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
1134 Binder.getCallingPid(), Binder.getCallingUid(), null);
1135 synchronized (this) {
1136 UidState uidState = getUidStateLocked(uid, false);
1137 if (uidState == null) {
1138 return null;
1139 }
1140 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(uidState.opModes, ops);
1141 if (resOps == null) {
1142 return null;
1143 }
1144 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
1145 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
1146 null, uidState.uid, resOps);
1147 res.add(resPackage);
1148 return res;
1149 }
1150 }
1151
Dianne Hackborn607b4142013-08-02 18:10:10 -07001152 private void pruneOp(Op op, int uid, String packageName) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001153 if (!op.hasAnyTime()) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001154 Ops ops = getOpsRawLocked(uid, packageName, false /* edit */,
1155 false /* uidMismatchExpected */);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001156 if (ops != null) {
1157 ops.remove(op.op);
1158 if (ops.size() <= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -07001159 UidState uidState = ops.uidState;
1160 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
Dianne Hackborn607b4142013-08-02 18:10:10 -07001161 if (pkgOps != null) {
1162 pkgOps.remove(ops.packageName);
Svet Ganov2af57082015-07-30 08:44:20 -07001163 if (pkgOps.isEmpty()) {
1164 uidState.pkgOps = null;
1165 }
1166 if (uidState.isDefault()) {
1167 mUidStates.remove(uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001168 }
1169 }
1170 }
1171 }
1172 }
1173 }
1174
Dianne Hackbornd5254412018-05-11 18:02:58 -07001175 void enforceManageAppOpsModes(int callingPid, int callingUid, int targetUid) {
1176 if (callingPid == Process.myPid()) {
1177 return;
1178 }
1179 final int callingUser = UserHandle.getUserId(callingUid);
1180 synchronized (this) {
1181 if (mProfileOwners != null && mProfileOwners.get(callingUser, -1) == callingUid) {
1182 if (targetUid >= 0 && callingUser == UserHandle.getUserId(targetUid)) {
1183 // Profile owners are allowed to change modes but only for apps
1184 // within their user.
1185 return;
1186 }
1187 }
1188 }
1189 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
1190 Binder.getCallingPid(), Binder.getCallingUid(), null);
1191 }
1192
Dianne Hackborn72e39832013-01-18 18:36:09 -08001193 @Override
Svet Ganov2af57082015-07-30 08:44:20 -07001194 public void setUidMode(int code, int uid, int mode) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08001195 if (DEBUG) {
1196 Slog.i(TAG, "uid " + uid + " OP_" + opToName(code) + " := " + modeToName(mode)
1197 + " by uid " + Binder.getCallingUid());
1198 }
1199
Dianne Hackbornd5254412018-05-11 18:02:58 -07001200 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
Svet Ganov2af57082015-07-30 08:44:20 -07001201 verifyIncomingOp(code);
1202 code = AppOpsManager.opToSwitch(code);
1203
1204 synchronized (this) {
1205 final int defaultMode = AppOpsManager.opToDefaultMode(code);
1206
1207 UidState uidState = getUidStateLocked(uid, false);
1208 if (uidState == null) {
1209 if (mode == defaultMode) {
1210 return;
1211 }
1212 uidState = new UidState(uid);
1213 uidState.opModes = new SparseIntArray();
1214 uidState.opModes.put(code, mode);
1215 mUidStates.put(uid, uidState);
1216 scheduleWriteLocked();
1217 } else if (uidState.opModes == null) {
1218 if (mode != defaultMode) {
1219 uidState.opModes = new SparseIntArray();
1220 uidState.opModes.put(code, mode);
1221 scheduleWriteLocked();
1222 }
1223 } else {
Hai Zhang2b98fb32018-09-21 15:18:46 -07001224 if (uidState.opModes.indexOfKey(code) >= 0 && uidState.opModes.get(code) == mode) {
Svet Ganov2af57082015-07-30 08:44:20 -07001225 return;
1226 }
1227 if (mode == defaultMode) {
1228 uidState.opModes.delete(code);
1229 if (uidState.opModes.size() <= 0) {
1230 uidState.opModes = null;
1231 }
1232 } else {
1233 uidState.opModes.put(code, mode);
1234 }
1235 scheduleWriteLocked();
1236 }
1237 }
1238
Svetoslav215b44a2015-08-04 19:03:40 -07001239 String[] uidPackageNames = getPackagesForUid(uid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001240 ArrayMap<ModeCallback, ArraySet<String>> callbackSpecs = null;
Svet Ganov2af57082015-07-30 08:44:20 -07001241
riddle_hsu40b300f2015-11-23 13:22:03 +08001242 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001243 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001244 if (callbacks != null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001245 final int callbackCount = callbacks.size();
1246 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001247 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +08001248 ArraySet<String> changedPackages = new ArraySet<>();
1249 Collections.addAll(changedPackages, uidPackageNames);
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001250 if (callbackSpecs == null) {
1251 callbackSpecs = new ArrayMap<>();
1252 }
riddle_hsu40b300f2015-11-23 13:22:03 +08001253 callbackSpecs.put(callback, changedPackages);
1254 }
1255 }
1256
1257 for (String uidPackageName : uidPackageNames) {
1258 callbacks = mPackageModeWatchers.get(uidPackageName);
1259 if (callbacks != null) {
1260 if (callbackSpecs == null) {
1261 callbackSpecs = new ArrayMap<>();
Svet Ganov2af57082015-07-30 08:44:20 -07001262 }
riddle_hsu40b300f2015-11-23 13:22:03 +08001263 final int callbackCount = callbacks.size();
1264 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001265 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +08001266 ArraySet<String> changedPackages = callbackSpecs.get(callback);
1267 if (changedPackages == null) {
1268 changedPackages = new ArraySet<>();
1269 callbackSpecs.put(callback, changedPackages);
1270 }
1271 changedPackages.add(uidPackageName);
1272 }
Svet Ganov2af57082015-07-30 08:44:20 -07001273 }
1274 }
1275 }
1276
1277 if (callbackSpecs == null) {
1278 return;
1279 }
1280
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001281 for (int i = 0; i < callbackSpecs.size(); i++) {
1282 final ModeCallback callback = callbackSpecs.keyAt(i);
1283 final ArraySet<String> reportedPackageNames = callbackSpecs.valueAt(i);
1284 if (reportedPackageNames == null) {
1285 mHandler.sendMessage(PooledLambda.obtainMessage(
1286 AppOpsService::notifyOpChanged,
1287 this, callback, code, uid, (String) null));
1288
1289 } else {
1290 final int reportedPackageCount = reportedPackageNames.size();
1291 for (int j = 0; j < reportedPackageCount; j++) {
1292 final String reportedPackageName = reportedPackageNames.valueAt(j);
1293 mHandler.sendMessage(PooledLambda.obtainMessage(
1294 AppOpsService::notifyOpChanged,
1295 this, callback, code, uid, reportedPackageName));
Svet Ganov2af57082015-07-30 08:44:20 -07001296 }
1297 }
Svet Ganov2af57082015-07-30 08:44:20 -07001298 }
1299 }
1300
Philip P. Moltmanndde07852019-01-25 16:42:36 -08001301 /**
1302 * Set all {@link #setMode (package) modes} for this uid to the default value.
1303 *
1304 * @param code The app-op
1305 * @param uid The uid
1306 */
1307 private void setAllPkgModesToDefault(int code, int uid) {
1308 synchronized (this) {
1309 UidState uidState = getUidStateLocked(uid, false);
1310 if (uidState == null) {
1311 return;
1312 }
1313
1314 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
1315 if (pkgOps == null) {
1316 return;
1317 }
1318
1319 int numPkgs = pkgOps.size();
1320 for (int pkgNum = 0; pkgNum < numPkgs; pkgNum++) {
1321 Ops ops = pkgOps.valueAt(pkgNum);
1322
1323 Op op = ops.get(code);
1324 if (op == null) {
1325 continue;
1326 }
1327
1328 int defaultMode = AppOpsManager.opToDefaultMode(code);
1329 if (op.mode != defaultMode) {
1330 Slog.w(TAG, "resetting app-op mode for " + AppOpsManager.opToName(code) + " of "
1331 + pkgOps.keyAt(pkgNum));
1332
1333 op.mode = defaultMode;
1334
1335 scheduleWriteLocked();
1336 }
1337 }
1338 }
1339 }
1340
Svet Ganov2af57082015-07-30 08:44:20 -07001341 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001342 public void setMode(int code, int uid, String packageName, int mode) {
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07001343 setMode(code, uid, packageName, mode, true, false);
1344 }
1345
1346 /**
1347 * Sets the mode for a certain op and uid.
1348 *
1349 * @param code The op code to set
1350 * @param uid The UID for which to set
1351 * @param packageName The package for which to set
1352 * @param mode The new mode to set
1353 * @param verifyUid Iff {@code true}, check that the package name belongs to the uid
1354 * @param isPrivileged Whether the package is privileged. (Only used if {@code verifyUid ==
1355 * false})
1356 */
1357 private void setMode(int code, int uid, @NonNull String packageName, int mode,
1358 boolean verifyUid, boolean isPrivileged) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07001359 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001360 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001361 ArraySet<ModeCallback> repCbs = null;
Dianne Hackbornc2293022013-02-06 23:14:49 -08001362 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001363 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -07001364 UidState uidState = getUidStateLocked(uid, false);
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07001365 Op op = getOpLocked(code, uid, packageName, true, verifyUid, isPrivileged);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001366 if (op != null) {
1367 if (op.mode != mode) {
1368 op.mode = mode;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001369 if (uidState != null) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001370 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001371 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001372 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001373 if (cbs != null) {
1374 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001375 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001376 }
1377 repCbs.addAll(cbs);
1378 }
1379 cbs = mPackageModeWatchers.get(packageName);
1380 if (cbs != null) {
1381 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001382 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001383 }
1384 repCbs.addAll(cbs);
1385 }
David Braunf5d83192013-09-16 13:43:51 -07001386 if (mode == AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001387 // If going into the default mode, prune this op
1388 // if there is nothing else interesting in it.
Dianne Hackborn607b4142013-08-02 18:10:10 -07001389 pruneOp(op, uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001390 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001391 scheduleFastWriteLocked();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001392 }
1393 }
1394 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001395 if (repCbs != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001396 mHandler.sendMessage(PooledLambda.obtainMessage(
1397 AppOpsService::notifyOpChanged,
1398 this, repCbs, code, uid, packageName));
Dianne Hackbornc2293022013-02-06 23:14:49 -08001399 }
1400 }
1401
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001402 private void notifyOpChanged(ArraySet<ModeCallback> callbacks, int code,
1403 int uid, String packageName) {
1404 for (int i = 0; i < callbacks.size(); i++) {
1405 final ModeCallback callback = callbacks.valueAt(i);
1406 notifyOpChanged(callback, code, uid, packageName);
1407 }
1408 }
1409
1410 private void notifyOpChanged(ModeCallback callback, int code,
1411 int uid, String packageName) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001412 if (uid != UID_ANY && callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001413 return;
1414 }
1415 // There are components watching for mode changes such as window manager
1416 // and location manager which are in our process. The callbacks in these
1417 // components may require permissions our remote caller does not have.
1418 final long identity = Binder.clearCallingIdentity();
1419 try {
1420 callback.mCallback.opChanged(code, uid, packageName);
1421 } catch (RemoteException e) {
1422 /* ignore */
1423 } finally {
1424 Binder.restoreCallingIdentity(identity);
1425 }
1426 }
1427
1428 private static HashMap<ModeCallback, ArrayList<ChangeRec>> addCallbacks(
1429 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks,
1430 int op, int uid, String packageName, ArraySet<ModeCallback> cbs) {
Dianne Hackborn607b4142013-08-02 18:10:10 -07001431 if (cbs == null) {
1432 return callbacks;
1433 }
1434 if (callbacks == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001435 callbacks = new HashMap<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001436 }
Svet Ganov2af57082015-07-30 08:44:20 -07001437 boolean duplicate = false;
Dianne Hackborn68d76552017-02-27 15:32:03 -08001438 final int N = cbs.size();
1439 for (int i=0; i<N; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001440 ModeCallback cb = cbs.valueAt(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001441 ArrayList<ChangeRec> reports = callbacks.get(cb);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001442 if (reports == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001443 reports = new ArrayList<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001444 callbacks.put(cb, reports);
Svet Ganov2af57082015-07-30 08:44:20 -07001445 } else {
1446 final int reportCount = reports.size();
1447 for (int j = 0; j < reportCount; j++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001448 ChangeRec report = reports.get(j);
1449 if (report.op == op && report.pkg.equals(packageName)) {
Svet Ganov2af57082015-07-30 08:44:20 -07001450 duplicate = true;
1451 break;
1452 }
1453 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001454 }
Svet Ganov2af57082015-07-30 08:44:20 -07001455 if (!duplicate) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001456 reports.add(new ChangeRec(op, uid, packageName));
Svet Ganov2af57082015-07-30 08:44:20 -07001457 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001458 }
1459 return callbacks;
1460 }
1461
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001462 static final class ChangeRec {
1463 final int op;
1464 final int uid;
1465 final String pkg;
1466
1467 ChangeRec(int _op, int _uid, String _pkg) {
1468 op = _op;
1469 uid = _uid;
1470 pkg = _pkg;
1471 }
1472 }
1473
Dianne Hackborn607b4142013-08-02 18:10:10 -07001474 @Override
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001475 public void resetAllModes(int reqUserId, String reqPackageName) {
1476 final int callingPid = Binder.getCallingPid();
1477 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001478 reqUserId = ActivityManager.handleIncomingUser(callingPid, callingUid, reqUserId,
1479 true, true, "resetAllModes", null);
Svet Ganov2af57082015-07-30 08:44:20 -07001480
1481 int reqUid = -1;
1482 if (reqPackageName != null) {
1483 try {
1484 reqUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -07001485 reqPackageName, PackageManager.MATCH_UNINSTALLED_PACKAGES, reqUserId);
Svet Ganov2af57082015-07-30 08:44:20 -07001486 } catch (RemoteException e) {
1487 /* ignore - local call */
1488 }
1489 }
1490
Dianne Hackbornd5254412018-05-11 18:02:58 -07001491 enforceManageAppOpsModes(callingPid, callingUid, reqUid);
1492
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001493 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks = null;
Dianne Hackborn607b4142013-08-02 18:10:10 -07001494 synchronized (this) {
1495 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -07001496 for (int i = mUidStates.size() - 1; i >= 0; i--) {
1497 UidState uidState = mUidStates.valueAt(i);
1498
1499 SparseIntArray opModes = uidState.opModes;
1500 if (opModes != null && (uidState.uid == reqUid || reqUid == -1)) {
1501 final int uidOpCount = opModes.size();
1502 for (int j = uidOpCount - 1; j >= 0; j--) {
1503 final int code = opModes.keyAt(j);
1504 if (AppOpsManager.opAllowsReset(code)) {
1505 opModes.removeAt(j);
1506 if (opModes.size() <= 0) {
1507 uidState.opModes = null;
1508 }
1509 for (String packageName : getPackagesForUid(uidState.uid)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001510 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -07001511 mOpModeWatchers.get(code));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001512 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -07001513 mPackageModeWatchers.get(packageName));
1514 }
1515 }
1516 }
1517 }
1518
1519 if (uidState.pkgOps == null) {
1520 continue;
1521 }
1522
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001523 if (reqUserId != UserHandle.USER_ALL
Svet Ganov2af57082015-07-30 08:44:20 -07001524 && reqUserId != UserHandle.getUserId(uidState.uid)) {
Alexandra Gherghinad6a98972014-08-04 17:05:34 +01001525 // Skip any ops for a different user
1526 continue;
1527 }
Svet Ganov2af57082015-07-30 08:44:20 -07001528
1529 Map<String, Ops> packages = uidState.pkgOps;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001530 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001531 boolean uidChanged = false;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001532 while (it.hasNext()) {
1533 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001534 String packageName = ent.getKey();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001535 if (reqPackageName != null && !reqPackageName.equals(packageName)) {
1536 // Skip any ops for a different package
1537 continue;
1538 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001539 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001540 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -07001541 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -07001542 if (AppOpsManager.opAllowsReset(curOp.op)
1543 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -07001544 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001545 changed = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001546 uidChanged = true;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001547 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -07001548 mOpModeWatchers.get(curOp.op));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001549 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -07001550 mPackageModeWatchers.get(packageName));
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001551 if (!curOp.hasAnyTime()) {
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001552 pkgOps.removeAt(j);
1553 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001554 }
1555 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001556 if (pkgOps.size() == 0) {
1557 it.remove();
1558 }
1559 }
Svet Ganov2af57082015-07-30 08:44:20 -07001560 if (uidState.isDefault()) {
1561 mUidStates.remove(uidState.uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001562 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001563 if (uidChanged) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001564 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001565 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001566 }
Svet Ganov2af57082015-07-30 08:44:20 -07001567
Dianne Hackborn607b4142013-08-02 18:10:10 -07001568 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001569 scheduleFastWriteLocked();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001570 }
1571 }
1572 if (callbacks != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001573 for (Map.Entry<ModeCallback, ArrayList<ChangeRec>> ent : callbacks.entrySet()) {
1574 ModeCallback cb = ent.getKey();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001575 ArrayList<ChangeRec> reports = ent.getValue();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001576 for (int i=0; i<reports.size(); i++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001577 ChangeRec rep = reports.get(i);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001578 mHandler.sendMessage(PooledLambda.obtainMessage(
1579 AppOpsService::notifyOpChanged,
1580 this, cb, rep.op, rep.uid, rep.pkg));
Dianne Hackborn607b4142013-08-02 18:10:10 -07001581 }
1582 }
1583 }
1584 }
1585
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001586 private void evalAllForegroundOpsLocked() {
1587 for (int uidi = mUidStates.size() - 1; uidi >= 0; uidi--) {
1588 final UidState uidState = mUidStates.valueAt(uidi);
1589 if (uidState.foregroundOps != null) {
1590 uidState.evalForegroundOps(mOpModeWatchers);
1591 }
1592 }
1593 }
1594
Dianne Hackbornc2293022013-02-06 23:14:49 -08001595 @Override
1596 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001597 startWatchingModeWithFlags(op, packageName, 0, callback);
1598 }
1599
1600 @Override
1601 public void startWatchingModeWithFlags(int op, String packageName, int flags,
1602 IAppOpsCallback callback) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001603 int watchedUid = -1;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001604 final int callingUid = Binder.getCallingUid();
1605 final int callingPid = Binder.getCallingPid();
Dianne Hackborn5376edd2018-06-05 13:21:16 -07001606 // TODO: should have a privileged permission to protect this.
1607 // Also, if the caller has requested WATCH_FOREGROUND_CHANGES, should we require
1608 // the USAGE_STATS permission since this can provide information about when an
1609 // app is in the foreground?
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001610 Preconditions.checkArgumentInRange(op, AppOpsManager.OP_NONE,
1611 AppOpsManager._NUM_OP - 1, "Invalid op code: " + op);
Svetoslav Ganov8de59712015-12-09 18:25:13 -08001612 if (callback == null) {
1613 return;
1614 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001615 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -07001616 op = (op != AppOpsManager.OP_NONE) ? AppOpsManager.opToSwitch(op) : op;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001617 ModeCallback cb = mModeWatchers.get(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -08001618 if (cb == null) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001619 cb = new ModeCallback(callback, watchedUid, flags, callingUid, callingPid);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001620 mModeWatchers.put(callback.asBinder(), cb);
1621 }
1622 if (op != AppOpsManager.OP_NONE) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001623 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(op);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001624 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08001625 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001626 mOpModeWatchers.put(op, cbs);
1627 }
1628 cbs.add(cb);
1629 }
1630 if (packageName != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001631 ArraySet<ModeCallback> cbs = mPackageModeWatchers.get(packageName);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001632 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08001633 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001634 mPackageModeWatchers.put(packageName, cbs);
1635 }
1636 cbs.add(cb);
1637 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001638 evalAllForegroundOpsLocked();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001639 }
1640 }
1641
1642 @Override
1643 public void stopWatchingMode(IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -08001644 if (callback == null) {
1645 return;
1646 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001647 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001648 ModeCallback cb = mModeWatchers.remove(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -08001649 if (cb != null) {
1650 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001651 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001652 ArraySet<ModeCallback> cbs = mOpModeWatchers.valueAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001653 cbs.remove(cb);
1654 if (cbs.size() <= 0) {
1655 mOpModeWatchers.removeAt(i);
1656 }
1657 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001658 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001659 ArraySet<ModeCallback> cbs = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001660 cbs.remove(cb);
1661 if (cbs.size() <= 0) {
1662 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001663 }
1664 }
1665 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001666 evalAllForegroundOpsLocked();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001667 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001668 }
1669
1670 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001671 public IBinder getToken(IBinder clientToken) {
1672 synchronized (this) {
1673 ClientState cs = mClients.get(clientToken);
1674 if (cs == null) {
1675 cs = new ClientState(clientToken);
1676 mClients.put(clientToken, cs);
1677 }
1678 return cs;
1679 }
1680 }
1681
Svet Ganovd873ae62018-06-25 16:39:23 -07001682 public CheckOpsDelegate getAppOpsServiceDelegate() {
1683 synchronized (this) {
1684 return mCheckOpsDelegate;
1685 }
1686 }
1687
1688 public void setAppOpsServiceDelegate(CheckOpsDelegate delegate) {
1689 synchronized (this) {
1690 mCheckOpsDelegate = delegate;
1691 }
1692 }
1693
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001694 @Override
Svet Ganov9d528a12018-12-19 17:23:11 -08001695 public int checkOperationRaw(int code, int uid, String packageName) {
1696 return checkOperationInternal(code, uid, packageName, true /*raw*/);
1697 }
1698
1699 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -08001700 public int checkOperation(int code, int uid, String packageName) {
Svet Ganov9d528a12018-12-19 17:23:11 -08001701 return checkOperationInternal(code, uid, packageName, false /*raw*/);
1702 }
1703
1704 private int checkOperationInternal(int code, int uid, String packageName, boolean raw) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001705 final CheckOpsDelegate delegate;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001706 synchronized (this) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001707 delegate = mCheckOpsDelegate;
1708 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001709 if (delegate == null) {
Svet Ganov9d528a12018-12-19 17:23:11 -08001710 return checkOperationImpl(code, uid, packageName, raw);
Todd Kennedy556efba2018-11-15 07:43:55 -08001711 }
Svet Ganov9d528a12018-12-19 17:23:11 -08001712 return delegate.checkOperation(code, uid, packageName, raw,
Svet Ganovd873ae62018-06-25 16:39:23 -07001713 AppOpsService.this::checkOperationImpl);
1714 }
1715
Svet Ganov9d528a12018-12-19 17:23:11 -08001716 private int checkOperationImpl(int code, int uid, String packageName,
1717 boolean raw) {
Todd Kennedy556efba2018-11-15 07:43:55 -08001718 verifyIncomingUid(uid);
1719 verifyIncomingOp(code);
1720 String resolvedPackageName = resolvePackageName(uid, packageName);
1721 if (resolvedPackageName == null) {
1722 return AppOpsManager.MODE_IGNORED;
1723 }
Svet Ganov9d528a12018-12-19 17:23:11 -08001724 return checkOperationUnchecked(code, uid, resolvedPackageName, raw);
Todd Kennedy556efba2018-11-15 07:43:55 -08001725 }
1726
Svet Ganov9d528a12018-12-19 17:23:11 -08001727 private int checkOperationUnchecked(int code, int uid, String packageName,
1728 boolean raw) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001729 synchronized (this) {
Todd Kennedy556efba2018-11-15 07:43:55 -08001730 if (isOpRestrictedLocked(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001731 return AppOpsManager.MODE_IGNORED;
1732 }
Svet Ganov2af57082015-07-30 08:44:20 -07001733 code = AppOpsManager.opToSwitch(code);
1734 UidState uidState = getUidStateLocked(uid, false);
Svet Ganovee438d42017-01-19 18:04:38 -08001735 if (uidState != null && uidState.opModes != null
1736 && uidState.opModes.indexOfKey(code) >= 0) {
Svet Ganov9d528a12018-12-19 17:23:11 -08001737 final int rawMode = uidState.opModes.get(code);
1738 return raw ? rawMode : uidState.evalMode(rawMode);
Svet Ganov2af57082015-07-30 08:44:20 -07001739 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001740 Op op = getOpLocked(code, uid, packageName, false, true, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001741 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -07001742 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001743 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001744 return op.mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001745 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001746 }
1747
1748 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001749 public int checkAudioOperation(int code, int usage, int uid, String packageName) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001750 final CheckOpsDelegate delegate;
John Spurlock1af30c72014-03-10 08:33:35 -04001751 synchronized (this) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001752 delegate = mCheckOpsDelegate;
1753 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001754 if (delegate == null) {
1755 return checkAudioOperationImpl(code, usage, uid, packageName);
1756 }
Svet Ganovd873ae62018-06-25 16:39:23 -07001757 return delegate.checkAudioOperation(code, usage, uid, packageName,
1758 AppOpsService.this::checkAudioOperationImpl);
1759 }
1760
1761 private int checkAudioOperationImpl(int code, int usage, int uid, String packageName) {
Todd Kennedy556efba2018-11-15 07:43:55 -08001762 boolean suspended;
1763 try {
1764 suspended = isPackageSuspendedForUser(packageName, uid);
1765 } catch (IllegalArgumentException ex) {
1766 // Package not found.
1767 suspended = false;
1768 }
1769
1770 if (suspended) {
1771 Slog.i(TAG, "Audio disabled for suspended package=" + packageName
1772 + " for uid=" + uid);
1773 return AppOpsManager.MODE_IGNORED;
1774 }
1775
Svet Ganovd873ae62018-06-25 16:39:23 -07001776 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001777 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -04001778 if (mode != AppOpsManager.MODE_ALLOWED) {
1779 return mode;
1780 }
1781 }
1782 return checkOperation(code, uid, packageName);
1783 }
1784
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001785 private boolean isPackageSuspendedForUser(String pkg, int uid) {
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001786 try {
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001787 return AppGlobals.getPackageManager().isPackageSuspendedForUser(
1788 pkg, UserHandle.getUserId(uid));
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001789 } catch (RemoteException re) {
1790 throw new SecurityException("Could not talk to package manager service");
1791 }
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001792 }
1793
John Spurlock7b414672014-07-18 13:02:39 -04001794 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
1795 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1796 if (usageRestrictions != null) {
1797 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001798 if (r != null && !r.exceptionPackages.contains(packageName)) {
1799 return r.mode;
1800 }
1801 }
1802 return AppOpsManager.MODE_ALLOWED;
1803 }
1804
1805 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001806 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -04001807 String[] exceptionPackages) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07001808 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
John Spurlock1af30c72014-03-10 08:33:35 -04001809 verifyIncomingUid(uid);
1810 verifyIncomingOp(code);
1811 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001812 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1813 if (usageRestrictions == null) {
1814 usageRestrictions = new SparseArray<Restriction>();
1815 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -04001816 }
John Spurlock7b414672014-07-18 13:02:39 -04001817 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001818 if (mode != AppOpsManager.MODE_ALLOWED) {
1819 final Restriction r = new Restriction();
1820 r.mode = mode;
1821 if (exceptionPackages != null) {
1822 final int N = exceptionPackages.length;
1823 r.exceptionPackages = new ArraySet<String>(N);
1824 for (int i = 0; i < N; i++) {
1825 final String pkg = exceptionPackages[i];
1826 if (pkg != null) {
1827 r.exceptionPackages.add(pkg.trim());
1828 }
1829 }
1830 }
John Spurlock7b414672014-07-18 13:02:39 -04001831 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -04001832 }
1833 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001834
1835 mHandler.sendMessage(PooledLambda.obtainMessage(
Svet Ganov3a95f832018-03-23 17:44:30 -07001836 AppOpsService::notifyWatchersOfChange, this, code, UID_ANY));
John Spurlock1af30c72014-03-10 08:33:35 -04001837 }
1838
1839 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001840 public int checkPackage(int uid, String packageName) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001841 Preconditions.checkNotNull(packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001842 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001843 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1844 true /* uidMismatchExpected */);
1845 if (ops != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001846 return AppOpsManager.MODE_ALLOWED;
1847 } else {
1848 return AppOpsManager.MODE_ERRORED;
1849 }
1850 }
1851 }
1852
1853 @Override
Svet Ganovd873ae62018-06-25 16:39:23 -07001854 public int noteProxyOperation(int code, int proxyUid,
1855 String proxyPackageName, int proxiedUid, String proxiedPackageName) {
1856 verifyIncomingUid(proxyUid);
Svet Ganov99b60432015-06-27 13:15:22 -07001857 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001858 String resolveProxyPackageName = resolvePackageName(proxyUid, proxyPackageName);
1859 if (resolveProxyPackageName == null) {
1860 return AppOpsManager.MODE_IGNORED;
1861 }
1862 final int proxyMode = noteOperationUnchecked(code, proxyUid,
1863 resolveProxyPackageName, -1, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001864 if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
1865 return proxyMode;
1866 }
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001867 String resolveProxiedPackageName = resolvePackageName(proxiedUid, proxiedPackageName);
1868 if (resolveProxiedPackageName == null) {
1869 return AppOpsManager.MODE_IGNORED;
1870 }
1871 return noteOperationUnchecked(code, proxiedUid, resolveProxiedPackageName,
1872 proxyMode, resolveProxyPackageName);
Svet Ganov99b60432015-06-27 13:15:22 -07001873 }
1874
1875 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001876 public int noteOperation(int code, int uid, String packageName) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001877 final CheckOpsDelegate delegate;
1878 synchronized (this) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001879 delegate = mCheckOpsDelegate;
1880 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001881 if (delegate == null) {
1882 return noteOperationImpl(code, uid, packageName);
1883 }
Svet Ganovd873ae62018-06-25 16:39:23 -07001884 return delegate.noteOperation(code, uid, packageName,
1885 AppOpsService.this::noteOperationImpl);
1886 }
1887
1888 private int noteOperationImpl(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001889 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001890 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001891 String resolvedPackageName = resolvePackageName(uid, packageName);
1892 if (resolvedPackageName == null) {
1893 return AppOpsManager.MODE_IGNORED;
1894 }
1895 return noteOperationUnchecked(code, uid, resolvedPackageName, 0, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001896 }
1897
1898 private int noteOperationUnchecked(int code, int uid, String packageName,
1899 int proxyUid, String proxyPackageName) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001900 synchronized (this) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001901 final Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
Yohei Yukawaa965d652017-10-12 15:02:26 -07001902 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001903 if (ops == null) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -08001904 scheduleOpNotedIfNeededLocked(code, uid, packageName,
1905 AppOpsManager.MODE_IGNORED);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001906 if (DEBUG) Slog.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001907 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001908 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001909 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001910 final Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07001911 if (isOpRestrictedLocked(uid, code, packageName)) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -08001912 scheduleOpNotedIfNeededLocked(code, uid, packageName,
1913 AppOpsManager.MODE_IGNORED);
Jason Monk62062992014-05-06 09:55:28 -04001914 return AppOpsManager.MODE_IGNORED;
1915 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001916 final UidState uidState = ops.uidState;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001917 if (op.duration == -1) {
1918 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001919 + " code " + code + " time=" + op.time[uidState.state]
1920 + " duration=" + op.duration);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001921 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001922 op.duration = 0;
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001923 final int switchCode = AppOpsManager.opToSwitch(code);
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001924 // If there is a non-default per UID policy (we set UID op mode only if
1925 // non-default) it takes over, otherwise use the per package policy.
1926 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001927 final int uidMode = uidState.evalMode(uidState.opModes.get(switchCode));
Svet Ganov2af57082015-07-30 08:44:20 -07001928 if (uidMode != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001929 if (DEBUG) Slog.d(TAG, "noteOperation: uid reject #" + uidMode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07001930 + switchCode + " (" + code + ") uid " + uid + " package "
1931 + packageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001932 op.rejectTime[uidState.state] = System.currentTimeMillis();
Svet Ganovb3d2ae22018-12-17 22:06:15 -08001933 scheduleOpNotedIfNeededLocked(code, uid, packageName, uidMode);
Svet Ganov8455ba22019-01-02 13:05:56 -08001934 mHistoricalRegistry.incrementOpRejected(op.op, uid, packageName,
1935 uidState.state);
Svet Ganov2af57082015-07-30 08:44:20 -07001936 return uidMode;
1937 }
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001938 } else {
1939 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001940 final int mode = switchOp.getMode();
1941 if (mode != AppOpsManager.MODE_ALLOWED) {
1942 if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + mode + " for code "
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001943 + switchCode + " (" + code + ") uid " + uid + " package "
1944 + packageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001945 op.rejectTime[uidState.state] = System.currentTimeMillis();
Svet Ganovb3d2ae22018-12-17 22:06:15 -08001946 scheduleOpNotedIfNeededLocked(op.op, uid, packageName, mode);
Svet Ganov8455ba22019-01-02 13:05:56 -08001947 mHistoricalRegistry.incrementOpRejected(op.op, uid, packageName,
1948 uidState.state);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001949 return mode;
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001950 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001951 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001952 if (DEBUG) Slog.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001953 + " package " + packageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001954 op.time[uidState.state] = System.currentTimeMillis();
Svet Ganov8455ba22019-01-02 13:05:56 -08001955 mHistoricalRegistry.incrementOpAccessedCount(op.op, uid, packageName,
1956 uidState.state);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001957 op.rejectTime[uidState.state] = 0;
Svet Ganov99b60432015-06-27 13:15:22 -07001958 op.proxyUid = proxyUid;
1959 op.proxyPackageName = proxyPackageName;
Svet Ganovb3d2ae22018-12-17 22:06:15 -08001960 scheduleOpNotedIfNeededLocked(code, uid, packageName,
1961 AppOpsManager.MODE_ALLOWED);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001962 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001963 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001964 }
1965
1966 @Override
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001967 public void startWatchingActive(int[] ops, IAppOpsActiveCallback callback) {
Svet Ganovf7b47252018-02-26 11:11:27 -08001968 int watchedUid = -1;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001969 final int callingUid = Binder.getCallingUid();
1970 final int callingPid = Binder.getCallingPid();
Svet Ganovf7b47252018-02-26 11:11:27 -08001971 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
1972 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001973 watchedUid = callingUid;
Svet Ganovf7b47252018-02-26 11:11:27 -08001974 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001975 if (ops != null) {
1976 Preconditions.checkArrayElementsInRange(ops, 0,
1977 AppOpsManager._NUM_OP - 1, "Invalid op code in: " + Arrays.toString(ops));
1978 }
1979 if (callback == null) {
1980 return;
1981 }
1982 synchronized (this) {
1983 SparseArray<ActiveCallback> callbacks = mActiveWatchers.get(callback.asBinder());
1984 if (callbacks == null) {
1985 callbacks = new SparseArray<>();
1986 mActiveWatchers.put(callback.asBinder(), callbacks);
1987 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001988 final ActiveCallback activeCallback = new ActiveCallback(callback, watchedUid,
1989 callingUid, callingPid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001990 for (int op : ops) {
1991 callbacks.put(op, activeCallback);
1992 }
1993 }
1994 }
1995
1996 @Override
1997 public void stopWatchingActive(IAppOpsActiveCallback callback) {
1998 if (callback == null) {
1999 return;
2000 }
2001 synchronized (this) {
2002 final SparseArray<ActiveCallback> activeCallbacks =
2003 mActiveWatchers.remove(callback.asBinder());
2004 if (activeCallbacks == null) {
2005 return;
2006 }
2007 final int callbackCount = activeCallbacks.size();
2008 for (int i = 0; i < callbackCount; i++) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002009 activeCallbacks.valueAt(i).destroy();
2010 }
2011 }
2012 }
2013
2014 @Override
2015 public void startWatchingNoted(@NonNull int[] ops, @NonNull IAppOpsNotedCallback callback) {
2016 int watchedUid = Process.INVALID_UID;
2017 final int callingUid = Binder.getCallingUid();
2018 final int callingPid = Binder.getCallingPid();
2019 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
2020 != PackageManager.PERMISSION_GRANTED) {
2021 watchedUid = callingUid;
2022 }
2023 Preconditions.checkArgument(!ArrayUtils.isEmpty(ops), "Ops cannot be null or empty");
2024 Preconditions.checkArrayElementsInRange(ops, 0, AppOpsManager._NUM_OP - 1,
2025 "Invalid op code in: " + Arrays.toString(ops));
2026 Preconditions.checkNotNull(callback, "Callback cannot be null");
2027 synchronized (this) {
2028 SparseArray<NotedCallback> callbacks = mNotedWatchers.get(callback.asBinder());
2029 if (callbacks == null) {
2030 callbacks = new SparseArray<>();
2031 mNotedWatchers.put(callback.asBinder(), callbacks);
2032 }
2033 final NotedCallback notedCallback = new NotedCallback(callback, watchedUid,
2034 callingUid, callingPid);
2035 for (int op : ops) {
2036 callbacks.put(op, notedCallback);
2037 }
2038 }
2039 }
2040
2041 @Override
2042 public void stopWatchingNoted(IAppOpsNotedCallback callback) {
2043 Preconditions.checkNotNull(callback, "Callback cannot be null");
2044 synchronized (this) {
2045 final SparseArray<NotedCallback> notedCallbacks =
2046 mNotedWatchers.remove(callback.asBinder());
2047 if (notedCallbacks == null) {
2048 return;
2049 }
2050 final int callbackCount = notedCallbacks.size();
2051 for (int i = 0; i < callbackCount; i++) {
2052 notedCallbacks.valueAt(i).destroy();
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002053 }
2054 }
2055 }
2056
2057 @Override
Svet Ganovf7b47252018-02-26 11:11:27 -08002058 public int startOperation(IBinder token, int code, int uid, String packageName,
2059 boolean startIfModeDefault) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002060 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08002061 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002062 String resolvedPackageName = resolvePackageName(uid, packageName);
2063 if (resolvedPackageName == null) {
2064 return AppOpsManager.MODE_IGNORED;
2065 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002066 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002067 synchronized (this) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002068 final Ops ops = getOpsRawLocked(uid, resolvedPackageName, true /* edit */,
Yohei Yukawaa965d652017-10-12 15:02:26 -07002069 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002070 if (ops == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002071 if (DEBUG) Slog.d(TAG, "startOperation: no op for code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002072 + " package " + resolvedPackageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07002073 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002074 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002075 final Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07002076 if (isOpRestrictedLocked(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -04002077 return AppOpsManager.MODE_IGNORED;
2078 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002079 final int switchCode = AppOpsManager.opToSwitch(code);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002080 final UidState uidState = ops.uidState;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002081 // If there is a non-default per UID policy (we set UID op mode only if
2082 // non-default) it takes over, otherwise use the per package policy.
2083 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002084 final int uidMode = uidState.evalMode(uidState.opModes.get(switchCode));
Svet Ganovf7b47252018-02-26 11:11:27 -08002085 if (uidMode != AppOpsManager.MODE_ALLOWED
2086 && (!startIfModeDefault || uidMode != AppOpsManager.MODE_DEFAULT)) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002087 if (DEBUG) Slog.d(TAG, "noteOperation: uid reject #" + uidMode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07002088 + switchCode + " (" + code + ") uid " + uid + " package "
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002089 + resolvedPackageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002090 op.rejectTime[uidState.state] = System.currentTimeMillis();
Svet Ganov8455ba22019-01-02 13:05:56 -08002091 mHistoricalRegistry.incrementOpRejected(op.op, uid, packageName,
2092 uidState.state);
Svet Ganov2af57082015-07-30 08:44:20 -07002093 return uidMode;
2094 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002095 } else {
2096 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002097 final int mode = switchOp.getMode();
2098 if (mode != AppOpsManager.MODE_ALLOWED
2099 && (!startIfModeDefault || mode != AppOpsManager.MODE_DEFAULT)) {
2100 if (DEBUG) Slog.d(TAG, "startOperation: reject #" + mode + " for code "
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002101 + switchCode + " (" + code + ") uid " + uid + " package "
2102 + resolvedPackageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002103 op.rejectTime[uidState.state] = System.currentTimeMillis();
Svet Ganov8455ba22019-01-02 13:05:56 -08002104 mHistoricalRegistry.incrementOpRejected(op.op, uid, packageName,
2105 uidState.state);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002106 return mode;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002107 }
Svet Ganov2af57082015-07-30 08:44:20 -07002108 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002109 if (DEBUG) Slog.d(TAG, "startOperation: allowing code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002110 + " package " + resolvedPackageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002111 if (op.startNesting == 0) {
2112 op.startRealtime = SystemClock.elapsedRealtime();
2113 op.time[uidState.state] = System.currentTimeMillis();
Svet Ganov8455ba22019-01-02 13:05:56 -08002114 mHistoricalRegistry.incrementOpAccessedCount(op.op, uid, packageName,
2115 uidState.state);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002116 op.rejectTime[uidState.state] = 0;
Dianne Hackborn35654b62013-01-14 17:38:02 -08002117 op.duration = -1;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002118 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002119 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002120 op.startNesting++;
2121 uidState.startNesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002122 if (client.mStartedOps != null) {
2123 client.mStartedOps.add(op);
2124 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002125 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002126
2127 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002128 }
2129
2130 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002131 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002132 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08002133 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002134 String resolvedPackageName = resolvePackageName(uid, packageName);
2135 if (resolvedPackageName == null) {
2136 return;
2137 }
2138 if (!(token instanceof ClientState)) {
2139 return;
2140 }
2141 ClientState client = (ClientState) token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002142 synchronized (this) {
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07002143 Op op = getOpLocked(code, uid, resolvedPackageName, true, true, false);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002144 if (op == null) {
2145 return;
2146 }
Svet Ganovf7b47252018-02-26 11:11:27 -08002147 if (!client.mStartedOps.remove(op)) {
Svet Ganovf5d5af12018-03-18 11:51:17 -07002148 // We finish ops when packages get removed to guarantee no dangling
2149 // started ops. However, some part of the system may asynchronously
2150 // finish ops for an already gone package. Hence, finishing an op
2151 // for a non existing package is fine and we don't log as a wtf.
2152 final long identity = Binder.clearCallingIdentity();
2153 try {
2154 if (LocalServices.getService(PackageManagerInternal.class).getPackageUid(
2155 resolvedPackageName, 0, UserHandle.getUserId(uid)) < 0) {
2156 Slog.i(TAG, "Finishing op=" + AppOpsManager.opToName(code)
2157 + " for non-existing package=" + resolvedPackageName
2158 + " in uid=" + uid);
2159 return;
2160 }
2161 } finally {
2162 Binder.restoreCallingIdentity(identity);
2163 }
2164 Slog.wtf(TAG, "Operation not started: uid=" + op.uid + " pkg="
2165 + op.packageName + " op=" + AppOpsManager.opToName(op.op));
Svet Ganov31d83ae2018-03-15 10:45:56 -07002166 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002167 }
Svet Ganova7a0db62018-02-27 20:08:01 -08002168 finishOperationLocked(op, /*finishNested*/ false);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002169 if (op.startNesting <= 0) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002170 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, false);
2171 }
2172 }
2173 }
2174
2175 private void scheduleOpActiveChangedIfNeededLocked(int code, int uid, String packageName,
2176 boolean active) {
2177 ArraySet<ActiveCallback> dispatchedCallbacks = null;
2178 final int callbackListCount = mActiveWatchers.size();
2179 for (int i = 0; i < callbackListCount; i++) {
2180 final SparseArray<ActiveCallback> callbacks = mActiveWatchers.valueAt(i);
2181 ActiveCallback callback = callbacks.get(code);
2182 if (callback != null) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002183 if (callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
Svet Ganovf7b47252018-02-26 11:11:27 -08002184 continue;
2185 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002186 if (dispatchedCallbacks == null) {
2187 dispatchedCallbacks = new ArraySet<>();
2188 }
2189 dispatchedCallbacks.add(callback);
2190 }
2191 }
2192 if (dispatchedCallbacks == null) {
2193 return;
2194 }
2195 mHandler.sendMessage(PooledLambda.obtainMessage(
2196 AppOpsService::notifyOpActiveChanged,
2197 this, dispatchedCallbacks, code, uid, packageName, active));
2198 }
2199
2200 private void notifyOpActiveChanged(ArraySet<ActiveCallback> callbacks,
2201 int code, int uid, String packageName, boolean active) {
2202 // There are components watching for mode changes such as window manager
2203 // and location manager which are in our process. The callbacks in these
2204 // components may require permissions our remote caller does not have.
2205 final long identity = Binder.clearCallingIdentity();
2206 try {
2207 final int callbackCount = callbacks.size();
2208 for (int i = 0; i < callbackCount; i++) {
2209 final ActiveCallback callback = callbacks.valueAt(i);
2210 try {
2211 callback.mCallback.opActiveChanged(code, uid, packageName, active);
2212 } catch (RemoteException e) {
2213 /* do nothing */
2214 }
2215 }
2216 } finally {
2217 Binder.restoreCallingIdentity(identity);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002218 }
2219 }
2220
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002221 private void scheduleOpNotedIfNeededLocked(int code, int uid, String packageName,
2222 int result) {
2223 ArraySet<NotedCallback> dispatchedCallbacks = null;
2224 final int callbackListCount = mNotedWatchers.size();
2225 for (int i = 0; i < callbackListCount; i++) {
2226 final SparseArray<NotedCallback> callbacks = mNotedWatchers.valueAt(i);
2227 final NotedCallback callback = callbacks.get(code);
2228 if (callback != null) {
2229 if (callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
2230 continue;
2231 }
2232 if (dispatchedCallbacks == null) {
2233 dispatchedCallbacks = new ArraySet<>();
2234 }
2235 dispatchedCallbacks.add(callback);
2236 }
2237 }
2238 if (dispatchedCallbacks == null) {
2239 return;
2240 }
2241 mHandler.sendMessage(PooledLambda.obtainMessage(
2242 AppOpsService::notifyOpChecked,
2243 this, dispatchedCallbacks, code, uid, packageName, result));
2244 }
2245
2246 private void notifyOpChecked(ArraySet<NotedCallback> callbacks,
2247 int code, int uid, String packageName, int result) {
2248 // There are components watching for checks in our process. The callbacks in
2249 // these components may require permissions our remote caller does not have.
2250 final long identity = Binder.clearCallingIdentity();
2251 try {
2252 final int callbackCount = callbacks.size();
2253 for (int i = 0; i < callbackCount; i++) {
2254 final NotedCallback callback = callbacks.valueAt(i);
2255 try {
2256 callback.mCallback.opNoted(code, uid, packageName, result);
2257 } catch (RemoteException e) {
2258 /* do nothing */
2259 }
2260 }
2261 } finally {
2262 Binder.restoreCallingIdentity(identity);
2263 }
2264 }
2265
Svet Ganovb9d71a62015-04-30 10:38:13 -07002266 @Override
2267 public int permissionToOpCode(String permission) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002268 if (permission == null) {
2269 return AppOpsManager.OP_NONE;
2270 }
Svet Ganovb9d71a62015-04-30 10:38:13 -07002271 return AppOpsManager.permissionToOpCode(permission);
2272 }
2273
Svet Ganova7a0db62018-02-27 20:08:01 -08002274 void finishOperationLocked(Op op, boolean finishNested) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002275 if (op.startNesting <= 1 || finishNested) {
2276 if (op.startNesting == 1 || finishNested) {
2277 op.duration = (int)(SystemClock.elapsedRealtime() - op.startRealtime);
Svet Ganov8455ba22019-01-02 13:05:56 -08002278 mHistoricalRegistry.increaseOpAccessDuration(op.op, op.uid, op.packageName,
2279 op.uidState.state, op.duration);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002280 op.time[op.uidState.state] = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002281 } else {
2282 Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
2283 + op.packageName + " code " + op.op + " time=" + op.time
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002284 + " duration=" + op.duration + " nesting=" + op.startNesting);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002285 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002286 if (op.startNesting >= 1) {
2287 op.uidState.startNesting -= op.startNesting;
2288 }
2289 op.startNesting = 0;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002290 } else {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002291 op.startNesting--;
2292 op.uidState.startNesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002293 }
2294 }
2295
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002296 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002297 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002298 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002299 }
2300 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002301 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002302 }
2303 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
2304 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002305 }
2306
Dianne Hackborn961321f2013-02-05 17:22:41 -08002307 private void verifyIncomingOp(int op) {
2308 if (op >= 0 && op < AppOpsManager._NUM_OP) {
2309 return;
2310 }
2311 throw new IllegalArgumentException("Bad operation #" + op);
2312 }
2313
Svet Ganov2af57082015-07-30 08:44:20 -07002314 private UidState getUidStateLocked(int uid, boolean edit) {
2315 UidState uidState = mUidStates.get(uid);
2316 if (uidState == null) {
2317 if (!edit) {
2318 return null;
2319 }
2320 uidState = new UidState(uid);
2321 mUidStates.put(uid, uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002322 } else {
2323 if (uidState.pendingStateCommitTime != 0) {
Dianne Hackborn9fb93502018-06-18 12:29:44 -07002324 if (uidState.pendingStateCommitTime < mLastRealtime) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002325 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002326 } else {
Dianne Hackborn9fb93502018-06-18 12:29:44 -07002327 mLastRealtime = SystemClock.elapsedRealtime();
2328 if (uidState.pendingStateCommitTime < mLastRealtime) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002329 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002330 }
2331 }
2332 }
Svet Ganov2af57082015-07-30 08:44:20 -07002333 }
2334 return uidState;
2335 }
2336
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002337 private void commitUidPendingStateLocked(UidState uidState) {
Dianne Hackborne93ab412018-05-14 17:52:30 -07002338 final boolean lastForeground = uidState.state <= UID_STATE_LAST_NON_RESTRICTED;
2339 final boolean nowForeground = uidState.pendingState <= UID_STATE_LAST_NON_RESTRICTED;
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002340 uidState.state = uidState.pendingState;
2341 uidState.pendingStateCommitTime = 0;
Dianne Hackborne93ab412018-05-14 17:52:30 -07002342 if (uidState.hasForegroundWatchers && lastForeground != nowForeground) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002343 for (int fgi = uidState.foregroundOps.size() - 1; fgi >= 0; fgi--) {
2344 if (!uidState.foregroundOps.valueAt(fgi)) {
2345 continue;
2346 }
2347 final int code = uidState.foregroundOps.keyAt(fgi);
2348
2349 final ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
2350 if (callbacks != null) {
2351 for (int cbi = callbacks.size() - 1; cbi >= 0; cbi--) {
2352 final ModeCallback callback = callbacks.valueAt(cbi);
2353 if ((callback.mFlags & AppOpsManager.WATCH_FOREGROUND_CHANGES) == 0
2354 || !callback.isWatchingUid(uidState.uid)) {
2355 continue;
2356 }
2357 boolean doAllPackages = uidState.opModes != null
Hai Zhang2b98fb32018-09-21 15:18:46 -07002358 && uidState.opModes.indexOfKey(code) >= 0
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002359 && uidState.opModes.get(code) == AppOpsManager.MODE_FOREGROUND;
2360 if (uidState.pkgOps != null) {
2361 for (int pkgi = uidState.pkgOps.size() - 1; pkgi >= 0; pkgi--) {
2362 final Op op = uidState.pkgOps.valueAt(pkgi).get(code);
2363 if (doAllPackages || (op != null
2364 && op.mode == AppOpsManager.MODE_FOREGROUND)) {
2365 mHandler.sendMessage(PooledLambda.obtainMessage(
2366 AppOpsService::notifyOpChanged,
2367 this, callback, code, uidState.uid,
2368 uidState.pkgOps.keyAt(pkgi)));
2369 }
2370 }
2371 }
2372 }
2373 }
2374 }
2375 }
2376 }
2377
Yohei Yukawaa965d652017-10-12 15:02:26 -07002378 private Ops getOpsRawLocked(int uid, String packageName, boolean edit,
2379 boolean uidMismatchExpected) {
Svet Ganov2af57082015-07-30 08:44:20 -07002380 UidState uidState = getUidStateLocked(uid, edit);
2381 if (uidState == null) {
2382 return null;
2383 }
2384
2385 if (uidState.pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002386 if (!edit) {
2387 return null;
2388 }
Svet Ganov2af57082015-07-30 08:44:20 -07002389 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002390 }
Svet Ganov2af57082015-07-30 08:44:20 -07002391
2392 Ops ops = uidState.pkgOps.get(packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002393 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002394 if (!edit) {
2395 return null;
2396 }
Jason Monk1c7c3192014-06-26 12:52:18 -04002397 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002398 // This is the first time we have seen this package name under this uid,
2399 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -08002400 if (uid != 0) {
2401 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002402 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -08002403 int pkgUid = -1;
2404 try {
Jason Monk1c7c3192014-06-26 12:52:18 -04002405 ApplicationInfo appInfo = ActivityThread.getPackageManager()
Jeff Sharkeycd654482016-01-08 17:42:11 -07002406 .getApplicationInfo(packageName,
Svet Ganovad0a49b2018-10-29 10:07:08 -07002407 PackageManager.MATCH_DIRECT_BOOT_AWARE
Svet Ganov8455ba22019-01-02 13:05:56 -08002408 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkeycd654482016-01-08 17:42:11 -07002409 UserHandle.getUserId(uid));
Jason Monk1c7c3192014-06-26 12:52:18 -04002410 if (appInfo != null) {
2411 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002412 isPrivileged = (appInfo.privateFlags
2413 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04002414 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08002415 pkgUid = resolveUid(packageName);
2416 if (pkgUid >= 0) {
Chien-Yu Chen75cade02016-01-11 10:56:21 -08002417 isPrivileged = false;
Jason Monk1c7c3192014-06-26 12:52:18 -04002418 }
Dianne Hackborn713df152013-05-17 11:27:57 -07002419 }
Jason Monk1c7c3192014-06-26 12:52:18 -04002420 } catch (RemoteException e) {
2421 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08002422 }
2423 if (pkgUid != uid) {
2424 // Oops! The package name is not valid for the uid they are calling
2425 // under. Abort.
Yohei Yukawaa965d652017-10-12 15:02:26 -07002426 if (!uidMismatchExpected) {
2427 RuntimeException ex = new RuntimeException("here");
2428 ex.fillInStackTrace();
2429 Slog.w(TAG, "Bad call: specified package " + packageName
2430 + " under uid " + uid + " but it is really " + pkgUid, ex);
2431 }
Dianne Hackborn514074f2013-02-11 10:52:46 -08002432 return null;
2433 }
2434 } finally {
2435 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002436 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002437 }
Svet Ganov2af57082015-07-30 08:44:20 -07002438 ops = new Ops(packageName, uidState, isPrivileged);
2439 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002440 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08002441 return ops;
2442 }
2443
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07002444 /**
2445 * Get the state of all ops for a package, <b>don't verify that package belongs to uid</b>.
2446 *
2447 * <p>Usually callers should use {@link #getOpLocked} and not call this directly.
2448 *
2449 * @param uid The uid the of the package
2450 * @param packageName The package name for which to get the state for
2451 * @param edit Iff {@code true} create the {@link Ops} object if not yet created
2452 * @param isPrivileged Whether the package is privileged or not
2453 *
2454 * @return The {@link Ops state} of all ops for the package
2455 */
2456 private @Nullable Ops getOpsRawNoVerifyLocked(int uid, @NonNull String packageName,
2457 boolean edit, boolean isPrivileged) {
2458 UidState uidState = getUidStateLocked(uid, edit);
2459 if (uidState == null) {
2460 return null;
2461 }
2462
2463 if (uidState.pkgOps == null) {
2464 if (!edit) {
2465 return null;
2466 }
2467 uidState.pkgOps = new ArrayMap<>();
2468 }
2469
2470 Ops ops = uidState.pkgOps.get(packageName);
2471 if (ops == null) {
2472 if (!edit) {
2473 return null;
2474 }
2475 ops = new Ops(packageName, uidState, isPrivileged);
2476 uidState.pkgOps.put(packageName, ops);
2477 }
2478 return ops;
2479 }
2480
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002481 private void scheduleWriteLocked() {
2482 if (!mWriteScheduled) {
2483 mWriteScheduled = true;
2484 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
2485 }
2486 }
2487
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002488 private void scheduleFastWriteLocked() {
2489 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002490 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002491 mFastWriteScheduled = true;
2492 mHandler.removeCallbacks(mWriteRunner);
2493 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002494 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002495 }
2496
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07002497 /**
2498 * Get the state of an op for a uid.
2499 *
2500 * @param code The code of the op
2501 * @param uid The uid the of the package
2502 * @param packageName The package name for which to get the state for
2503 * @param edit Iff {@code true} create the {@link Op} object if not yet created
2504 * @param verifyUid Iff {@code true} check that the package belongs to the uid
2505 * @param isPrivileged Whether the package is privileged or not (only used if {@code verifyUid
2506 * == false})
2507 *
2508 * @return The {@link Op state} of the op
2509 */
2510 private @Nullable Op getOpLocked(int code, int uid, @NonNull String packageName, boolean edit,
2511 boolean verifyUid, boolean isPrivileged) {
2512 Ops ops;
2513
2514 if (verifyUid) {
2515 ops = getOpsRawLocked(uid, packageName, edit, false /* uidMismatchExpected */);
2516 } else {
2517 ops = getOpsRawNoVerifyLocked(uid, packageName, edit, isPrivileged);
2518 }
2519
Dianne Hackborn72e39832013-01-18 18:36:09 -08002520 if (ops == null) {
2521 return null;
2522 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002523 return getOpLocked(ops, code, edit);
2524 }
2525
2526 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002527 Op op = ops.get(code);
2528 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002529 if (!edit) {
2530 return null;
2531 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002532 op = new Op(ops.uidState, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002533 ops.put(code, op);
2534 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002535 if (edit) {
2536 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002537 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002538 return op;
2539 }
2540
Svet Ganov442ed572016-08-17 17:29:43 -07002541 private boolean isOpRestrictedLocked(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04002542 int userHandle = UserHandle.getUserId(uid);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002543 final int restrictionSetCount = mOpUserRestrictions.size();
Ruben Brunk29931bc2016-03-11 00:24:26 -08002544
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002545 for (int i = 0; i < restrictionSetCount; i++) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002546 // For each client, check that the given op is not restricted, or that the given
2547 // package is exempt from the restriction.
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002548 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07002549 if (restrictionState.hasRestriction(code, packageName, userHandle)) {
2550 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
2551 // If we are the system, bypass user restrictions for certain codes
2552 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07002553 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
2554 false /* uidMismatchExpected */);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07002555 if ((ops != null) && ops.isPrivileged) {
2556 return false;
2557 }
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002558 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002559 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002560 return true;
Jason Monk1c7c3192014-06-26 12:52:18 -04002561 }
Jason Monk62062992014-05-06 09:55:28 -04002562 }
2563 return false;
2564 }
2565
Dianne Hackborn35654b62013-01-14 17:38:02 -08002566 void readState() {
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002567 int oldVersion = NO_VERSION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08002568 synchronized (mFile) {
2569 synchronized (this) {
2570 FileInputStream stream;
2571 try {
2572 stream = mFile.openRead();
2573 } catch (FileNotFoundException e) {
2574 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
2575 return;
2576 }
2577 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002578 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002579 try {
2580 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002581 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08002582 int type;
2583 while ((type = parser.next()) != XmlPullParser.START_TAG
2584 && type != XmlPullParser.END_DOCUMENT) {
2585 ;
2586 }
2587
2588 if (type != XmlPullParser.START_TAG) {
2589 throw new IllegalStateException("no start tag found");
2590 }
2591
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002592 final String versionString = parser.getAttributeValue(null, "v");
2593 if (versionString != null) {
2594 oldVersion = Integer.parseInt(versionString);
2595 }
2596
Dianne Hackborn35654b62013-01-14 17:38:02 -08002597 int outerDepth = parser.getDepth();
2598 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2599 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2600 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2601 continue;
2602 }
2603
2604 String tagName = parser.getName();
2605 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00002606 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07002607 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07002608 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002609 } else {
2610 Slog.w(TAG, "Unknown element under <app-ops>: "
2611 + parser.getName());
2612 XmlUtils.skipCurrentTag(parser);
2613 }
2614 }
2615 success = true;
2616 } catch (IllegalStateException e) {
2617 Slog.w(TAG, "Failed parsing " + e);
2618 } catch (NullPointerException e) {
2619 Slog.w(TAG, "Failed parsing " + e);
2620 } catch (NumberFormatException e) {
2621 Slog.w(TAG, "Failed parsing " + e);
2622 } catch (XmlPullParserException e) {
2623 Slog.w(TAG, "Failed parsing " + e);
2624 } catch (IOException e) {
2625 Slog.w(TAG, "Failed parsing " + e);
2626 } catch (IndexOutOfBoundsException e) {
2627 Slog.w(TAG, "Failed parsing " + e);
2628 } finally {
2629 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07002630 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002631 }
2632 try {
2633 stream.close();
2634 } catch (IOException e) {
2635 }
2636 }
2637 }
2638 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002639 synchronized (this) {
2640 upgradeLocked(oldVersion);
2641 }
2642 }
2643
2644 private void upgradeRunAnyInBackgroundLocked() {
2645 for (int i = 0; i < mUidStates.size(); i++) {
2646 final UidState uidState = mUidStates.valueAt(i);
2647 if (uidState == null) {
2648 continue;
2649 }
2650 if (uidState.opModes != null) {
2651 final int idx = uidState.opModes.indexOfKey(AppOpsManager.OP_RUN_IN_BACKGROUND);
2652 if (idx >= 0) {
2653 uidState.opModes.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND,
2654 uidState.opModes.valueAt(idx));
2655 }
2656 }
2657 if (uidState.pkgOps == null) {
2658 continue;
2659 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002660 boolean changed = false;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002661 for (int j = 0; j < uidState.pkgOps.size(); j++) {
2662 Ops ops = uidState.pkgOps.valueAt(j);
2663 if (ops != null) {
2664 final Op op = ops.get(AppOpsManager.OP_RUN_IN_BACKGROUND);
2665 if (op != null && op.mode != AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002666 final Op copy = new Op(op.uidState, op.packageName,
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002667 AppOpsManager.OP_RUN_ANY_IN_BACKGROUND);
2668 copy.mode = op.mode;
2669 ops.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, copy);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002670 changed = true;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002671 }
2672 }
2673 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002674 if (changed) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002675 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002676 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002677 }
2678 }
2679
2680 private void upgradeLocked(int oldVersion) {
2681 if (oldVersion >= CURRENT_VERSION) {
2682 return;
2683 }
2684 Slog.d(TAG, "Upgrading app-ops xml from version " + oldVersion + " to " + CURRENT_VERSION);
2685 switch (oldVersion) {
2686 case NO_VERSION:
2687 upgradeRunAnyInBackgroundLocked();
2688 // fall through
2689 case 1:
2690 // for future upgrades
2691 }
2692 scheduleFastWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002693 }
2694
Svet Ganov2af57082015-07-30 08:44:20 -07002695 void readUidOps(XmlPullParser parser) throws NumberFormatException,
2696 XmlPullParserException, IOException {
2697 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
2698 int outerDepth = parser.getDepth();
2699 int type;
2700 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2701 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2702 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2703 continue;
2704 }
2705
2706 String tagName = parser.getName();
2707 if (tagName.equals("op")) {
2708 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
2709 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
2710 UidState uidState = getUidStateLocked(uid, true);
2711 if (uidState.opModes == null) {
2712 uidState.opModes = new SparseIntArray();
2713 }
2714 uidState.opModes.put(code, mode);
2715 } else {
2716 Slog.w(TAG, "Unknown element under <uid-ops>: "
2717 + parser.getName());
2718 XmlUtils.skipCurrentTag(parser);
2719 }
2720 }
2721 }
2722
Dave Burke0997c5bd2013-08-02 20:25:02 +00002723 void readPackage(XmlPullParser parser) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08002724 XmlPullParserException, IOException {
2725 String pkgName = parser.getAttributeValue(null, "n");
2726 int outerDepth = parser.getDepth();
2727 int type;
2728 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2729 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2730 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2731 continue;
2732 }
2733
2734 String tagName = parser.getName();
2735 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00002736 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002737 } else {
2738 Slog.w(TAG, "Unknown element under <pkg>: "
2739 + parser.getName());
2740 XmlUtils.skipCurrentTag(parser);
2741 }
2742 }
2743 }
2744
Dave Burke0997c5bd2013-08-02 20:25:02 +00002745 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08002746 XmlPullParserException, IOException {
2747 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Jason Monk1c7c3192014-06-26 12:52:18 -04002748 String isPrivilegedString = parser.getAttributeValue(null, "p");
2749 boolean isPrivileged = false;
2750 if (isPrivilegedString == null) {
2751 try {
2752 IPackageManager packageManager = ActivityThread.getPackageManager();
2753 if (packageManager != null) {
2754 ApplicationInfo appInfo = ActivityThread.getPackageManager()
2755 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
2756 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002757 isPrivileged = (appInfo.privateFlags
2758 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04002759 }
2760 } else {
2761 // Could not load data, don't add to cache so it will be loaded later.
2762 return;
2763 }
2764 } catch (RemoteException e) {
2765 Slog.w(TAG, "Could not contact PackageManager", e);
2766 }
2767 } else {
2768 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
2769 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002770 int outerDepth = parser.getDepth();
2771 int type;
2772 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2773 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2774 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2775 continue;
2776 }
2777
2778 String tagName = parser.getName();
2779 if (tagName.equals("op")) {
Svet Ganov2af57082015-07-30 08:44:20 -07002780 UidState uidState = getUidStateLocked(uid, true);
2781 if (uidState.pkgOps == null) {
2782 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002783 }
Svet Ganov2af57082015-07-30 08:44:20 -07002784
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002785 Op op = new Op(uidState, pkgName,
2786 Integer.parseInt(parser.getAttributeValue(null, "n")));
2787
2788 for (int i = parser.getAttributeCount()-1; i >= 0; i--) {
2789 final String name = parser.getAttributeName(i);
2790 final String value = parser.getAttributeValue(i);
2791 switch (name) {
2792 case "m":
2793 op.mode = Integer.parseInt(value);
2794 break;
2795 case "d":
2796 op.duration = Integer.parseInt(value);
2797 break;
2798 case "pu":
2799 op.proxyUid = Integer.parseInt(value);
2800 break;
2801 case "pp":
2802 op.proxyPackageName = value;
2803 break;
2804 case "tp":
2805 op.time[AppOpsManager.UID_STATE_PERSISTENT] = Long.parseLong(value);
2806 break;
2807 case "tt":
2808 op.time[AppOpsManager.UID_STATE_TOP] = Long.parseLong(value);
2809 break;
Amith Yamasania0a30a12019-01-22 11:38:06 -08002810 case "tfsl":
2811 op.time[AppOpsManager.UID_STATE_FOREGROUND_SERVICE_LOCATION] =
2812 Long.parseLong(value);
2813 break;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002814 case "tfs":
Amith Yamasania0a30a12019-01-22 11:38:06 -08002815 op.time[AppOpsManager.UID_STATE_FOREGROUND_SERVICE] =
2816 Long.parseLong(value);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002817 break;
2818 case "tf":
2819 op.time[AppOpsManager.UID_STATE_FOREGROUND] = Long.parseLong(value);
2820 break;
2821 case "tb":
2822 op.time[AppOpsManager.UID_STATE_BACKGROUND] = Long.parseLong(value);
2823 break;
2824 case "tc":
2825 op.time[AppOpsManager.UID_STATE_CACHED] = Long.parseLong(value);
2826 break;
2827 case "rp":
Amith Yamasania0a30a12019-01-22 11:38:06 -08002828 op.rejectTime[AppOpsManager.UID_STATE_PERSISTENT] =
2829 Long.parseLong(value);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002830 break;
2831 case "rt":
2832 op.rejectTime[AppOpsManager.UID_STATE_TOP] = Long.parseLong(value);
2833 break;
Amith Yamasania0a30a12019-01-22 11:38:06 -08002834 case "rfsl":
2835 op.rejectTime[AppOpsManager.UID_STATE_FOREGROUND_SERVICE_LOCATION] =
2836 Long.parseLong(value);
2837 break;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002838 case "rfs":
Amith Yamasania0a30a12019-01-22 11:38:06 -08002839 op.rejectTime[AppOpsManager.UID_STATE_FOREGROUND_SERVICE] =
2840 Long.parseLong(value);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002841 break;
2842 case "rf":
Amith Yamasania0a30a12019-01-22 11:38:06 -08002843 op.rejectTime[AppOpsManager.UID_STATE_FOREGROUND] =
2844 Long.parseLong(value);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002845 break;
2846 case "rb":
Amith Yamasania0a30a12019-01-22 11:38:06 -08002847 op.rejectTime[AppOpsManager.UID_STATE_BACKGROUND] =
2848 Long.parseLong(value);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002849 break;
2850 case "rc":
Amith Yamasania0a30a12019-01-22 11:38:06 -08002851 op.rejectTime[AppOpsManager.UID_STATE_CACHED] =
2852 Long.parseLong(value);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002853 break;
2854 case "t":
2855 // Backwards compat.
2856 op.time[AppOpsManager.UID_STATE_TOP] = Long.parseLong(value);
2857 break;
2858 case "r":
2859 // Backwards compat.
2860 op.rejectTime[AppOpsManager.UID_STATE_TOP] = Long.parseLong(value);
2861 break;
2862 default:
2863 Slog.w(TAG, "Unknown attribute in 'op' tag: " + name);
2864 break;
2865 }
2866 }
2867
Svet Ganov2af57082015-07-30 08:44:20 -07002868 Ops ops = uidState.pkgOps.get(pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002869 if (ops == null) {
Svet Ganov2af57082015-07-30 08:44:20 -07002870 ops = new Ops(pkgName, uidState, isPrivileged);
2871 uidState.pkgOps.put(pkgName, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002872 }
2873 ops.put(op.op, op);
2874 } else {
2875 Slog.w(TAG, "Unknown element under <pkg>: "
2876 + parser.getName());
2877 XmlUtils.skipCurrentTag(parser);
2878 }
2879 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002880 UidState uidState = getUidStateLocked(uid, false);
2881 if (uidState != null) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002882 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002883 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002884 }
2885
2886 void writeState() {
2887 synchronized (mFile) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002888 FileOutputStream stream;
2889 try {
2890 stream = mFile.startWrite();
2891 } catch (IOException e) {
2892 Slog.w(TAG, "Failed to write state: " + e);
2893 return;
2894 }
2895
Dianne Hackborne17b4452018-01-10 13:15:40 -08002896 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
2897
Dianne Hackborn35654b62013-01-14 17:38:02 -08002898 try {
2899 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002900 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08002901 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002902 out.startTag(null, "app-ops");
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002903 out.attribute(null, "v", String.valueOf(CURRENT_VERSION));
Svet Ganov2af57082015-07-30 08:44:20 -07002904
2905 final int uidStateCount = mUidStates.size();
2906 for (int i = 0; i < uidStateCount; i++) {
2907 UidState uidState = mUidStates.valueAt(i);
2908 if (uidState.opModes != null && uidState.opModes.size() > 0) {
2909 out.startTag(null, "uid");
2910 out.attribute(null, "n", Integer.toString(uidState.uid));
2911 SparseIntArray uidOpModes = uidState.opModes;
2912 final int opCount = uidOpModes.size();
2913 for (int j = 0; j < opCount; j++) {
2914 final int op = uidOpModes.keyAt(j);
2915 final int mode = uidOpModes.valueAt(j);
2916 out.startTag(null, "op");
2917 out.attribute(null, "n", Integer.toString(op));
2918 out.attribute(null, "m", Integer.toString(mode));
2919 out.endTag(null, "op");
2920 }
2921 out.endTag(null, "uid");
2922 }
2923 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002924
2925 if (allOps != null) {
2926 String lastPkg = null;
2927 for (int i=0; i<allOps.size(); i++) {
2928 AppOpsManager.PackageOps pkg = allOps.get(i);
2929 if (!pkg.getPackageName().equals(lastPkg)) {
2930 if (lastPkg != null) {
2931 out.endTag(null, "pkg");
2932 }
2933 lastPkg = pkg.getPackageName();
2934 out.startTag(null, "pkg");
2935 out.attribute(null, "n", lastPkg);
2936 }
2937 out.startTag(null, "uid");
2938 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04002939 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07002940 Ops ops = getOpsRawLocked(pkg.getUid(), pkg.getPackageName(),
2941 false /* edit */, false /* uidMismatchExpected */);
Jason Monk1c7c3192014-06-26 12:52:18 -04002942 // Should always be present as the list of PackageOps is generated
2943 // from Ops.
2944 if (ops != null) {
2945 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
2946 } else {
2947 out.attribute(null, "p", Boolean.toString(false));
2948 }
2949 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002950 List<AppOpsManager.OpEntry> ops = pkg.getOps();
2951 for (int j=0; j<ops.size(); j++) {
2952 AppOpsManager.OpEntry op = ops.get(j);
2953 out.startTag(null, "op");
2954 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07002955 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002956 out.attribute(null, "m", Integer.toString(op.getMode()));
2957 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002958 for (int k = 0; k < _NUM_UID_STATE; k++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002959 final long time = op.getLastTimeFor(k);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002960 if (time != 0) {
2961 out.attribute(null, UID_STATE_TIME_ATTRS[k],
2962 Long.toString(time));
2963 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002964 final long rejectTime = op.getLastRejectTimeFor(k);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002965 if (rejectTime != 0) {
2966 out.attribute(null, UID_STATE_REJECT_ATTRS[k],
2967 Long.toString(rejectTime));
2968 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002969 }
2970 int dur = op.getDuration();
2971 if (dur != 0) {
2972 out.attribute(null, "d", Integer.toString(dur));
2973 }
Svet Ganov99b60432015-06-27 13:15:22 -07002974 int proxyUid = op.getProxyUid();
2975 if (proxyUid != -1) {
2976 out.attribute(null, "pu", Integer.toString(proxyUid));
2977 }
2978 String proxyPackageName = op.getProxyPackageName();
2979 if (proxyPackageName != null) {
2980 out.attribute(null, "pp", proxyPackageName);
2981 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002982 out.endTag(null, "op");
2983 }
2984 out.endTag(null, "uid");
2985 }
2986 if (lastPkg != null) {
2987 out.endTag(null, "pkg");
2988 }
2989 }
2990
2991 out.endTag(null, "app-ops");
2992 out.endDocument();
2993 mFile.finishWrite(stream);
2994 } catch (IOException e) {
2995 Slog.w(TAG, "Failed to write state, restoring backup.", e);
2996 mFile.failWrite(stream);
2997 }
2998 }
2999 }
3000
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003001 static class Shell extends ShellCommand {
3002 final IAppOpsService mInterface;
3003 final AppOpsService mInternal;
3004
3005 int userId = UserHandle.USER_SYSTEM;
3006 String packageName;
3007 String opStr;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003008 String modeStr;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003009 int op;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003010 int mode;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003011 int packageUid;
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003012 int nonpackageUid;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003013 final static Binder sBinder = new Binder();
3014 IBinder mToken;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003015
3016 Shell(IAppOpsService iface, AppOpsService internal) {
3017 mInterface = iface;
3018 mInternal = internal;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003019 try {
3020 mToken = mInterface.getToken(sBinder);
3021 } catch (RemoteException e) {
3022 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003023 }
3024
3025 @Override
3026 public int onCommand(String cmd) {
3027 return onShellCommand(this, cmd);
3028 }
3029
3030 @Override
3031 public void onHelp() {
3032 PrintWriter pw = getOutPrintWriter();
3033 dumpCommandHelp(pw);
3034 }
3035
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003036 static private int strOpToOp(String op, PrintWriter err) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003037 try {
3038 return AppOpsManager.strOpToOp(op);
3039 } catch (IllegalArgumentException e) {
3040 }
3041 try {
3042 return Integer.parseInt(op);
3043 } catch (NumberFormatException e) {
3044 }
3045 try {
3046 return AppOpsManager.strDebugOpToOp(op);
3047 } catch (IllegalArgumentException e) {
3048 err.println("Error: " + e.getMessage());
3049 return -1;
3050 }
3051 }
3052
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003053 static int strModeToMode(String modeStr, PrintWriter err) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003054 for (int i = AppOpsManager.MODE_NAMES.length - 1; i >= 0; i--) {
3055 if (AppOpsManager.MODE_NAMES[i].equals(modeStr)) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003056 return i;
3057 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003058 }
3059 try {
3060 return Integer.parseInt(modeStr);
3061 } catch (NumberFormatException e) {
3062 }
3063 err.println("Error: Mode " + modeStr + " is not valid");
3064 return -1;
3065 }
3066
3067 int parseUserOpMode(int defMode, PrintWriter err) throws RemoteException {
3068 userId = UserHandle.USER_CURRENT;
3069 opStr = null;
3070 modeStr = null;
3071 for (String argument; (argument = getNextArg()) != null;) {
3072 if ("--user".equals(argument)) {
3073 userId = UserHandle.parseUserArg(getNextArgRequired());
3074 } else {
3075 if (opStr == null) {
3076 opStr = argument;
3077 } else if (modeStr == null) {
3078 modeStr = argument;
3079 break;
3080 }
3081 }
3082 }
3083 if (opStr == null) {
3084 err.println("Error: Operation not specified.");
3085 return -1;
3086 }
3087 op = strOpToOp(opStr, err);
3088 if (op < 0) {
3089 return -1;
3090 }
3091 if (modeStr != null) {
3092 if ((mode=strModeToMode(modeStr, err)) < 0) {
3093 return -1;
3094 }
3095 } else {
3096 mode = defMode;
3097 }
3098 return 0;
3099 }
3100
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003101 int parseUserPackageOp(boolean reqOp, PrintWriter err) throws RemoteException {
3102 userId = UserHandle.USER_CURRENT;
3103 packageName = null;
3104 opStr = null;
3105 for (String argument; (argument = getNextArg()) != null;) {
3106 if ("--user".equals(argument)) {
3107 userId = UserHandle.parseUserArg(getNextArgRequired());
3108 } else {
3109 if (packageName == null) {
3110 packageName = argument;
3111 } else if (opStr == null) {
3112 opStr = argument;
3113 break;
3114 }
3115 }
3116 }
3117 if (packageName == null) {
3118 err.println("Error: Package name not specified.");
3119 return -1;
3120 } else if (opStr == null && reqOp) {
3121 err.println("Error: Operation not specified.");
3122 return -1;
3123 }
3124 if (opStr != null) {
3125 op = strOpToOp(opStr, err);
3126 if (op < 0) {
3127 return -1;
3128 }
3129 } else {
3130 op = AppOpsManager.OP_NONE;
3131 }
3132 if (userId == UserHandle.USER_CURRENT) {
3133 userId = ActivityManager.getCurrentUser();
3134 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003135 nonpackageUid = -1;
3136 try {
3137 nonpackageUid = Integer.parseInt(packageName);
3138 } catch (NumberFormatException e) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003139 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003140 if (nonpackageUid == -1 && packageName.length() > 1 && packageName.charAt(0) == 'u'
3141 && packageName.indexOf('.') < 0) {
3142 int i = 1;
3143 while (i < packageName.length() && packageName.charAt(i) >= '0'
3144 && packageName.charAt(i) <= '9') {
3145 i++;
3146 }
3147 if (i > 1 && i < packageName.length()) {
3148 String userStr = packageName.substring(1, i);
3149 try {
3150 int user = Integer.parseInt(userStr);
3151 char type = packageName.charAt(i);
3152 i++;
3153 int startTypeVal = i;
3154 while (i < packageName.length() && packageName.charAt(i) >= '0'
3155 && packageName.charAt(i) <= '9') {
3156 i++;
3157 }
3158 if (i > startTypeVal) {
3159 String typeValStr = packageName.substring(startTypeVal, i);
3160 try {
3161 int typeVal = Integer.parseInt(typeValStr);
3162 if (type == 'a') {
3163 nonpackageUid = UserHandle.getUid(user,
3164 typeVal + Process.FIRST_APPLICATION_UID);
3165 } else if (type == 's') {
3166 nonpackageUid = UserHandle.getUid(user, typeVal);
3167 }
3168 } catch (NumberFormatException e) {
3169 }
3170 }
3171 } catch (NumberFormatException e) {
3172 }
3173 }
3174 }
3175 if (nonpackageUid != -1) {
3176 packageName = null;
3177 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08003178 packageUid = resolveUid(packageName);
3179 if (packageUid < 0) {
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003180 packageUid = AppGlobals.getPackageManager().getPackageUid(packageName,
3181 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
3182 }
3183 if (packageUid < 0) {
3184 err.println("Error: No UID for " + packageName + " in user " + userId);
3185 return -1;
3186 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003187 }
3188 return 0;
3189 }
3190 }
3191
3192 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003193 FileDescriptor err, String[] args, ShellCallback callback,
3194 ResultReceiver resultReceiver) {
3195 (new Shell(this, this)).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003196 }
3197
3198 static void dumpCommandHelp(PrintWriter pw) {
3199 pw.println("AppOps service (appops) commands:");
3200 pw.println(" help");
3201 pw.println(" Print this help text.");
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003202 pw.println(" start [--user <USER_ID>] <PACKAGE | UID> <OP> ");
3203 pw.println(" Starts a given operation for a particular application.");
3204 pw.println(" stop [--user <USER_ID>] <PACKAGE | UID> <OP> ");
3205 pw.println(" Stops a given operation for a particular application.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003206 pw.println(" set [--user <USER_ID>] <PACKAGE | UID> <OP> <MODE>");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003207 pw.println(" Set the mode for a particular application and operation.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003208 pw.println(" get [--user <USER_ID>] <PACKAGE | UID> [<OP>]");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003209 pw.println(" Return the mode for a particular application and optional operation.");
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003210 pw.println(" query-op [--user <USER_ID>] <OP> [<MODE>]");
3211 pw.println(" Print all packages that currently have the given op in the given mode.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003212 pw.println(" reset [--user <USER_ID>] [<PACKAGE>]");
3213 pw.println(" Reset the given application or all applications to default modes.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003214 pw.println(" write-settings");
3215 pw.println(" Immediately write pending changes to storage.");
3216 pw.println(" read-settings");
3217 pw.println(" Read the last written settings, replacing current state in RAM.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003218 pw.println(" options:");
3219 pw.println(" <PACKAGE> an Android package name.");
3220 pw.println(" <OP> an AppOps operation.");
3221 pw.println(" <MODE> one of allow, ignore, deny, or default");
3222 pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
3223 pw.println(" specified, the current user is assumed.");
3224 }
3225
3226 static int onShellCommand(Shell shell, String cmd) {
3227 if (cmd == null) {
3228 return shell.handleDefaultCommands(cmd);
3229 }
3230 PrintWriter pw = shell.getOutPrintWriter();
3231 PrintWriter err = shell.getErrPrintWriter();
3232 try {
3233 switch (cmd) {
3234 case "set": {
3235 int res = shell.parseUserPackageOp(true, err);
3236 if (res < 0) {
3237 return res;
3238 }
3239 String modeStr = shell.getNextArg();
3240 if (modeStr == null) {
3241 err.println("Error: Mode not specified.");
3242 return -1;
3243 }
3244
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003245 final int mode = shell.strModeToMode(modeStr, err);
3246 if (mode < 0) {
3247 return -1;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003248 }
3249
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003250 if (shell.packageName != null) {
3251 shell.mInterface.setMode(shell.op, shell.packageUid, shell.packageName,
3252 mode);
3253 } else {
3254 shell.mInterface.setUidMode(shell.op, shell.nonpackageUid, mode);
3255 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003256 return 0;
3257 }
3258 case "get": {
3259 int res = shell.parseUserPackageOp(false, err);
3260 if (res < 0) {
3261 return res;
3262 }
3263
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003264 List<AppOpsManager.PackageOps> ops = new ArrayList<>();
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003265 if (shell.packageName != null) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003266 // Uid mode overrides package mode, so make sure it's also reported
3267 List<AppOpsManager.PackageOps> r = shell.mInterface.getUidOps(
3268 shell.packageUid,
3269 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
3270 if (r != null) {
3271 ops.addAll(r);
3272 }
3273 r = shell.mInterface.getOpsForPackage(
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003274 shell.packageUid, shell.packageName,
3275 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003276 if (r != null) {
3277 ops.addAll(r);
3278 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003279 } else {
3280 ops = shell.mInterface.getUidOps(
3281 shell.nonpackageUid,
3282 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
3283 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003284 if (ops == null || ops.size() <= 0) {
3285 pw.println("No operations.");
Svet Ganov82f09bc2018-01-12 22:08:40 -08003286 if (shell.op > AppOpsManager.OP_NONE && shell.op < AppOpsManager._NUM_OP) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003287 pw.println("Default mode: " + AppOpsManager.modeToName(
Svet Ganov82f09bc2018-01-12 22:08:40 -08003288 AppOpsManager.opToDefaultMode(shell.op)));
3289 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003290 return 0;
3291 }
3292 final long now = System.currentTimeMillis();
3293 for (int i=0; i<ops.size(); i++) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003294 AppOpsManager.PackageOps packageOps = ops.get(i);
3295 if (packageOps.getPackageName() == null) {
3296 pw.print("Uid mode: ");
3297 }
3298 List<AppOpsManager.OpEntry> entries = packageOps.getOps();
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003299 for (int j=0; j<entries.size(); j++) {
3300 AppOpsManager.OpEntry ent = entries.get(j);
3301 pw.print(AppOpsManager.opToName(ent.getOp()));
3302 pw.print(": ");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003303 pw.print(AppOpsManager.modeToName(ent.getMode()));
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003304 if (ent.getTime() != 0) {
3305 pw.print("; time=");
3306 TimeUtils.formatDuration(now - ent.getTime(), pw);
3307 pw.print(" ago");
3308 }
3309 if (ent.getRejectTime() != 0) {
3310 pw.print("; rejectTime=");
3311 TimeUtils.formatDuration(now - ent.getRejectTime(), pw);
3312 pw.print(" ago");
3313 }
3314 if (ent.getDuration() == -1) {
3315 pw.print(" (running)");
3316 } else if (ent.getDuration() != 0) {
3317 pw.print("; duration=");
3318 TimeUtils.formatDuration(ent.getDuration(), pw);
3319 }
3320 pw.println();
3321 }
3322 }
3323 return 0;
3324 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003325 case "query-op": {
3326 int res = shell.parseUserOpMode(AppOpsManager.MODE_IGNORED, err);
3327 if (res < 0) {
3328 return res;
3329 }
3330 List<AppOpsManager.PackageOps> ops = shell.mInterface.getPackagesForOps(
3331 new int[] {shell.op});
3332 if (ops == null || ops.size() <= 0) {
3333 pw.println("No operations.");
3334 return 0;
3335 }
3336 for (int i=0; i<ops.size(); i++) {
3337 final AppOpsManager.PackageOps pkg = ops.get(i);
3338 boolean hasMatch = false;
3339 final List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
3340 for (int j=0; j<entries.size(); j++) {
3341 AppOpsManager.OpEntry ent = entries.get(j);
3342 if (ent.getOp() == shell.op && ent.getMode() == shell.mode) {
3343 hasMatch = true;
3344 break;
3345 }
3346 }
3347 if (hasMatch) {
3348 pw.println(pkg.getPackageName());
3349 }
3350 }
3351 return 0;
3352 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003353 case "reset": {
3354 String packageName = null;
3355 int userId = UserHandle.USER_CURRENT;
3356 for (String argument; (argument = shell.getNextArg()) != null;) {
3357 if ("--user".equals(argument)) {
3358 String userStr = shell.getNextArgRequired();
3359 userId = UserHandle.parseUserArg(userStr);
3360 } else {
3361 if (packageName == null) {
3362 packageName = argument;
3363 } else {
3364 err.println("Error: Unsupported argument: " + argument);
3365 return -1;
3366 }
3367 }
3368 }
3369
3370 if (userId == UserHandle.USER_CURRENT) {
3371 userId = ActivityManager.getCurrentUser();
3372 }
3373
3374 shell.mInterface.resetAllModes(userId, packageName);
3375 pw.print("Reset all modes for: ");
3376 if (userId == UserHandle.USER_ALL) {
3377 pw.print("all users");
3378 } else {
3379 pw.print("user "); pw.print(userId);
3380 }
3381 pw.print(", ");
3382 if (packageName == null) {
3383 pw.println("all packages");
3384 } else {
3385 pw.print("package "); pw.println(packageName);
3386 }
3387 return 0;
3388 }
3389 case "write-settings": {
Dianne Hackbornd5254412018-05-11 18:02:58 -07003390 shell.mInternal.enforceManageAppOpsModes(Binder.getCallingPid(),
3391 Binder.getCallingUid(), -1);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003392 long token = Binder.clearCallingIdentity();
3393 try {
3394 synchronized (shell.mInternal) {
3395 shell.mInternal.mHandler.removeCallbacks(shell.mInternal.mWriteRunner);
3396 }
3397 shell.mInternal.writeState();
3398 pw.println("Current settings written.");
3399 } finally {
3400 Binder.restoreCallingIdentity(token);
3401 }
3402 return 0;
3403 }
3404 case "read-settings": {
Dianne Hackbornd5254412018-05-11 18:02:58 -07003405 shell.mInternal.enforceManageAppOpsModes(Binder.getCallingPid(),
3406 Binder.getCallingUid(), -1);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003407 long token = Binder.clearCallingIdentity();
3408 try {
3409 shell.mInternal.readState();
3410 pw.println("Last settings read.");
3411 } finally {
3412 Binder.restoreCallingIdentity(token);
3413 }
3414 return 0;
3415 }
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003416 case "start": {
3417 int res = shell.parseUserPackageOp(true, err);
3418 if (res < 0) {
3419 return res;
3420 }
3421
3422 if (shell.packageName != null) {
3423 shell.mInterface.startOperation(shell.mToken,
3424 shell.op, shell.packageUid, shell.packageName, true);
3425 } else {
3426 return -1;
3427 }
3428 return 0;
3429 }
3430 case "stop": {
3431 int res = shell.parseUserPackageOp(true, err);
3432 if (res < 0) {
3433 return res;
3434 }
3435
3436 if (shell.packageName != null) {
3437 shell.mInterface.finishOperation(shell.mToken,
3438 shell.op, shell.packageUid, shell.packageName);
3439 } else {
3440 return -1;
3441 }
3442 return 0;
3443 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003444 default:
3445 return shell.handleDefaultCommands(cmd);
3446 }
3447 } catch (RemoteException e) {
3448 pw.println("Remote exception: " + e);
3449 }
3450 return -1;
3451 }
3452
3453 private void dumpHelp(PrintWriter pw) {
3454 pw.println("AppOps service (appops) dump options:");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003455 pw.println(" -h");
3456 pw.println(" Print this help text.");
3457 pw.println(" --op [OP]");
3458 pw.println(" Limit output to data associated with the given app op code.");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003459 pw.println(" --mode [MODE]");
3460 pw.println(" Limit output to data associated with the given app op mode.");
3461 pw.println(" --package [PACKAGE]");
3462 pw.println(" Limit output to data associated with the given package name.");
Dianne Hackborn125dc532019-01-09 13:31:48 -08003463 pw.println(" --watchers");
3464 pw.println(" Only output the watcher sections.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003465 }
3466
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003467 private void dumpTimesLocked(PrintWriter pw, String firstPrefix, String prefix, long[] times,
3468 long now, SimpleDateFormat sdf, Date date) {
3469 boolean hasTime = false;
3470 for (int i = 0; i < _NUM_UID_STATE; i++) {
3471 if (times[i] != 0) {
3472 hasTime = true;
3473 break;
3474 }
3475 }
3476 if (!hasTime) {
3477 return;
3478 }
3479 boolean first = true;
3480 for (int i = 0; i < _NUM_UID_STATE; i++) {
3481 if (times[i] != 0) {
3482 pw.print(first ? firstPrefix : prefix);
3483 first = false;
3484 pw.print(UID_STATE_NAMES[i]);
3485 pw.print(" = ");
3486 date.setTime(times[i]);
3487 pw.print(sdf.format(date));
3488 pw.print(" (");
3489 TimeUtils.formatDuration(times[i]-now, pw);
3490 pw.println(")");
3491 }
3492 }
3493 }
3494
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003495 @Override
3496 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06003497 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003498
Svet Ganov8455ba22019-01-02 13:05:56 -08003499 int dumpOp = OP_NONE;
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003500 String dumpPackage = null;
Svet Ganov8455ba22019-01-02 13:05:56 -08003501 int dumpUid = Process.INVALID_UID;
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003502 int dumpMode = -1;
Dianne Hackborn125dc532019-01-09 13:31:48 -08003503 boolean dumpWatchers = false;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003504
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003505 if (args != null) {
3506 for (int i=0; i<args.length; i++) {
3507 String arg = args[i];
3508 if ("-h".equals(arg)) {
3509 dumpHelp(pw);
3510 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07003511 } else if ("-a".equals(arg)) {
3512 // dump all data
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003513 } else if ("--op".equals(arg)) {
3514 i++;
3515 if (i >= args.length) {
3516 pw.println("No argument for --op option");
3517 return;
3518 }
3519 dumpOp = Shell.strOpToOp(args[i], pw);
3520 if (dumpOp < 0) {
3521 return;
3522 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003523 } else if ("--package".equals(arg)) {
3524 i++;
3525 if (i >= args.length) {
3526 pw.println("No argument for --package option");
3527 return;
3528 }
3529 dumpPackage = args[i];
3530 try {
3531 dumpUid = AppGlobals.getPackageManager().getPackageUid(dumpPackage,
3532 PackageManager.MATCH_KNOWN_PACKAGES | PackageManager.MATCH_INSTANT,
3533 0);
3534 } catch (RemoteException e) {
3535 }
3536 if (dumpUid < 0) {
3537 pw.println("Unknown package: " + dumpPackage);
3538 return;
3539 }
3540 dumpUid = UserHandle.getAppId(dumpUid);
3541 } else if ("--mode".equals(arg)) {
3542 i++;
3543 if (i >= args.length) {
3544 pw.println("No argument for --mode option");
3545 return;
3546 }
3547 dumpMode = Shell.strModeToMode(args[i], pw);
3548 if (dumpMode < 0) {
3549 return;
3550 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08003551 } else if ("--watchers".equals(arg)) {
3552 dumpWatchers = true;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003553 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
3554 pw.println("Unknown option: " + arg);
3555 return;
3556 } else {
3557 pw.println("Unknown command: " + arg);
3558 return;
3559 }
3560 }
3561 }
3562
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003563 synchronized (this) {
3564 pw.println("Current AppOps Service state:");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003565 mConstants.dump(pw);
3566 pw.println();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003567 final long now = System.currentTimeMillis();
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003568 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003569 final long nowUptime = SystemClock.uptimeMillis();
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003570 final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
3571 final Date date = new Date();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003572 boolean needSep = false;
Dianne Hackborn125dc532019-01-09 13:31:48 -08003573 if (dumpOp < 0 && dumpMode < 0 && dumpPackage == null && mProfileOwners != null
3574 && !dumpWatchers) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07003575 pw.println(" Profile owners:");
3576 for (int poi = 0; poi < mProfileOwners.size(); poi++) {
3577 pw.print(" User #");
3578 pw.print(mProfileOwners.keyAt(poi));
3579 pw.print(": ");
3580 UserHandle.formatUid(pw, mProfileOwners.valueAt(poi));
3581 pw.println();
3582 }
3583 pw.println();
3584 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003585 if (mOpModeWatchers.size() > 0) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003586 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003587 for (int i=0; i<mOpModeWatchers.size(); i++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003588 if (dumpOp >= 0 && dumpOp != mOpModeWatchers.keyAt(i)) {
3589 continue;
3590 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003591 boolean printedOpHeader = false;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003592 ArraySet<ModeCallback> callbacks = mOpModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003593 for (int j=0; j<callbacks.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003594 final ModeCallback cb = callbacks.valueAt(j);
Dianne Hackborn125dc532019-01-09 13:31:48 -08003595 if (dumpPackage != null
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003596 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3597 continue;
3598 }
3599 needSep = true;
3600 if (!printedHeader) {
3601 pw.println(" Op mode watchers:");
3602 printedHeader = true;
3603 }
3604 if (!printedOpHeader) {
3605 pw.print(" Op ");
3606 pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
3607 pw.println(":");
3608 printedOpHeader = true;
3609 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003610 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003611 pw.println(cb);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003612 }
3613 }
3614 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003615 if (mPackageModeWatchers.size() > 0 && dumpOp < 0) {
3616 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003617 for (int i=0; i<mPackageModeWatchers.size(); i++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003618 if (dumpPackage != null && !dumpPackage.equals(mPackageModeWatchers.keyAt(i))) {
3619 continue;
3620 }
3621 needSep = true;
3622 if (!printedHeader) {
3623 pw.println(" Package mode watchers:");
3624 printedHeader = true;
3625 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003626 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
3627 pw.println(":");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003628 ArraySet<ModeCallback> callbacks = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003629 for (int j=0; j<callbacks.size(); j++) {
3630 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08003631 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003632 }
3633 }
3634 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003635 if (mModeWatchers.size() > 0 && dumpOp < 0) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003636 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003637 for (int i=0; i<mModeWatchers.size(); i++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003638 final ModeCallback cb = mModeWatchers.valueAt(i);
Dianne Hackborn125dc532019-01-09 13:31:48 -08003639 if (dumpPackage != null
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003640 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3641 continue;
3642 }
3643 needSep = true;
3644 if (!printedHeader) {
3645 pw.println(" All op mode watchers:");
3646 printedHeader = true;
3647 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003648 pw.print(" ");
3649 pw.print(Integer.toHexString(System.identityHashCode(mModeWatchers.keyAt(i))));
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003650 pw.print(": "); pw.println(cb);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003651 }
3652 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003653 if (mActiveWatchers.size() > 0 && dumpMode < 0) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003654 needSep = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003655 boolean printedHeader = false;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003656 for (int i = 0; i < mActiveWatchers.size(); i++) {
3657 final SparseArray<ActiveCallback> activeWatchers = mActiveWatchers.valueAt(i);
3658 if (activeWatchers.size() <= 0) {
3659 continue;
3660 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003661 final ActiveCallback cb = activeWatchers.valueAt(0);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003662 if (dumpOp >= 0 && activeWatchers.indexOfKey(dumpOp) < 0) {
3663 continue;
3664 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08003665 if (dumpPackage != null
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003666 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3667 continue;
3668 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003669 if (!printedHeader) {
3670 pw.println(" All op active watchers:");
3671 printedHeader = true;
3672 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003673 pw.print(" ");
3674 pw.print(Integer.toHexString(System.identityHashCode(
3675 mActiveWatchers.keyAt(i))));
3676 pw.println(" ->");
3677 pw.print(" [");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003678 final int opCount = activeWatchers.size();
3679 for (i = 0; i < opCount; i++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003680 if (i > 0) {
3681 pw.print(' ');
3682 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003683 pw.print(AppOpsManager.opToName(activeWatchers.keyAt(i)));
3684 if (i < opCount - 1) {
3685 pw.print(',');
3686 }
3687 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003688 pw.println("]");
3689 pw.print(" ");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003690 pw.println(cb);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003691 }
3692 }
Svet Ganovb3d2ae22018-12-17 22:06:15 -08003693 if (mNotedWatchers.size() > 0 && dumpMode < 0) {
3694 needSep = true;
3695 boolean printedHeader = false;
3696 for (int i = 0; i < mNotedWatchers.size(); i++) {
3697 final SparseArray<NotedCallback> notedWatchers = mNotedWatchers.valueAt(i);
3698 if (notedWatchers.size() <= 0) {
3699 continue;
3700 }
3701 final NotedCallback cb = notedWatchers.valueAt(0);
3702 if (dumpOp >= 0 && notedWatchers.indexOfKey(dumpOp) < 0) {
3703 continue;
3704 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08003705 if (dumpPackage != null
Svet Ganovb3d2ae22018-12-17 22:06:15 -08003706 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3707 continue;
3708 }
3709 if (!printedHeader) {
3710 pw.println(" All op noted watchers:");
3711 printedHeader = true;
3712 }
3713 pw.print(" ");
3714 pw.print(Integer.toHexString(System.identityHashCode(
3715 mNotedWatchers.keyAt(i))));
3716 pw.println(" ->");
3717 pw.print(" [");
3718 final int opCount = notedWatchers.size();
3719 for (i = 0; i < opCount; i++) {
3720 if (i > 0) {
3721 pw.print(' ');
3722 }
3723 pw.print(AppOpsManager.opToName(notedWatchers.keyAt(i)));
3724 if (i < opCount - 1) {
3725 pw.print(',');
3726 }
3727 }
3728 pw.println("]");
3729 pw.print(" ");
3730 pw.println(cb);
3731 }
3732 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08003733 if (mClients.size() > 0 && dumpMode < 0 && !dumpWatchers) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003734 needSep = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003735 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003736 for (int i=0; i<mClients.size(); i++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003737 boolean printedClient = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003738 ClientState cs = mClients.valueAt(i);
Svet Ganovf7b47252018-02-26 11:11:27 -08003739 if (cs.mStartedOps.size() > 0) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003740 boolean printedStarted = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003741 for (int j=0; j<cs.mStartedOps.size(); j++) {
3742 Op op = cs.mStartedOps.get(j);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003743 if (dumpOp >= 0 && op.op != dumpOp) {
3744 continue;
3745 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003746 if (dumpPackage != null && !dumpPackage.equals(op.packageName)) {
3747 continue;
3748 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003749 if (!printedHeader) {
3750 pw.println(" Clients:");
3751 printedHeader = true;
3752 }
3753 if (!printedClient) {
3754 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
3755 pw.print(" "); pw.println(cs);
3756 printedClient = true;
3757 }
3758 if (!printedStarted) {
3759 pw.println(" Started ops:");
3760 printedStarted = true;
3761 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003762 pw.print(" "); pw.print("uid="); pw.print(op.uid);
3763 pw.print(" pkg="); pw.print(op.packageName);
3764 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
3765 }
3766 }
3767 }
3768 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003769 if (mAudioRestrictions.size() > 0 && dumpOp < 0 && dumpPackage != null
Dianne Hackborn125dc532019-01-09 13:31:48 -08003770 && dumpMode < 0 && !dumpWatchers) {
John Spurlock1af30c72014-03-10 08:33:35 -04003771 boolean printedHeader = false;
3772 for (int o=0; o<mAudioRestrictions.size(); o++) {
3773 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
3774 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
3775 for (int i=0; i<restrictions.size(); i++) {
3776 if (!printedHeader){
3777 pw.println(" Audio Restrictions:");
3778 printedHeader = true;
3779 needSep = true;
3780 }
John Spurlock7b414672014-07-18 13:02:39 -04003781 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04003782 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04003783 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04003784 Restriction r = restrictions.valueAt(i);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003785 pw.print(": mode="); pw.println(AppOpsManager.modeToName(r.mode));
John Spurlock1af30c72014-03-10 08:33:35 -04003786 if (!r.exceptionPackages.isEmpty()) {
3787 pw.println(" Exceptions:");
3788 for (int j=0; j<r.exceptionPackages.size(); j++) {
3789 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
3790 }
3791 }
3792 }
3793 }
3794 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003795 if (needSep) {
3796 pw.println();
3797 }
Svet Ganov2af57082015-07-30 08:44:20 -07003798 for (int i=0; i<mUidStates.size(); i++) {
3799 UidState uidState = mUidStates.valueAt(i);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003800 final SparseIntArray opModes = uidState.opModes;
3801 final ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
3802
Dianne Hackborn125dc532019-01-09 13:31:48 -08003803 if (dumpWatchers) {
3804 continue;
3805 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003806 if (dumpOp >= 0 || dumpPackage != null || dumpMode >= 0) {
3807 boolean hasOp = dumpOp < 0 || (uidState.opModes != null
3808 && uidState.opModes.indexOfKey(dumpOp) >= 0);
3809 boolean hasPackage = dumpPackage == null;
3810 boolean hasMode = dumpMode < 0;
3811 if (!hasMode && opModes != null) {
3812 for (int opi = 0; !hasMode && opi < opModes.size(); opi++) {
3813 if (opModes.valueAt(opi) == dumpMode) {
3814 hasMode = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003815 }
3816 }
3817 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003818 if (pkgOps != null) {
3819 for (int pkgi = 0;
Svet Ganov8455ba22019-01-02 13:05:56 -08003820 (!hasOp || !hasPackage || !hasMode) && pkgi < pkgOps.size();
3821 pkgi++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003822 Ops ops = pkgOps.valueAt(pkgi);
3823 if (!hasOp && ops != null && ops.indexOfKey(dumpOp) >= 0) {
3824 hasOp = true;
3825 }
3826 if (!hasMode) {
3827 for (int opi = 0; !hasMode && opi < ops.size(); opi++) {
3828 if (ops.valueAt(opi).mode == dumpMode) {
3829 hasMode = true;
3830 }
3831 }
3832 }
3833 if (!hasPackage && dumpPackage.equals(ops.packageName)) {
3834 hasPackage = true;
3835 }
3836 }
3837 }
3838 if (uidState.foregroundOps != null && !hasOp) {
3839 if (uidState.foregroundOps.indexOfKey(dumpOp) > 0) {
3840 hasOp = true;
3841 }
3842 }
3843 if (!hasOp || !hasPackage || !hasMode) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003844 continue;
3845 }
3846 }
Svet Ganov2af57082015-07-30 08:44:20 -07003847
3848 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003849 pw.print(" state=");
3850 pw.println(UID_STATE_NAMES[uidState.state]);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003851 if (uidState.state != uidState.pendingState) {
3852 pw.print(" pendingState=");
3853 pw.println(UID_STATE_NAMES[uidState.pendingState]);
3854 }
3855 if (uidState.pendingStateCommitTime != 0) {
3856 pw.print(" pendingStateCommitTime=");
Dianne Hackborn9fb93502018-06-18 12:29:44 -07003857 TimeUtils.formatDuration(uidState.pendingStateCommitTime, nowElapsed, pw);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003858 pw.println();
3859 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003860 if (uidState.startNesting != 0) {
3861 pw.print(" startNesting=");
3862 pw.println(uidState.startNesting);
3863 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003864 if (uidState.foregroundOps != null && (dumpMode < 0
3865 || dumpMode == AppOpsManager.MODE_FOREGROUND)) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003866 pw.println(" foregroundOps:");
3867 for (int j = 0; j < uidState.foregroundOps.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003868 if (dumpOp >= 0 && dumpOp != uidState.foregroundOps.keyAt(j)) {
3869 continue;
3870 }
3871 pw.print(" ");
3872 pw.print(AppOpsManager.opToName(uidState.foregroundOps.keyAt(j)));
3873 pw.print(": ");
3874 pw.println(uidState.foregroundOps.valueAt(j) ? "WATCHER" : "SILENT");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003875 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003876 pw.print(" hasForegroundWatchers=");
3877 pw.println(uidState.hasForegroundWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003878 }
Svet Ganovee438d42017-01-19 18:04:38 -08003879 needSep = true;
Svet Ganov2af57082015-07-30 08:44:20 -07003880
Svet Ganov2af57082015-07-30 08:44:20 -07003881 if (opModes != null) {
3882 final int opModeCount = opModes.size();
3883 for (int j = 0; j < opModeCount; j++) {
3884 final int code = opModes.keyAt(j);
3885 final int mode = opModes.valueAt(j);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003886 if (dumpOp >= 0 && dumpOp != code) {
3887 continue;
3888 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003889 if (dumpMode >= 0 && dumpMode != mode) {
3890 continue;
3891 }
Svet Ganov2af57082015-07-30 08:44:20 -07003892 pw.print(" "); pw.print(AppOpsManager.opToName(code));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003893 pw.print(": mode="); pw.println(AppOpsManager.modeToName(mode));
Svet Ganov2af57082015-07-30 08:44:20 -07003894 }
3895 }
3896
Svet Ganov2af57082015-07-30 08:44:20 -07003897 if (pkgOps == null) {
3898 continue;
3899 }
3900
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003901 for (int pkgi = 0; pkgi < pkgOps.size(); pkgi++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003902 final Ops ops = pkgOps.valueAt(pkgi);
3903 if (dumpPackage != null && !dumpPackage.equals(ops.packageName)) {
3904 continue;
3905 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003906 boolean printedPackage = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003907 for (int j=0; j<ops.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003908 final Op op = ops.valueAt(j);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003909 if (dumpOp >= 0 && dumpOp != op.op) {
3910 continue;
3911 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003912 if (dumpMode >= 0 && dumpMode != op.mode) {
3913 continue;
3914 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003915 if (!printedPackage) {
3916 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
3917 printedPackage = true;
3918 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003919 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003920 pw.print(" ("); pw.print(AppOpsManager.modeToName(op.mode));
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003921 final int switchOp = AppOpsManager.opToSwitch(op.op);
3922 if (switchOp != op.op) {
3923 pw.print(" / switch ");
3924 pw.print(AppOpsManager.opToName(switchOp));
3925 final Op switchObj = ops.get(switchOp);
3926 int mode = switchObj != null
3927 ? switchObj.mode : AppOpsManager.opToDefaultMode(switchOp);
3928 pw.print("="); pw.print(AppOpsManager.modeToName(mode));
3929 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003930 pw.println("): ");
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003931 dumpTimesLocked(pw,
3932 " Access: ",
3933 " ", op.time, now, sdf, date);
3934 dumpTimesLocked(pw,
3935 " Reject: ",
3936 " ", op.rejectTime, now, sdf, date);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003937 if (op.duration == -1) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003938 pw.print(" Running start at: ");
3939 TimeUtils.formatDuration(nowElapsed-op.startRealtime, pw);
3940 pw.println();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08003941 } else if (op.duration != 0) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003942 pw.print(" duration=");
3943 TimeUtils.formatDuration(op.duration, pw);
3944 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003945 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003946 if (op.startNesting != 0) {
3947 pw.print(" startNesting=");
3948 pw.println(op.startNesting);
3949 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003950 }
3951 }
3952 }
Svet Ganovee438d42017-01-19 18:04:38 -08003953 if (needSep) {
3954 pw.println();
3955 }
3956
3957 final int userRestrictionCount = mOpUserRestrictions.size();
3958 for (int i = 0; i < userRestrictionCount; i++) {
3959 IBinder token = mOpUserRestrictions.keyAt(i);
3960 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
Dianne Hackborn125dc532019-01-09 13:31:48 -08003961 boolean printedTokenHeader = false;
3962
3963 if (dumpMode >= 0 || dumpWatchers) {
3964 continue;
3965 }
Svet Ganovee438d42017-01-19 18:04:38 -08003966
3967 final int restrictionCount = restrictionState.perUserRestrictions != null
3968 ? restrictionState.perUserRestrictions.size() : 0;
Dianne Hackborn125dc532019-01-09 13:31:48 -08003969 if (restrictionCount > 0 && dumpPackage == null) {
3970 boolean printedOpsHeader = false;
Svet Ganovee438d42017-01-19 18:04:38 -08003971 for (int j = 0; j < restrictionCount; j++) {
3972 int userId = restrictionState.perUserRestrictions.keyAt(j);
3973 boolean[] restrictedOps = restrictionState.perUserRestrictions.valueAt(j);
3974 if (restrictedOps == null) {
3975 continue;
3976 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08003977 if (dumpOp >= 0 && (dumpOp >= restrictedOps.length
3978 || !restrictedOps[dumpOp])) {
3979 continue;
3980 }
3981 if (!printedTokenHeader) {
3982 pw.println(" User restrictions for token " + token + ":");
3983 printedTokenHeader = true;
3984 }
3985 if (!printedOpsHeader) {
3986 pw.println(" Restricted ops:");
3987 printedOpsHeader = true;
3988 }
Svet Ganovee438d42017-01-19 18:04:38 -08003989 StringBuilder restrictedOpsValue = new StringBuilder();
3990 restrictedOpsValue.append("[");
3991 final int restrictedOpCount = restrictedOps.length;
3992 for (int k = 0; k < restrictedOpCount; k++) {
3993 if (restrictedOps[k]) {
3994 if (restrictedOpsValue.length() > 1) {
3995 restrictedOpsValue.append(", ");
3996 }
3997 restrictedOpsValue.append(AppOpsManager.opToName(k));
3998 }
3999 }
4000 restrictedOpsValue.append("]");
4001 pw.print(" "); pw.print("user: "); pw.print(userId);
4002 pw.print(" restricted ops: "); pw.println(restrictedOpsValue);
4003 }
4004 }
4005
4006 final int excludedPackageCount = restrictionState.perUserExcludedPackages != null
4007 ? restrictionState.perUserExcludedPackages.size() : 0;
Dianne Hackborn125dc532019-01-09 13:31:48 -08004008 if (excludedPackageCount > 0 && dumpOp < 0) {
4009 boolean printedPackagesHeader = false;
Svet Ganovee438d42017-01-19 18:04:38 -08004010 for (int j = 0; j < excludedPackageCount; j++) {
4011 int userId = restrictionState.perUserExcludedPackages.keyAt(j);
4012 String[] packageNames = restrictionState.perUserExcludedPackages.valueAt(j);
Dianne Hackborn125dc532019-01-09 13:31:48 -08004013 if (packageNames == null) {
4014 continue;
4015 }
4016 boolean hasPackage;
4017 if (dumpPackage != null) {
4018 hasPackage = false;
4019 for (String pkg : packageNames) {
4020 if (dumpPackage.equals(pkg)) {
4021 hasPackage = true;
4022 break;
4023 }
4024 }
4025 } else {
4026 hasPackage = true;
4027 }
4028 if (!hasPackage) {
4029 continue;
4030 }
4031 if (!printedTokenHeader) {
4032 pw.println(" User restrictions for token " + token + ":");
4033 printedTokenHeader = true;
4034 }
4035 if (!printedPackagesHeader) {
4036 pw.println(" Excluded packages:");
4037 printedPackagesHeader = true;
4038 }
Svet Ganovee438d42017-01-19 18:04:38 -08004039 pw.print(" "); pw.print("user: "); pw.print(userId);
4040 pw.print(" packages: "); pw.println(Arrays.toString(packageNames));
4041 }
4042 }
4043 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004044 }
Svet Ganov8455ba22019-01-02 13:05:56 -08004045
4046 // Must not hold the appops lock
4047 mHistoricalRegistry.dump(" ", pw, dumpUid, dumpPackage, dumpOp);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004048 }
John Spurlock1af30c72014-03-10 08:33:35 -04004049
4050 private static final class Restriction {
4051 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
4052 int mode;
4053 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
4054 }
Jason Monk62062992014-05-06 09:55:28 -04004055
4056 @Override
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004057 public void setUserRestrictions(Bundle restrictions, IBinder token, int userHandle) {
Jason Monk62062992014-05-06 09:55:28 -04004058 checkSystemUid("setUserRestrictions");
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004059 Preconditions.checkNotNull(restrictions);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004060 Preconditions.checkNotNull(token);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004061 for (int i = 0; i < AppOpsManager._NUM_OP; i++) {
Jason Monk62062992014-05-06 09:55:28 -04004062 String restriction = AppOpsManager.opToRestriction(i);
Suprabh Shukla64e0dcb2016-05-24 16:23:11 -07004063 if (restriction != null) {
4064 setUserRestrictionNoCheck(i, restrictions.getBoolean(restriction, false), token,
4065 userHandle, null);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004066 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004067 }
4068 }
4069
4070 @Override
Ruben Brunk29931bc2016-03-11 00:24:26 -08004071 public void setUserRestriction(int code, boolean restricted, IBinder token, int userHandle,
4072 String[] exceptionPackages) {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004073 if (Binder.getCallingPid() != Process.myPid()) {
4074 mContext.enforcePermission(Manifest.permission.MANAGE_APP_OPS_RESTRICTIONS,
4075 Binder.getCallingPid(), Binder.getCallingUid(), null);
4076 }
4077 if (userHandle != UserHandle.getCallingUserId()) {
4078 if (mContext.checkCallingOrSelfPermission(Manifest.permission
4079 .INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
4080 && mContext.checkCallingOrSelfPermission(Manifest.permission
4081 .INTERACT_ACROSS_USERS) != PackageManager.PERMISSION_GRANTED) {
4082 throw new SecurityException("Need INTERACT_ACROSS_USERS_FULL or"
4083 + " INTERACT_ACROSS_USERS to interact cross user ");
Jason Monk62062992014-05-06 09:55:28 -04004084 }
4085 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004086 verifyIncomingOp(code);
4087 Preconditions.checkNotNull(token);
Ruben Brunk29931bc2016-03-11 00:24:26 -08004088 setUserRestrictionNoCheck(code, restricted, token, userHandle, exceptionPackages);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004089 }
4090
4091 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
Ruben Brunk29931bc2016-03-11 00:24:26 -08004092 int userHandle, String[] exceptionPackages) {
Svet Ganov442ed572016-08-17 17:29:43 -07004093 synchronized (AppOpsService.this) {
4094 ClientRestrictionState restrictionState = mOpUserRestrictions.get(token);
4095
4096 if (restrictionState == null) {
4097 try {
4098 restrictionState = new ClientRestrictionState(token);
4099 } catch (RemoteException e) {
4100 return;
4101 }
4102 mOpUserRestrictions.put(token, restrictionState);
Ruben Brunk29931bc2016-03-11 00:24:26 -08004103 }
Svet Ganov442ed572016-08-17 17:29:43 -07004104
4105 if (restrictionState.setRestriction(code, restricted, exceptionPackages, userHandle)) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004106 mHandler.sendMessage(PooledLambda.obtainMessage(
Svet Ganov3a95f832018-03-23 17:44:30 -07004107 AppOpsService::notifyWatchersOfChange, this, code, UID_ANY));
Svet Ganov442ed572016-08-17 17:29:43 -07004108 }
4109
4110 if (restrictionState.isDefault()) {
4111 mOpUserRestrictions.remove(token);
4112 restrictionState.destroy();
4113 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08004114 }
Julia Reynoldsbb21c252016-04-05 16:01:49 -04004115 }
4116
Svet Ganov3a95f832018-03-23 17:44:30 -07004117 private void notifyWatchersOfChange(int code, int uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004118 final ArraySet<ModeCallback> clonedCallbacks;
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004119 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004120 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004121 if (callbacks == null) {
4122 return;
4123 }
Dianne Hackborn68d76552017-02-27 15:32:03 -08004124 clonedCallbacks = new ArraySet<>(callbacks);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004125 }
4126
Svet Ganov3a95f832018-03-23 17:44:30 -07004127 notifyOpChanged(clonedCallbacks, code, uid, null);
Jason Monk62062992014-05-06 09:55:28 -04004128 }
4129
4130 @Override
4131 public void removeUser(int userHandle) throws RemoteException {
4132 checkSystemUid("removeUser");
Svet Ganov442ed572016-08-17 17:29:43 -07004133 synchronized (AppOpsService.this) {
4134 final int tokenCount = mOpUserRestrictions.size();
4135 for (int i = tokenCount - 1; i >= 0; i--) {
4136 ClientRestrictionState opRestrictions = mOpUserRestrictions.valueAt(i);
4137 opRestrictions.removeUser(userHandle);
4138 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07004139 removeUidsForUserLocked(userHandle);
4140 }
4141 }
4142
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004143 @Override
4144 public boolean isOperationActive(int code, int uid, String packageName) {
Svet Ganovf7b47252018-02-26 11:11:27 -08004145 if (Binder.getCallingUid() != uid) {
4146 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
4147 != PackageManager.PERMISSION_GRANTED) {
4148 return false;
4149 }
4150 }
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004151 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004152 final String resolvedPackageName = resolvePackageName(uid, packageName);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004153 if (resolvedPackageName == null) {
4154 return false;
4155 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004156 synchronized (AppOpsService.this) {
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004157 for (int i = mClients.size() - 1; i >= 0; i--) {
4158 final ClientState client = mClients.valueAt(i);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004159 for (int j = client.mStartedOps.size() - 1; j >= 0; j--) {
4160 final Op op = client.mStartedOps.get(j);
4161 if (op.op == code && op.uid == uid) return true;
4162 }
4163 }
4164 }
4165 return false;
4166 }
4167
Svet Ganov8455ba22019-01-02 13:05:56 -08004168 @Override
4169 public void setHistoryParameters(@AppOpsManager.HistoricalMode int mode,
4170 long baseSnapshotInterval, int compressionStep) {
4171 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4172 "setHistoryParameters");
4173 // Must not hold the appops lock
4174 mHistoricalRegistry.setHistoryParameters(mode, baseSnapshotInterval, compressionStep);
4175 }
4176
4177 @Override
4178 public void offsetHistory(long offsetMillis) {
4179 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4180 "offsetHistory");
4181 // Must not hold the appops lock
4182 mHistoricalRegistry.offsetHistory(offsetMillis);
4183 }
4184
4185 @Override
4186 public void addHistoricalOps(HistoricalOps ops) {
4187 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4188 "addHistoricalOps");
4189 // Must not hold the appops lock
4190 mHistoricalRegistry.addHistoricalOps(ops);
4191 }
4192
4193 @Override
4194 public void resetHistoryParameters() {
4195 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4196 "resetHistoryParameters");
4197 // Must not hold the appops lock
4198 mHistoricalRegistry.resetHistoryParameters();
4199 }
4200
4201 @Override
4202 public void clearHistory() {
4203 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4204 "clearHistory");
4205 // Must not hold the appops lock
4206 mHistoricalRegistry.clearHistory();
4207 }
4208
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07004209 private void removeUidsForUserLocked(int userHandle) {
4210 for (int i = mUidStates.size() - 1; i >= 0; --i) {
4211 final int uid = mUidStates.keyAt(i);
4212 if (UserHandle.getUserId(uid) == userHandle) {
4213 mUidStates.removeAt(i);
4214 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004215 }
4216 }
4217
Jason Monk62062992014-05-06 09:55:28 -04004218 private void checkSystemUid(String function) {
4219 int uid = Binder.getCallingUid();
4220 if (uid != Process.SYSTEM_UID) {
4221 throw new SecurityException(function + " must by called by the system");
4222 }
4223 }
4224
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004225 private static String resolvePackageName(int uid, String packageName) {
Svet Ganov82f09bc2018-01-12 22:08:40 -08004226 if (uid == Process.ROOT_UID) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004227 return "root";
4228 } else if (uid == Process.SHELL_UID) {
4229 return "com.android.shell";
Svet Ganov82f09bc2018-01-12 22:08:40 -08004230 } else if (uid == Process.MEDIA_UID) {
4231 return "media";
4232 } else if (uid == Process.AUDIOSERVER_UID) {
4233 return "audioserver";
4234 } else if (uid == Process.CAMERASERVER_UID) {
4235 return "cameraserver";
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004236 } else if (uid == Process.SYSTEM_UID && packageName == null) {
4237 return "android";
4238 }
4239 return packageName;
4240 }
4241
Svet Ganov82f09bc2018-01-12 22:08:40 -08004242 private static int resolveUid(String packageName) {
4243 if (packageName == null) {
4244 return -1;
4245 }
4246 switch (packageName) {
4247 case "root":
4248 return Process.ROOT_UID;
4249 case "shell":
4250 return Process.SHELL_UID;
4251 case "media":
4252 return Process.MEDIA_UID;
4253 case "audioserver":
4254 return Process.AUDIOSERVER_UID;
4255 case "cameraserver":
4256 return Process.CAMERASERVER_UID;
4257 }
4258 return -1;
4259 }
4260
Svet Ganov2af57082015-07-30 08:44:20 -07004261 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07004262 String[] packageNames = null;
Philip P. Moltmann159d98b2018-12-20 08:30:53 -08004263
4264 // Very early during boot the package manager is not yet or not yet fully started. At this
4265 // time there are no packages yet.
4266 if (AppGlobals.getPackageManager() != null) {
4267 try {
4268 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
4269 } catch (RemoteException e) {
4270 /* ignore - local call */
4271 }
Svet Ganov2af57082015-07-30 08:44:20 -07004272 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07004273 if (packageNames == null) {
4274 return EmptyArray.STRING;
4275 }
4276 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07004277 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004278
4279 private final class ClientRestrictionState implements DeathRecipient {
4280 private final IBinder token;
4281 SparseArray<boolean[]> perUserRestrictions;
4282 SparseArray<String[]> perUserExcludedPackages;
4283
4284 public ClientRestrictionState(IBinder token)
4285 throws RemoteException {
4286 token.linkToDeath(this, 0);
4287 this.token = token;
4288 }
4289
4290 public boolean setRestriction(int code, boolean restricted,
4291 String[] excludedPackages, int userId) {
4292 boolean changed = false;
4293
4294 if (perUserRestrictions == null && restricted) {
4295 perUserRestrictions = new SparseArray<>();
4296 }
4297
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004298 int[] users;
4299 if (userId == UserHandle.USER_ALL) {
4300 List<UserInfo> liveUsers = UserManager.get(mContext).getUsers(false);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004301
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004302 users = new int[liveUsers.size()];
4303 for (int i = 0; i < liveUsers.size(); i++) {
4304 users[i] = liveUsers.get(i).id;
4305 }
4306 } else {
4307 users = new int[]{userId};
4308 }
4309
4310 if (perUserRestrictions != null) {
4311 int numUsers = users.length;
4312
4313 for (int i = 0; i < numUsers; i++) {
4314 int thisUserId = users[i];
4315
4316 boolean[] userRestrictions = perUserRestrictions.get(thisUserId);
4317 if (userRestrictions == null && restricted) {
4318 userRestrictions = new boolean[AppOpsManager._NUM_OP];
4319 perUserRestrictions.put(thisUserId, userRestrictions);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004320 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004321 if (userRestrictions != null && userRestrictions[code] != restricted) {
4322 userRestrictions[code] = restricted;
4323 if (!restricted && isDefault(userRestrictions)) {
4324 perUserRestrictions.remove(thisUserId);
4325 userRestrictions = null;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004326 }
4327 changed = true;
4328 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004329
4330 if (userRestrictions != null) {
4331 final boolean noExcludedPackages = ArrayUtils.isEmpty(excludedPackages);
4332 if (perUserExcludedPackages == null && !noExcludedPackages) {
4333 perUserExcludedPackages = new SparseArray<>();
4334 }
4335 if (perUserExcludedPackages != null && !Arrays.equals(excludedPackages,
4336 perUserExcludedPackages.get(thisUserId))) {
4337 if (noExcludedPackages) {
4338 perUserExcludedPackages.remove(thisUserId);
4339 if (perUserExcludedPackages.size() <= 0) {
4340 perUserExcludedPackages = null;
4341 }
4342 } else {
4343 perUserExcludedPackages.put(thisUserId, excludedPackages);
4344 }
4345 changed = true;
4346 }
4347 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004348 }
4349 }
4350
4351 return changed;
4352 }
4353
4354 public boolean hasRestriction(int restriction, String packageName, int userId) {
4355 if (perUserRestrictions == null) {
4356 return false;
4357 }
4358 boolean[] restrictions = perUserRestrictions.get(userId);
4359 if (restrictions == null) {
4360 return false;
4361 }
4362 if (!restrictions[restriction]) {
4363 return false;
4364 }
4365 if (perUserExcludedPackages == null) {
4366 return true;
4367 }
4368 String[] perUserExclusions = perUserExcludedPackages.get(userId);
4369 if (perUserExclusions == null) {
4370 return true;
4371 }
4372 return !ArrayUtils.contains(perUserExclusions, packageName);
4373 }
4374
4375 public void removeUser(int userId) {
4376 if (perUserExcludedPackages != null) {
4377 perUserExcludedPackages.remove(userId);
4378 if (perUserExcludedPackages.size() <= 0) {
4379 perUserExcludedPackages = null;
4380 }
4381 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07004382 if (perUserRestrictions != null) {
4383 perUserRestrictions.remove(userId);
4384 if (perUserRestrictions.size() <= 0) {
4385 perUserRestrictions = null;
4386 }
4387 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004388 }
4389
4390 public boolean isDefault() {
4391 return perUserRestrictions == null || perUserRestrictions.size() <= 0;
4392 }
4393
4394 @Override
4395 public void binderDied() {
4396 synchronized (AppOpsService.this) {
4397 mOpUserRestrictions.remove(token);
4398 if (perUserRestrictions == null) {
4399 return;
4400 }
4401 final int userCount = perUserRestrictions.size();
4402 for (int i = 0; i < userCount; i++) {
4403 final boolean[] restrictions = perUserRestrictions.valueAt(i);
4404 final int restrictionCount = restrictions.length;
4405 for (int j = 0; j < restrictionCount; j++) {
4406 if (restrictions[j]) {
4407 final int changedCode = j;
Svet Ganov3a95f832018-03-23 17:44:30 -07004408 mHandler.post(() -> notifyWatchersOfChange(changedCode, UID_ANY));
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004409 }
4410 }
4411 }
4412 destroy();
4413 }
4414 }
4415
4416 public void destroy() {
4417 token.unlinkToDeath(this, 0);
4418 }
4419
4420 private boolean isDefault(boolean[] array) {
4421 if (ArrayUtils.isEmpty(array)) {
4422 return true;
4423 }
4424 for (boolean value : array) {
4425 if (value) {
4426 return false;
4427 }
4428 }
4429 return true;
4430 }
4431 }
Dianne Hackbornd5254412018-05-11 18:02:58 -07004432
4433 private final class AppOpsManagerInternalImpl extends AppOpsManagerInternal {
4434 @Override public void setDeviceAndProfileOwners(SparseIntArray owners) {
4435 synchronized (AppOpsService.this) {
4436 mProfileOwners = owners;
4437 }
4438 }
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07004439
4440 @Override
Philip P. Moltmann159d98b2018-12-20 08:30:53 -08004441 public void setUidMode(int code, int uid, int mode) {
4442 AppOpsService.this.setUidMode(code, uid, mode);
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07004443 }
Philip P. Moltmanndde07852019-01-25 16:42:36 -08004444
4445 @Override
4446 public void setAllPkgModesToDefault(int code, int uid) {
4447 AppOpsService.this.setAllPkgModesToDefault(code, uid);
4448 }
Dianne Hackbornd5254412018-05-11 18:02:58 -07004449 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004450}