blob: 059fc57787ae2c65b8129c42df2db6e54d83c6e0 [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
Suprabh Shukla3017fe42018-11-08 19:00:01 -080019import static android.app.AppOpsManager.OP_PLAY_AUDIO;
Svet Ganov8455ba22019-01-02 13:05:56 -080020import static android.app.AppOpsManager.OP_NONE;
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;
Dianne Hackbornd5254412018-05-11 18:02:58 -070041import android.app.AppOpsManagerInternal;
Svet Ganovd873ae62018-06-25 16:39:23 -070042import android.app.AppOpsManagerInternal.CheckOpsDelegate;
Suprabh Shukla3017fe42018-11-08 19:00:01 -080043import android.content.BroadcastReceiver;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070044import android.content.ContentResolver;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070045import android.content.Context;
Suprabh Shukla3017fe42018-11-08 19:00:01 -080046import android.content.Intent;
47import android.content.IntentFilter;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070048import android.content.pm.ApplicationInfo;
49import android.content.pm.IPackageManager;
50import android.content.pm.PackageManager;
51import android.content.pm.PackageManagerInternal;
52import android.content.pm.UserInfo;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070053import android.database.ContentObserver;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070054import android.media.AudioAttributes;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070055import android.net.Uri;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070056import android.os.AsyncTask;
57import android.os.Binder;
58import android.os.Bundle;
59import android.os.Handler;
60import android.os.IBinder;
61import android.os.Process;
Svet Ganov8455ba22019-01-02 13:05:56 -080062import android.os.RemoteCallback;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070063import android.os.RemoteException;
64import android.os.ResultReceiver;
65import android.os.ServiceManager;
66import android.os.ShellCallback;
67import android.os.ShellCommand;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -070068import android.os.SystemClock;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070069import android.os.UserHandle;
70import android.os.UserManager;
Sudheer Shanka98cb3f02018-08-17 16:10:29 -070071import android.os.storage.StorageManager;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070072import android.os.storage.StorageManagerInternal;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070073import android.provider.Settings;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070074import android.util.ArrayMap;
75import android.util.ArraySet;
76import android.util.AtomicFile;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070077import android.util.KeyValueListParser;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070078import android.util.Slog;
79import android.util.SparseArray;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -070080import android.util.SparseBooleanArray;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070081import android.util.SparseIntArray;
82import android.util.TimeUtils;
83import android.util.Xml;
84
Todd Kennedy556efba2018-11-15 07:43:55 -080085import com.android.internal.annotations.GuardedBy;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070086import com.android.internal.annotations.VisibleForTesting;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -080087import com.android.internal.app.IAppOpsActiveCallback;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070088import com.android.internal.app.IAppOpsCallback;
Svet Ganovb3d2ae22018-12-17 22:06:15 -080089import com.android.internal.app.IAppOpsNotedCallback;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070090import com.android.internal.app.IAppOpsService;
91import com.android.internal.os.Zygote;
92import com.android.internal.util.ArrayUtils;
93import com.android.internal.util.DumpUtils;
94import com.android.internal.util.FastXmlSerializer;
95import com.android.internal.util.Preconditions;
96import com.android.internal.util.XmlUtils;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -080097import com.android.internal.util.function.pooled.PooledLambda;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -050098
Svet Ganov8455ba22019-01-02 13:05:56 -080099import com.android.server.LocalServices;
100import com.android.server.LockGuard;
Philip P. Moltmanne683f192017-06-23 14:05:04 -0700101import libcore.util.EmptyArray;
102
103import org.xmlpull.v1.XmlPullParser;
104import org.xmlpull.v1.XmlPullParserException;
105import org.xmlpull.v1.XmlSerializer;
106
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800107import java.io.File;
108import java.io.FileDescriptor;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800109import java.io.FileInputStream;
110import java.io.FileNotFoundException;
111import java.io.FileOutputStream;
112import java.io.IOException;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800113import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100114import java.nio.charset.StandardCharsets;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700115import java.text.SimpleDateFormat;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800116import java.util.ArrayList;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -0700117import java.util.Arrays;
Svetoslav215b44a2015-08-04 19:03:40 -0700118import java.util.Collections;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700119import java.util.Date;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800120import java.util.HashMap;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800121import java.util.Iterator;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800122import java.util.List;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700123import java.util.Map;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800124
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800125public class AppOpsService extends IAppOpsService.Stub {
126 static final String TAG = "AppOps";
Dianne Hackborn35654b62013-01-14 17:38:02 -0800127 static final boolean DEBUG = false;
128
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700129 private static final int NO_VERSION = -1;
130 /** Increment by one every time and add the corresponding upgrade logic in
131 * {@link #upgradeLocked(int)} below. The first version was 1 */
132 private static final int CURRENT_VERSION = 1;
133
Dianne Hackborn35654b62013-01-14 17:38:02 -0800134 // Write at most every 30 minutes.
135 static final long WRITE_DELAY = DEBUG ? 1000 : 30*60*1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800136
Svet Ganov3a95f832018-03-23 17:44:30 -0700137 // Constant meaning that any UID should be matched when dispatching callbacks
138 private static final int UID_ANY = -2;
139
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700140 // Map from process states to the uid states we track.
141 private static final int[] PROCESS_STATE_TO_UID_STATE = new int[] {
142 UID_STATE_PERSISTENT, // ActivityManager.PROCESS_STATE_PERSISTENT
143 UID_STATE_PERSISTENT, // ActivityManager.PROCESS_STATE_PERSISTENT_UI
144 UID_STATE_TOP, // ActivityManager.PROCESS_STATE_TOP
Amith Yamasania0a30a12019-01-22 11:38:06 -0800145 UID_STATE_FOREGROUND_SERVICE_LOCATION,
146 // ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE_LOCATION
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700147 UID_STATE_FOREGROUND_SERVICE, // ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
148 UID_STATE_FOREGROUND, // ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
149 UID_STATE_FOREGROUND, // ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND
150 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND
151 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_TRANSIENT_BACKGROUND
152 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_BACKUP
153 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_SERVICE
154 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_RECEIVER
155 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_TOP_SLEEPING
156 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_HEAVY_WEIGHT
157 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_HOME
158 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_LAST_ACTIVITY
159 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY
160 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT
161 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_RECENT
162 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_EMPTY
163 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_NONEXISTENT
164 };
165
166 static final String[] UID_STATE_NAMES = new String[] {
167 "pers ", // UID_STATE_PERSISTENT
168 "top ", // UID_STATE_TOP
Amith Yamasania0a30a12019-01-22 11:38:06 -0800169 "fgsvcl", // UID_STATE_FOREGROUND_SERVICE_LOCATION
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700170 "fgsvc", // UID_STATE_FOREGROUND_SERVICE
171 "fg ", // UID_STATE_FOREGROUND
172 "bg ", // UID_STATE_BACKGROUND
173 "cch ", // UID_STATE_CACHED
174 };
175
176 static final String[] UID_STATE_TIME_ATTRS = new String[] {
177 "tp", // UID_STATE_PERSISTENT
178 "tt", // UID_STATE_TOP
Amith Yamasania0a30a12019-01-22 11:38:06 -0800179 "tfsl", // UID_STATE_FOREGROUND_SERVICE_LOCATION
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700180 "tfs", // UID_STATE_FOREGROUND_SERVICE
181 "tf", // UID_STATE_FOREGROUND
182 "tb", // UID_STATE_BACKGROUND
183 "tc", // UID_STATE_CACHED
184 };
185
186 static final String[] UID_STATE_REJECT_ATTRS = new String[] {
187 "rp", // UID_STATE_PERSISTENT
188 "rt", // UID_STATE_TOP
Amith Yamasania0a30a12019-01-22 11:38:06 -0800189 "rfsl", // UID_STATE_FOREGROUND_SERVICE_LOCATION
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700190 "rfs", // UID_STATE_FOREGROUND_SERVICE
191 "rf", // UID_STATE_FOREGROUND
192 "rb", // UID_STATE_BACKGROUND
193 "rc", // UID_STATE_CACHED
194 };
195
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800196 Context mContext;
197 final AtomicFile mFile;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800198 final Handler mHandler;
199
Dianne Hackbornd5254412018-05-11 18:02:58 -0700200 private final AppOpsManagerInternalImpl mAppOpsManagerInternal
201 = new AppOpsManagerInternalImpl();
202
Dianne Hackborn35654b62013-01-14 17:38:02 -0800203 boolean mWriteScheduled;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800204 boolean mFastWriteScheduled;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800205 final Runnable mWriteRunner = new Runnable() {
206 public void run() {
207 synchronized (AppOpsService.this) {
208 mWriteScheduled = false;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800209 mFastWriteScheduled = false;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800210 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
211 @Override protected Void doInBackground(Void... params) {
212 writeState();
213 return null;
214 }
215 };
216 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
217 }
218 }
219 };
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800220
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700221 @VisibleForTesting
222 final SparseArray<UidState> mUidStates = new SparseArray<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800223
Svet Ganov8455ba22019-01-02 13:05:56 -0800224 private final HistoricalRegistry mHistoricalRegistry = new HistoricalRegistry(this);
225
Dianne Hackborn9fb93502018-06-18 12:29:44 -0700226 long mLastRealtime;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700227
Ruben Brunk29931bc2016-03-11 00:24:26 -0800228 /*
229 * These are app op restrictions imposed per user from various parties.
Ruben Brunk29931bc2016-03-11 00:24:26 -0800230 */
Svetoslav Ganova8bbd762016-05-13 17:08:16 -0700231 private final ArrayMap<IBinder, ClientRestrictionState> mOpUserRestrictions = new ArrayMap<>();
Jason Monk62062992014-05-06 09:55:28 -0400232
Dianne Hackbornd5254412018-05-11 18:02:58 -0700233 SparseIntArray mProfileOwners;
234
Todd Kennedy556efba2018-11-15 07:43:55 -0800235 @GuardedBy("this")
Svet Ganovd873ae62018-06-25 16:39:23 -0700236 private CheckOpsDelegate mCheckOpsDelegate;
237
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700238 /**
239 * All times are in milliseconds. These constants are kept synchronized with the system
240 * global Settings. Any access to this class or its fields should be done while
241 * holding the AppOpsService lock.
242 */
243 private final class Constants extends ContentObserver {
244 // Key names stored in the settings value.
Dianne Hackborne93ab412018-05-14 17:52:30 -0700245 private static final String KEY_TOP_STATE_SETTLE_TIME = "top_state_settle_time";
246 private static final String KEY_FG_SERVICE_STATE_SETTLE_TIME
247 = "fg_service_state_settle_time";
248 private static final String KEY_BG_STATE_SETTLE_TIME = "bg_state_settle_time";
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700249
250 /**
Dianne Hackborne93ab412018-05-14 17:52:30 -0700251 * How long we want for a drop in uid state from top to settle before applying it.
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700252 * @see Settings.Global#APP_OPS_CONSTANTS
Dianne Hackborne93ab412018-05-14 17:52:30 -0700253 * @see #KEY_TOP_STATE_SETTLE_TIME
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700254 */
Dianne Hackborne93ab412018-05-14 17:52:30 -0700255 public long TOP_STATE_SETTLE_TIME;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700256
Dianne Hackborne93ab412018-05-14 17:52:30 -0700257 /**
258 * How long we want for a drop in uid state from foreground to settle before applying it.
259 * @see Settings.Global#APP_OPS_CONSTANTS
260 * @see #KEY_FG_SERVICE_STATE_SETTLE_TIME
261 */
262 public long FG_SERVICE_STATE_SETTLE_TIME;
263
264 /**
265 * How long we want for a drop in uid state from background to settle before applying it.
266 * @see Settings.Global#APP_OPS_CONSTANTS
267 * @see #KEY_BG_STATE_SETTLE_TIME
268 */
269 public long BG_STATE_SETTLE_TIME;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700270
271 private final KeyValueListParser mParser = new KeyValueListParser(',');
272 private ContentResolver mResolver;
273
274 public Constants(Handler handler) {
275 super(handler);
276 updateConstants();
277 }
278
279 public void startMonitoring(ContentResolver resolver) {
280 mResolver = resolver;
281 mResolver.registerContentObserver(
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700282 Settings.Global.getUriFor(Settings.Global.APP_OPS_CONSTANTS),
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700283 false, this);
284 updateConstants();
285 }
286
287 @Override
288 public void onChange(boolean selfChange, Uri uri) {
289 updateConstants();
290 }
291
292 private void updateConstants() {
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700293 String value = mResolver != null ? Settings.Global.getString(mResolver,
294 Settings.Global.APP_OPS_CONSTANTS) : "";
295
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700296 synchronized (AppOpsService.this) {
297 try {
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700298 mParser.setString(value);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700299 } catch (IllegalArgumentException e) {
300 // Failed to parse the settings string, log this and move on
301 // with defaults.
302 Slog.e(TAG, "Bad app ops settings", e);
303 }
Dianne Hackborne93ab412018-05-14 17:52:30 -0700304 TOP_STATE_SETTLE_TIME = mParser.getDurationMillis(
305 KEY_TOP_STATE_SETTLE_TIME, 30 * 1000L);
306 FG_SERVICE_STATE_SETTLE_TIME = mParser.getDurationMillis(
307 KEY_FG_SERVICE_STATE_SETTLE_TIME, 10 * 1000L);
308 BG_STATE_SETTLE_TIME = mParser.getDurationMillis(
309 KEY_BG_STATE_SETTLE_TIME, 1 * 1000L);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700310 }
311 }
312
313 void dump(PrintWriter pw) {
314 pw.println(" Settings:");
315
Dianne Hackborne93ab412018-05-14 17:52:30 -0700316 pw.print(" "); pw.print(KEY_TOP_STATE_SETTLE_TIME); pw.print("=");
317 TimeUtils.formatDuration(TOP_STATE_SETTLE_TIME, pw);
Dianne Hackbornb94d82f2018-05-16 17:03:01 -0700318 pw.println();
Dianne Hackborne93ab412018-05-14 17:52:30 -0700319 pw.print(" "); pw.print(KEY_FG_SERVICE_STATE_SETTLE_TIME); pw.print("=");
320 TimeUtils.formatDuration(FG_SERVICE_STATE_SETTLE_TIME, pw);
Dianne Hackbornb94d82f2018-05-16 17:03:01 -0700321 pw.println();
Dianne Hackborne93ab412018-05-14 17:52:30 -0700322 pw.print(" "); pw.print(KEY_BG_STATE_SETTLE_TIME); pw.print("=");
323 TimeUtils.formatDuration(BG_STATE_SETTLE_TIME, pw);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700324 pw.println();
325 }
326 }
327
328 private final Constants mConstants;
329
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700330 @VisibleForTesting
331 static final class UidState {
Svet Ganov2af57082015-07-30 08:44:20 -0700332 public final int uid;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700333
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700334 public int state = UID_STATE_CACHED;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700335 public int pendingState = UID_STATE_CACHED;
336 public long pendingStateCommitTime;
337
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700338 public int startNesting;
Svet Ganov2af57082015-07-30 08:44:20 -0700339 public ArrayMap<String, Ops> pkgOps;
340 public SparseIntArray opModes;
341
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700342 // true indicates there is an interested observer, false there isn't but it has such an op
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700343 public SparseBooleanArray foregroundOps;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700344 public boolean hasForegroundWatchers;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700345
Svet Ganov2af57082015-07-30 08:44:20 -0700346 public UidState(int uid) {
347 this.uid = uid;
348 }
349
350 public void clear() {
351 pkgOps = null;
352 opModes = null;
353 }
354
355 public boolean isDefault() {
356 return (pkgOps == null || pkgOps.isEmpty())
357 && (opModes == null || opModes.size() <= 0);
358 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700359
360 int evalMode(int mode) {
361 if (mode == AppOpsManager.MODE_FOREGROUND) {
Dianne Hackborne93ab412018-05-14 17:52:30 -0700362 return state <= UID_STATE_LAST_NON_RESTRICTED
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700363 ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED;
364 }
365 return mode;
366 }
367
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700368 private void evalForegroundWatchers(int op, SparseArray<ArraySet<ModeCallback>> watchers,
369 SparseBooleanArray which) {
370 boolean curValue = which.get(op, false);
371 ArraySet<ModeCallback> callbacks = watchers.get(op);
372 if (callbacks != null) {
373 for (int cbi = callbacks.size() - 1; !curValue && cbi >= 0; cbi--) {
374 if ((callbacks.valueAt(cbi).mFlags
375 & AppOpsManager.WATCH_FOREGROUND_CHANGES) != 0) {
376 hasForegroundWatchers = true;
377 curValue = true;
378 }
379 }
380 }
381 which.put(op, curValue);
382 }
383
384 public void evalForegroundOps(SparseArray<ArraySet<ModeCallback>> watchers) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700385 SparseBooleanArray which = null;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700386 hasForegroundWatchers = false;
387 if (opModes != null) {
388 for (int i = opModes.size() - 1; i >= 0; i--) {
389 if (opModes.valueAt(i) == AppOpsManager.MODE_FOREGROUND) {
390 if (which == null) {
391 which = new SparseBooleanArray();
392 }
393 evalForegroundWatchers(opModes.keyAt(i), watchers, which);
394 }
395 }
396 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700397 if (pkgOps != null) {
398 for (int i = pkgOps.size() - 1; i >= 0; i--) {
399 Ops ops = pkgOps.valueAt(i);
400 for (int j = ops.size() - 1; j >= 0; j--) {
401 if (ops.valueAt(j).mode == AppOpsManager.MODE_FOREGROUND) {
402 if (which == null) {
403 which = new SparseBooleanArray();
404 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700405 evalForegroundWatchers(ops.keyAt(j), watchers, which);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700406 }
407 }
408 }
409 }
410 foregroundOps = which;
411 }
Svet Ganov2af57082015-07-30 08:44:20 -0700412 }
413
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700414 final static class Ops extends SparseArray<Op> {
415 final String packageName;
416 final UidState uidState;
417 final boolean isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800418
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700419 Ops(String _packageName, UidState _uidState, boolean _isPrivileged) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800420 packageName = _packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700421 uidState = _uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400422 isPrivileged = _isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800423 }
424 }
425
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700426 final static class Op {
427 final UidState uidState;
428 final int uid;
429 final String packageName;
430 final int op;
431 int proxyUid = -1;
432 String proxyPackageName;
433 int mode;
434 int duration;
435 long time[] = new long[_NUM_UID_STATE];
436 long rejectTime[] = new long[_NUM_UID_STATE];
437 int startNesting;
438 long startRealtime;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800439
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700440 Op(UidState _uidState, String _packageName, int _op) {
441 uidState = _uidState;
442 uid = _uidState.uid;
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700443 packageName = _packageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800444 op = _op;
David Braunf5d83192013-09-16 13:43:51 -0700445 mode = AppOpsManager.opToDefaultMode(op);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800446 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700447
448 boolean hasAnyTime() {
449 for (int i = 0; i < AppOpsManager._NUM_UID_STATE; i++) {
450 if (time[i] != 0) {
451 return true;
452 }
453 if (rejectTime[i] != 0) {
454 return true;
455 }
456 }
457 return false;
458 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700459
460 int getMode() {
461 return uidState.evalMode(mode);
462 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800463 }
464
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800465 final SparseArray<ArraySet<ModeCallback>> mOpModeWatchers = new SparseArray<>();
466 final ArrayMap<String, ArraySet<ModeCallback>> mPackageModeWatchers = new ArrayMap<>();
467 final ArrayMap<IBinder, ModeCallback> mModeWatchers = new ArrayMap<>();
468 final ArrayMap<IBinder, SparseArray<ActiveCallback>> mActiveWatchers = new ArrayMap<>();
Svet Ganovb3d2ae22018-12-17 22:06:15 -0800469 final ArrayMap<IBinder, SparseArray<NotedCallback>> mNotedWatchers = new ArrayMap<>();
Dianne Hackborn68d76552017-02-27 15:32:03 -0800470 final SparseArray<SparseArray<Restriction>> mAudioRestrictions = new SparseArray<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800471
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700472 final class ModeCallback implements DeathRecipient {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800473 final IAppOpsCallback mCallback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700474 final int mWatchingUid;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700475 final int mFlags;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700476 final int mCallingUid;
477 final int mCallingPid;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800478
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700479 ModeCallback(IAppOpsCallback callback, int watchingUid, int flags, int callingUid,
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700480 int callingPid) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800481 mCallback = callback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700482 mWatchingUid = watchingUid;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700483 mFlags = flags;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700484 mCallingUid = callingUid;
485 mCallingPid = callingPid;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800486 try {
487 mCallback.asBinder().linkToDeath(this, 0);
488 } catch (RemoteException e) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -0800489 /*ignored*/
Dianne Hackbornc2293022013-02-06 23:14:49 -0800490 }
491 }
492
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700493 public boolean isWatchingUid(int uid) {
494 return uid == UID_ANY || mWatchingUid < 0 || mWatchingUid == uid;
495 }
496
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700497 @Override
498 public String toString() {
499 StringBuilder sb = new StringBuilder(128);
500 sb.append("ModeCallback{");
501 sb.append(Integer.toHexString(System.identityHashCode(this)));
502 sb.append(" watchinguid=");
503 UserHandle.formatUid(sb, mWatchingUid);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700504 sb.append(" flags=0x");
505 sb.append(Integer.toHexString(mFlags));
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700506 sb.append(" from uid=");
507 UserHandle.formatUid(sb, mCallingUid);
508 sb.append(" pid=");
509 sb.append(mCallingPid);
510 sb.append('}');
511 return sb.toString();
512 }
513
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700514 void unlinkToDeath() {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800515 mCallback.asBinder().unlinkToDeath(this, 0);
516 }
517
518 @Override
519 public void binderDied() {
520 stopWatchingMode(mCallback);
521 }
522 }
523
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700524 final class ActiveCallback implements DeathRecipient {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800525 final IAppOpsActiveCallback mCallback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700526 final int mWatchingUid;
527 final int mCallingUid;
528 final int mCallingPid;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800529
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700530 ActiveCallback(IAppOpsActiveCallback callback, int watchingUid, int callingUid,
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700531 int callingPid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800532 mCallback = callback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700533 mWatchingUid = watchingUid;
534 mCallingUid = callingUid;
535 mCallingPid = callingPid;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800536 try {
537 mCallback.asBinder().linkToDeath(this, 0);
538 } catch (RemoteException e) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -0800539 /*ignored*/
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800540 }
541 }
542
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700543 @Override
544 public String toString() {
545 StringBuilder sb = new StringBuilder(128);
546 sb.append("ActiveCallback{");
547 sb.append(Integer.toHexString(System.identityHashCode(this)));
548 sb.append(" watchinguid=");
549 UserHandle.formatUid(sb, mWatchingUid);
550 sb.append(" from uid=");
551 UserHandle.formatUid(sb, mCallingUid);
552 sb.append(" pid=");
553 sb.append(mCallingPid);
554 sb.append('}');
555 return sb.toString();
556 }
557
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700558 void destroy() {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800559 mCallback.asBinder().unlinkToDeath(this, 0);
560 }
561
562 @Override
563 public void binderDied() {
564 stopWatchingActive(mCallback);
565 }
566 }
567
Svet Ganovb3d2ae22018-12-17 22:06:15 -0800568 final class NotedCallback implements DeathRecipient {
569 final IAppOpsNotedCallback mCallback;
570 final int mWatchingUid;
571 final int mCallingUid;
572 final int mCallingPid;
573
574 NotedCallback(IAppOpsNotedCallback callback, int watchingUid, int callingUid,
575 int callingPid) {
576 mCallback = callback;
577 mWatchingUid = watchingUid;
578 mCallingUid = callingUid;
579 mCallingPid = callingPid;
580 try {
581 mCallback.asBinder().linkToDeath(this, 0);
582 } catch (RemoteException e) {
583 /*ignored*/
584 }
585 }
586
587 @Override
588 public String toString() {
589 StringBuilder sb = new StringBuilder(128);
590 sb.append("NotedCallback{");
591 sb.append(Integer.toHexString(System.identityHashCode(this)));
592 sb.append(" watchinguid=");
593 UserHandle.formatUid(sb, mWatchingUid);
594 sb.append(" from uid=");
595 UserHandle.formatUid(sb, mCallingUid);
596 sb.append(" pid=");
597 sb.append(mCallingPid);
598 sb.append('}');
599 return sb.toString();
600 }
601
602 void destroy() {
603 mCallback.asBinder().unlinkToDeath(this, 0);
604 }
605
606 @Override
607 public void binderDied() {
608 stopWatchingNoted(mCallback);
609 }
610 }
611
Svet Ganova7a0db62018-02-27 20:08:01 -0800612 final ArrayMap<IBinder, ClientState> mClients = new ArrayMap<>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700613
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700614 final class ClientState extends Binder implements DeathRecipient {
Svet Ganovf7b47252018-02-26 11:11:27 -0800615 final ArrayList<Op> mStartedOps = new ArrayList<>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700616 final IBinder mAppToken;
617 final int mPid;
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700618
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700619 ClientState(IBinder appToken) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700620 mAppToken = appToken;
621 mPid = Binder.getCallingPid();
Svet Ganovf7b47252018-02-26 11:11:27 -0800622 // Watch only for remote processes dying
623 if (!(appToken instanceof Binder)) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700624 try {
625 mAppToken.linkToDeath(this, 0);
626 } catch (RemoteException e) {
Svet Ganovf7b47252018-02-26 11:11:27 -0800627 /* do nothing */
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700628 }
629 }
630 }
631
632 @Override
633 public String toString() {
634 return "ClientState{" +
635 "mAppToken=" + mAppToken +
Svet Ganovf7b47252018-02-26 11:11:27 -0800636 ", " + "pid=" + mPid +
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700637 '}';
638 }
639
640 @Override
641 public void binderDied() {
642 synchronized (AppOpsService.this) {
643 for (int i=mStartedOps.size()-1; i>=0; i--) {
Svet Ganova7a0db62018-02-27 20:08:01 -0800644 finishOperationLocked(mStartedOps.get(i), /*finishNested*/ true);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700645 }
646 mClients.remove(mAppToken);
647 }
648 }
649 }
650
Jeff Brown6f357d32014-01-15 20:40:55 -0800651 public AppOpsService(File storagePath, Handler handler) {
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600652 LockGuard.installLock(this, LockGuard.INDEX_APP_OPS);
Dianne Hackborne17b4452018-01-10 13:15:40 -0800653 mFile = new AtomicFile(storagePath, "appops");
Jeff Brown6f357d32014-01-15 20:40:55 -0800654 mHandler = handler;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700655 mConstants = new Constants(mHandler);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800656 readState();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800657 }
David Braunf5d83192013-09-16 13:43:51 -0700658
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800659 public void publish(Context context) {
660 mContext = context;
661 ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
Dianne Hackbornd5254412018-05-11 18:02:58 -0700662 LocalServices.addService(AppOpsManagerInternal.class, mAppOpsManagerInternal);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800663 }
664
Dianne Hackborn514074f2013-02-11 10:52:46 -0800665 public void systemReady() {
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700666 mConstants.startMonitoring(mContext.getContentResolver());
Svet Ganov8455ba22019-01-02 13:05:56 -0800667 mHistoricalRegistry.systemReady(mContext.getContentResolver());
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700668
Dianne Hackborn514074f2013-02-11 10:52:46 -0800669 synchronized (this) {
670 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700671 for (int i = mUidStates.size() - 1; i >= 0; i--) {
672 UidState uidState = mUidStates.valueAt(i);
673
674 String[] packageNames = getPackagesForUid(uidState.uid);
675 if (ArrayUtils.isEmpty(packageNames)) {
676 uidState.clear();
677 mUidStates.removeAt(i);
678 changed = true;
679 continue;
680 }
681
682 ArrayMap<String, Ops> pkgs = uidState.pkgOps;
683 if (pkgs == null) {
684 continue;
685 }
686
Dianne Hackborn514074f2013-02-11 10:52:46 -0800687 Iterator<Ops> it = pkgs.values().iterator();
688 while (it.hasNext()) {
689 Ops ops = it.next();
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700690 int curUid = -1;
Dianne Hackborn514074f2013-02-11 10:52:46 -0800691 try {
Jeff Sharkeycd654482016-01-08 17:42:11 -0700692 curUid = AppGlobals.getPackageManager().getPackageUid(ops.packageName,
693 PackageManager.MATCH_UNINSTALLED_PACKAGES,
Svet Ganov2af57082015-07-30 08:44:20 -0700694 UserHandle.getUserId(ops.uidState.uid));
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700695 } catch (RemoteException ignored) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800696 }
Svet Ganov2af57082015-07-30 08:44:20 -0700697 if (curUid != ops.uidState.uid) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800698 Slog.i(TAG, "Pruning old package " + ops.packageName
Svet Ganov2af57082015-07-30 08:44:20 -0700699 + "/" + ops.uidState + ": new uid=" + curUid);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800700 it.remove();
701 changed = true;
702 }
703 }
Svet Ganov2af57082015-07-30 08:44:20 -0700704
705 if (uidState.isDefault()) {
706 mUidStates.removeAt(i);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800707 }
708 }
709 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800710 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800711 }
712 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700713
Suprabh Shukla3017fe42018-11-08 19:00:01 -0800714 final IntentFilter packageSuspendFilter = new IntentFilter();
715 packageSuspendFilter.addAction(Intent.ACTION_PACKAGES_UNSUSPENDED);
716 packageSuspendFilter.addAction(Intent.ACTION_PACKAGES_SUSPENDED);
717 mContext.registerReceiver(new BroadcastReceiver() {
718 @Override
719 public void onReceive(Context context, Intent intent) {
720 final int[] changedUids = intent.getIntArrayExtra(Intent.EXTRA_CHANGED_UID_LIST);
721 final String[] changedPkgs = intent.getStringArrayExtra(
722 Intent.EXTRA_CHANGED_PACKAGE_LIST);
723 final ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(OP_PLAY_AUDIO);
724 for (int i = 0; i < changedUids.length; i++) {
725 final int changedUid = changedUids[i];
726 final String changedPkg = changedPkgs[i];
727 // We trust packagemanager to insert matching uid and packageNames in the extras
728 mHandler.sendMessage(PooledLambda.obtainMessage(AppOpsService::notifyOpChanged,
729 AppOpsService.this, callbacks, OP_PLAY_AUDIO, changedUid, changedPkg));
730 }
731 }
732 }, packageSuspendFilter);
733
Suprabh Shuklaaef25132017-01-23 18:09:03 -0800734 PackageManagerInternal packageManagerInternal = LocalServices.getService(
735 PackageManagerInternal.class);
736 packageManagerInternal.setExternalSourcesPolicy(
737 new PackageManagerInternal.ExternalSourcesPolicy() {
738 @Override
739 public int getPackageTrustedToInstallApps(String packageName, int uid) {
740 int appOpMode = checkOperation(AppOpsManager.OP_REQUEST_INSTALL_PACKAGES,
741 uid, packageName);
742 switch (appOpMode) {
743 case AppOpsManager.MODE_ALLOWED:
744 return PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
745 case AppOpsManager.MODE_ERRORED:
746 return PackageManagerInternal.ExternalSourcesPolicy.USER_BLOCKED;
747 default:
748 return PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT;
749 }
750 }
751 });
752
Jeff Sharkey10ec9d82018-11-28 14:52:45 -0700753 if (!StorageManager.hasIsolatedStorage()) {
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700754 StorageManagerInternal storageManagerInternal = LocalServices.getService(
755 StorageManagerInternal.class);
756 storageManagerInternal.addExternalStoragePolicy(
757 new StorageManagerInternal.ExternalStorageMountPolicy() {
758 @Override
759 public int getMountMode(int uid, String packageName) {
760 if (Process.isIsolated(uid)) {
761 return Zygote.MOUNT_EXTERNAL_NONE;
762 }
763 if (noteOperation(AppOpsManager.OP_READ_EXTERNAL_STORAGE, uid,
764 packageName) != AppOpsManager.MODE_ALLOWED) {
765 return Zygote.MOUNT_EXTERNAL_NONE;
766 }
767 if (noteOperation(AppOpsManager.OP_WRITE_EXTERNAL_STORAGE, uid,
768 packageName) != AppOpsManager.MODE_ALLOWED) {
769 return Zygote.MOUNT_EXTERNAL_READ;
770 }
771 return Zygote.MOUNT_EXTERNAL_WRITE;
Svet Ganov6ee871e2015-07-10 14:29:33 -0700772 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700773
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700774 @Override
775 public boolean hasExternalStorage(int uid, String packageName) {
776 final int mountMode = getMountMode(uid, packageName);
777 return mountMode == Zygote.MOUNT_EXTERNAL_READ
778 || mountMode == Zygote.MOUNT_EXTERNAL_WRITE;
779 }
780 });
781 }
Dianne Hackborn514074f2013-02-11 10:52:46 -0800782 }
783
784 public void packageRemoved(int uid, String packageName) {
785 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700786 UidState uidState = mUidStates.get(uid);
787 if (uidState == null) {
788 return;
789 }
790
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800791 Ops ops = null;
Svet Ganov2af57082015-07-30 08:44:20 -0700792
793 // Remove any package state if such.
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800794 if (uidState.pkgOps != null) {
795 ops = uidState.pkgOps.remove(packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700796 }
797
798 // If we just nuked the last package state check if the UID is valid.
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800799 if (ops != null && uidState.pkgOps.isEmpty()
Svet Ganov2af57082015-07-30 08:44:20 -0700800 && getPackagesForUid(uid).length <= 0) {
801 mUidStates.remove(uid);
802 }
803
Svet Ganova7a0db62018-02-27 20:08:01 -0800804 // Finish ops other packages started on behalf of the package.
805 final int clientCount = mClients.size();
806 for (int i = 0; i < clientCount; i++) {
807 final ClientState client = mClients.valueAt(i);
808 if (client.mStartedOps == null) {
809 continue;
810 }
811 final int opCount = client.mStartedOps.size();
812 for (int j = opCount - 1; j >= 0; j--) {
813 final Op op = client.mStartedOps.get(j);
814 if (uid == op.uid && packageName.equals(op.packageName)) {
815 finishOperationLocked(op, /*finishNested*/ true);
816 client.mStartedOps.remove(j);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700817 if (op.startNesting <= 0) {
Svet Ganova7a0db62018-02-27 20:08:01 -0800818 scheduleOpActiveChangedIfNeededLocked(op.op,
819 uid, packageName, false);
820 }
821 }
822 }
823 }
824
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800825 if (ops != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700826 scheduleFastWriteLocked();
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800827
828 final int opCount = ops.size();
829 for (int i = 0; i < opCount; i++) {
830 final Op op = ops.valueAt(i);
831 if (op.duration == -1) {
832 scheduleOpActiveChangedIfNeededLocked(
833 op.op, op.uid, op.packageName, false);
834 }
835 }
Dianne Hackborn514074f2013-02-11 10:52:46 -0800836 }
837 }
838 }
839
840 public void uidRemoved(int uid) {
841 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700842 if (mUidStates.indexOfKey(uid) >= 0) {
843 mUidStates.remove(uid);
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800844 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800845 }
846 }
847 }
848
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700849 public void updateUidProcState(int uid, int procState) {
850 synchronized (this) {
851 final UidState uidState = getUidStateLocked(uid, true);
Amith Yamasania0a30a12019-01-22 11:38:06 -0800852 int newState = PROCESS_STATE_TO_UID_STATE[procState];
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700853 if (uidState != null && uidState.pendingState != newState) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700854 final int oldPendingState = uidState.pendingState;
855 uidState.pendingState = newState;
Dianne Hackborne93ab412018-05-14 17:52:30 -0700856 if (newState < uidState.state || newState <= UID_STATE_LAST_NON_RESTRICTED) {
857 // We are moving to a more important state, or the new state is in the
858 // foreground, then always do it immediately.
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700859 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700860 } else if (uidState.pendingStateCommitTime == 0) {
861 // We are moving to a less important state for the first time,
862 // delay the application for a bit.
Dianne Hackborne93ab412018-05-14 17:52:30 -0700863 final long settleTime;
864 if (uidState.state <= UID_STATE_TOP) {
865 settleTime = mConstants.TOP_STATE_SETTLE_TIME;
866 } else if (uidState.state <= UID_STATE_FOREGROUND_SERVICE) {
867 settleTime = mConstants.FG_SERVICE_STATE_SETTLE_TIME;
868 } else {
869 settleTime = mConstants.BG_STATE_SETTLE_TIME;
870 }
Dianne Hackborn9fb93502018-06-18 12:29:44 -0700871 uidState.pendingStateCommitTime = SystemClock.elapsedRealtime() + settleTime;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700872 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700873 if (uidState.startNesting != 0) {
874 // There is some actively running operation... need to find it
875 // and appropriately update its state.
876 final long now = System.currentTimeMillis();
877 for (int i = uidState.pkgOps.size() - 1; i >= 0; i--) {
878 final Ops ops = uidState.pkgOps.valueAt(i);
879 for (int j = ops.size() - 1; j >= 0; j--) {
880 final Op op = ops.valueAt(j);
881 if (op.startNesting > 0) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700882 op.time[oldPendingState] = now;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700883 op.time[newState] = now;
884 }
885 }
886 }
887 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700888 }
889 }
890 }
891
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800892 public void shutdown() {
893 Slog.w(TAG, "Writing app ops before shutdown...");
Dianne Hackborn35654b62013-01-14 17:38:02 -0800894 boolean doWrite = false;
895 synchronized (this) {
896 if (mWriteScheduled) {
897 mWriteScheduled = false;
898 doWrite = true;
899 }
900 }
901 if (doWrite) {
902 writeState();
903 }
904 }
905
Dianne Hackborn72e39832013-01-18 18:36:09 -0800906 private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
907 ArrayList<AppOpsManager.OpEntry> resOps = null;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700908 final long elapsedNow = SystemClock.elapsedRealtime();
Dianne Hackborn72e39832013-01-18 18:36:09 -0800909 if (ops == null) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700910 resOps = new ArrayList<>();
Dianne Hackborn72e39832013-01-18 18:36:09 -0800911 for (int j=0; j<pkgOps.size(); j++) {
912 Op curOp = pkgOps.valueAt(j);
Amith Yamasania1ce9632018-05-28 20:50:48 -0700913 final boolean running = curOp.duration == -1;
914 long duration = running
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700915 ? (elapsedNow - curOp.startRealtime)
916 : curOp.duration;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800917 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Amith Yamasania1ce9632018-05-28 20:50:48 -0700918 curOp.rejectTime, (int) duration, running, curOp.proxyUid,
Svet Ganov99b60432015-06-27 13:15:22 -0700919 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800920 }
921 } else {
922 for (int j=0; j<ops.length; j++) {
923 Op curOp = pkgOps.get(ops[j]);
924 if (curOp != null) {
925 if (resOps == null) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700926 resOps = new ArrayList<>();
Dianne Hackborn72e39832013-01-18 18:36:09 -0800927 }
Amith Yamasania1ce9632018-05-28 20:50:48 -0700928 final boolean running = curOp.duration == -1;
929 final long duration = running
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700930 ? (elapsedNow - curOp.startRealtime)
931 : curOp.duration;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800932 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Amith Yamasania1ce9632018-05-28 20:50:48 -0700933 curOp.rejectTime, (int) duration, running, curOp.proxyUid,
Svet Ganov99b60432015-06-27 13:15:22 -0700934 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800935 }
936 }
937 }
938 return resOps;
939 }
940
Dianne Hackbornc7214a32017-04-11 13:32:47 -0700941 private ArrayList<AppOpsManager.OpEntry> collectOps(SparseIntArray uidOps, int[] ops) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -0800942 if (uidOps == null) {
943 return null;
944 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -0700945 ArrayList<AppOpsManager.OpEntry> resOps = null;
946 if (ops == null) {
947 resOps = new ArrayList<>();
948 for (int j=0; j<uidOps.size(); j++) {
949 resOps.add(new AppOpsManager.OpEntry(uidOps.keyAt(j), uidOps.valueAt(j),
950 0, 0, 0, -1, null));
951 }
952 } else {
953 for (int j=0; j<ops.length; j++) {
954 int index = uidOps.indexOfKey(ops[j]);
955 if (index >= 0) {
956 if (resOps == null) {
957 resOps = new ArrayList<>();
958 }
959 resOps.add(new AppOpsManager.OpEntry(uidOps.keyAt(index), uidOps.valueAt(index),
960 0, 0, 0, -1, null));
961 }
962 }
963 }
964 return resOps;
965 }
966
Dianne Hackborn35654b62013-01-14 17:38:02 -0800967 @Override
968 public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
969 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
970 Binder.getCallingPid(), Binder.getCallingUid(), null);
971 ArrayList<AppOpsManager.PackageOps> res = null;
972 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700973 final int uidStateCount = mUidStates.size();
974 for (int i = 0; i < uidStateCount; i++) {
975 UidState uidState = mUidStates.valueAt(i);
976 if (uidState.pkgOps == null || uidState.pkgOps.isEmpty()) {
977 continue;
978 }
979 ArrayMap<String, Ops> packages = uidState.pkgOps;
980 final int packageCount = packages.size();
981 for (int j = 0; j < packageCount; j++) {
982 Ops pkgOps = packages.valueAt(j);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800983 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800984 if (resOps != null) {
985 if (res == null) {
986 res = new ArrayList<AppOpsManager.PackageOps>();
987 }
988 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700989 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800990 res.add(resPackage);
991 }
992 }
993 }
994 }
995 return res;
996 }
997
998 @Override
Dianne Hackborn72e39832013-01-18 18:36:09 -0800999 public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
1000 int[] ops) {
1001 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
1002 Binder.getCallingPid(), Binder.getCallingUid(), null);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001003 String resolvedPackageName = resolvePackageName(uid, packageName);
1004 if (resolvedPackageName == null) {
1005 return Collections.emptyList();
1006 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08001007 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001008 Ops pkgOps = getOpsRawLocked(uid, resolvedPackageName, false /* edit */,
1009 false /* uidMismatchExpected */);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001010 if (pkgOps == null) {
1011 return null;
1012 }
1013 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
1014 if (resOps == null) {
1015 return null;
1016 }
1017 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
1018 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -07001019 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn72e39832013-01-18 18:36:09 -08001020 res.add(resPackage);
1021 return res;
1022 }
1023 }
1024
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001025 @Override
Svet Ganov8455ba22019-01-02 13:05:56 -08001026 public void getHistoricalOps(int uid, @NonNull String packageName,
1027 @Nullable String[] opNames, long beginTimeMillis, long endTimeMillis,
1028 @NonNull RemoteCallback callback) {
1029 Preconditions.checkArgument(uid == Process.INVALID_UID || uid >= 0,
1030 "uid must be " + Process.INVALID_UID + " or non negative");
Svet Ganovad0a49b2018-10-29 10:07:08 -07001031 Preconditions.checkArgument(beginTimeMillis >= 0 && beginTimeMillis < endTimeMillis,
1032 "beginTimeMillis must be non negative and lesser than endTimeMillis");
Svet Ganov8455ba22019-01-02 13:05:56 -08001033 Preconditions.checkNotNull(callback, "callback cannot be null");
1034 checkValidOpsOrNull(opNames);
Svet Ganovad0a49b2018-10-29 10:07:08 -07001035
1036 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
Svet Ganov8455ba22019-01-02 13:05:56 -08001037 Binder.getCallingPid(), Binder.getCallingUid(), "getHistoricalOps");
Svet Ganovad0a49b2018-10-29 10:07:08 -07001038
Svet Ganov8455ba22019-01-02 13:05:56 -08001039 if (mHistoricalRegistry.getMode() == AppOpsManager.HISTORICAL_MODE_DISABLED) {
1040 // TODO (bug:122218838): Remove once the feature fully enabled.
1041 getHistoricalPackagesOpsCompat(uid, packageName, opNames, beginTimeMillis,
1042 endTimeMillis, callback);
1043 } else {
1044 // Must not hold the appops lock
1045 mHistoricalRegistry.getHistoricalOps(uid, packageName, opNames,
1046 beginTimeMillis, endTimeMillis, callback);
Svet Ganovad0a49b2018-10-29 10:07:08 -07001047 }
Svet Ganovad0a49b2018-10-29 10:07:08 -07001048 }
1049
Svet Ganov8455ba22019-01-02 13:05:56 -08001050 private void getHistoricalPackagesOpsCompat(int uid, @NonNull String packageName,
1051 @Nullable String[] opNames, long beginTimeMillis, long endTimeMillis,
1052 @NonNull RemoteCallback callback) {
1053 synchronized (AppOpsService.this) {
1054 final HistoricalOps ops = new HistoricalOps(beginTimeMillis, endTimeMillis);
1055 if (opNames == null) {
1056 opNames = AppOpsManager.getOpStrs();
1057 }
1058 final int uidStateCount = mUidStates.size();
1059 for (int uidIdx = 0; uidIdx < uidStateCount; uidIdx++) {
1060 final UidState uidState = mUidStates.valueAt(uidIdx);
1061 if (uidState.pkgOps == null || uidState.pkgOps.isEmpty()
1062 || (uid != Process.INVALID_UID && uid != uidState.uid)) {
1063 continue;
1064 }
1065 final ArrayMap<String, Ops> packages = uidState.pkgOps;
1066 final int packageCount = packages.size();
1067 for (int pkgIdx = 0; pkgIdx < packageCount; pkgIdx++) {
1068 final Ops pkgOps = packages.valueAt(pkgIdx);
1069 if (packageName != null && !packageName.equals(pkgOps.packageName)) {
1070 continue;
1071 }
1072 final int opCount = opNames.length;
1073 for (int opIdx = 0; opIdx < opCount; opIdx++) {
1074 final String opName = opNames[opIdx];
1075 if (!ArrayUtils.contains(opNames, opName)) {
1076 continue;
1077 }
1078 final int opCode = AppOpsManager.strOpToOp(opName);
1079 final Op op = pkgOps.get(opCode);
1080 if (op == null) {
1081 continue;
1082 }
1083 final int stateCount = AppOpsManager._NUM_UID_STATE;
1084 for (int stateIdx = 0; stateIdx < stateCount; stateIdx++) {
1085 if (op.rejectTime[stateIdx] != 0) {
1086 ops.increaseRejectCount(opCode, uidState.uid,
1087 pkgOps.packageName, stateIdx, 1);
1088 } else if (op.time[stateIdx] != 0) {
1089 ops.increaseAccessCount(opCode, uidState.uid,
1090 pkgOps.packageName, stateIdx, 1);
1091 }
1092 }
1093 }
1094 }
1095 }
1096 final Bundle payload = new Bundle();
1097 payload.putParcelable(AppOpsManager.KEY_HISTORICAL_OPS, ops);
1098 callback.sendResult(payload);
Svet Ganovad0a49b2018-10-29 10:07:08 -07001099 }
Svet Ganovad0a49b2018-10-29 10:07:08 -07001100 }
1101
1102 @Override
Svet Ganov8455ba22019-01-02 13:05:56 -08001103 public void getHistoricalOpsFromDiskRaw(int uid, @NonNull String packageName,
1104 @Nullable String[] opNames, long beginTimeMillis, long endTimeMillis,
1105 @NonNull RemoteCallback callback) {
1106 Preconditions.checkArgument(uid == Process.INVALID_UID || uid >= 0,
1107 "uid must be " + Process.INVALID_UID + " or non negative");
Svet Ganovad0a49b2018-10-29 10:07:08 -07001108 Preconditions.checkArgument(beginTimeMillis >= 0 && beginTimeMillis < endTimeMillis,
1109 "beginTimeMillis must be non negative and lesser than endTimeMillis");
Svet Ganov8455ba22019-01-02 13:05:56 -08001110 Preconditions.checkNotNull(callback, "callback cannot be null");
1111 checkValidOpsOrNull(opNames);
Svet Ganovad0a49b2018-10-29 10:07:08 -07001112
1113 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
Svet Ganov8455ba22019-01-02 13:05:56 -08001114 Binder.getCallingPid(), Binder.getCallingUid(), "getHistoricalOps");
Svet Ganovad0a49b2018-10-29 10:07:08 -07001115
Svet Ganov8455ba22019-01-02 13:05:56 -08001116 // Must not hold the appops lock
1117 mHistoricalRegistry.getHistoricalOpsFromDiskRaw(uid, packageName, opNames,
1118 beginTimeMillis, endTimeMillis, callback);
Svet Ganovad0a49b2018-10-29 10:07:08 -07001119 }
1120
1121 @Override
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001122 public List<AppOpsManager.PackageOps> getUidOps(int uid, int[] ops) {
1123 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
1124 Binder.getCallingPid(), Binder.getCallingUid(), null);
1125 synchronized (this) {
1126 UidState uidState = getUidStateLocked(uid, false);
1127 if (uidState == null) {
1128 return null;
1129 }
1130 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(uidState.opModes, ops);
1131 if (resOps == null) {
1132 return null;
1133 }
1134 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
1135 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
1136 null, uidState.uid, resOps);
1137 res.add(resPackage);
1138 return res;
1139 }
1140 }
1141
Dianne Hackborn607b4142013-08-02 18:10:10 -07001142 private void pruneOp(Op op, int uid, String packageName) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001143 if (!op.hasAnyTime()) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001144 Ops ops = getOpsRawLocked(uid, packageName, false /* edit */,
1145 false /* uidMismatchExpected */);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001146 if (ops != null) {
1147 ops.remove(op.op);
1148 if (ops.size() <= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -07001149 UidState uidState = ops.uidState;
1150 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
Dianne Hackborn607b4142013-08-02 18:10:10 -07001151 if (pkgOps != null) {
1152 pkgOps.remove(ops.packageName);
Svet Ganov2af57082015-07-30 08:44:20 -07001153 if (pkgOps.isEmpty()) {
1154 uidState.pkgOps = null;
1155 }
1156 if (uidState.isDefault()) {
1157 mUidStates.remove(uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001158 }
1159 }
1160 }
1161 }
1162 }
1163 }
1164
Dianne Hackbornd5254412018-05-11 18:02:58 -07001165 void enforceManageAppOpsModes(int callingPid, int callingUid, int targetUid) {
1166 if (callingPid == Process.myPid()) {
1167 return;
1168 }
1169 final int callingUser = UserHandle.getUserId(callingUid);
1170 synchronized (this) {
1171 if (mProfileOwners != null && mProfileOwners.get(callingUser, -1) == callingUid) {
1172 if (targetUid >= 0 && callingUser == UserHandle.getUserId(targetUid)) {
1173 // Profile owners are allowed to change modes but only for apps
1174 // within their user.
1175 return;
1176 }
1177 }
1178 }
1179 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
1180 Binder.getCallingPid(), Binder.getCallingUid(), null);
1181 }
1182
Dianne Hackborn72e39832013-01-18 18:36:09 -08001183 @Override
Svet Ganov2af57082015-07-30 08:44:20 -07001184 public void setUidMode(int code, int uid, int mode) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08001185 if (DEBUG) {
1186 Slog.i(TAG, "uid " + uid + " OP_" + opToName(code) + " := " + modeToName(mode)
1187 + " by uid " + Binder.getCallingUid());
1188 }
1189
Dianne Hackbornd5254412018-05-11 18:02:58 -07001190 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
Svet Ganov2af57082015-07-30 08:44:20 -07001191 verifyIncomingOp(code);
1192 code = AppOpsManager.opToSwitch(code);
1193
1194 synchronized (this) {
1195 final int defaultMode = AppOpsManager.opToDefaultMode(code);
1196
1197 UidState uidState = getUidStateLocked(uid, false);
1198 if (uidState == null) {
1199 if (mode == defaultMode) {
1200 return;
1201 }
1202 uidState = new UidState(uid);
1203 uidState.opModes = new SparseIntArray();
1204 uidState.opModes.put(code, mode);
1205 mUidStates.put(uid, uidState);
1206 scheduleWriteLocked();
1207 } else if (uidState.opModes == null) {
1208 if (mode != defaultMode) {
1209 uidState.opModes = new SparseIntArray();
1210 uidState.opModes.put(code, mode);
1211 scheduleWriteLocked();
1212 }
1213 } else {
Hai Zhang2b98fb32018-09-21 15:18:46 -07001214 if (uidState.opModes.indexOfKey(code) >= 0 && uidState.opModes.get(code) == mode) {
Svet Ganov2af57082015-07-30 08:44:20 -07001215 return;
1216 }
1217 if (mode == defaultMode) {
1218 uidState.opModes.delete(code);
1219 if (uidState.opModes.size() <= 0) {
1220 uidState.opModes = null;
1221 }
1222 } else {
1223 uidState.opModes.put(code, mode);
1224 }
1225 scheduleWriteLocked();
1226 }
1227 }
1228
Svetoslav215b44a2015-08-04 19:03:40 -07001229 String[] uidPackageNames = getPackagesForUid(uid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001230 ArrayMap<ModeCallback, ArraySet<String>> callbackSpecs = null;
Svet Ganov2af57082015-07-30 08:44:20 -07001231
riddle_hsu40b300f2015-11-23 13:22:03 +08001232 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001233 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001234 if (callbacks != null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001235 final int callbackCount = callbacks.size();
1236 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001237 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +08001238 ArraySet<String> changedPackages = new ArraySet<>();
1239 Collections.addAll(changedPackages, uidPackageNames);
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001240 if (callbackSpecs == null) {
1241 callbackSpecs = new ArrayMap<>();
1242 }
riddle_hsu40b300f2015-11-23 13:22:03 +08001243 callbackSpecs.put(callback, changedPackages);
1244 }
1245 }
1246
1247 for (String uidPackageName : uidPackageNames) {
1248 callbacks = mPackageModeWatchers.get(uidPackageName);
1249 if (callbacks != null) {
1250 if (callbackSpecs == null) {
1251 callbackSpecs = new ArrayMap<>();
Svet Ganov2af57082015-07-30 08:44:20 -07001252 }
riddle_hsu40b300f2015-11-23 13:22:03 +08001253 final int callbackCount = callbacks.size();
1254 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001255 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +08001256 ArraySet<String> changedPackages = callbackSpecs.get(callback);
1257 if (changedPackages == null) {
1258 changedPackages = new ArraySet<>();
1259 callbackSpecs.put(callback, changedPackages);
1260 }
1261 changedPackages.add(uidPackageName);
1262 }
Svet Ganov2af57082015-07-30 08:44:20 -07001263 }
1264 }
1265 }
1266
1267 if (callbackSpecs == null) {
1268 return;
1269 }
1270
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001271 for (int i = 0; i < callbackSpecs.size(); i++) {
1272 final ModeCallback callback = callbackSpecs.keyAt(i);
1273 final ArraySet<String> reportedPackageNames = callbackSpecs.valueAt(i);
1274 if (reportedPackageNames == null) {
1275 mHandler.sendMessage(PooledLambda.obtainMessage(
1276 AppOpsService::notifyOpChanged,
1277 this, callback, code, uid, (String) null));
1278
1279 } else {
1280 final int reportedPackageCount = reportedPackageNames.size();
1281 for (int j = 0; j < reportedPackageCount; j++) {
1282 final String reportedPackageName = reportedPackageNames.valueAt(j);
1283 mHandler.sendMessage(PooledLambda.obtainMessage(
1284 AppOpsService::notifyOpChanged,
1285 this, callback, code, uid, reportedPackageName));
Svet Ganov2af57082015-07-30 08:44:20 -07001286 }
1287 }
Svet Ganov2af57082015-07-30 08:44:20 -07001288 }
1289 }
1290
1291 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001292 public void setMode(int code, int uid, String packageName, int mode) {
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07001293 setMode(code, uid, packageName, mode, true, false);
1294 }
1295
1296 /**
1297 * Sets the mode for a certain op and uid.
1298 *
1299 * @param code The op code to set
1300 * @param uid The UID for which to set
1301 * @param packageName The package for which to set
1302 * @param mode The new mode to set
1303 * @param verifyUid Iff {@code true}, check that the package name belongs to the uid
1304 * @param isPrivileged Whether the package is privileged. (Only used if {@code verifyUid ==
1305 * false})
1306 */
1307 private void setMode(int code, int uid, @NonNull String packageName, int mode,
1308 boolean verifyUid, boolean isPrivileged) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07001309 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001310 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001311 ArraySet<ModeCallback> repCbs = null;
Dianne Hackbornc2293022013-02-06 23:14:49 -08001312 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001313 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -07001314 UidState uidState = getUidStateLocked(uid, false);
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07001315 Op op = getOpLocked(code, uid, packageName, true, verifyUid, isPrivileged);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001316 if (op != null) {
1317 if (op.mode != mode) {
1318 op.mode = mode;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001319 if (uidState != null) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001320 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001321 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001322 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001323 if (cbs != null) {
1324 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001325 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001326 }
1327 repCbs.addAll(cbs);
1328 }
1329 cbs = mPackageModeWatchers.get(packageName);
1330 if (cbs != null) {
1331 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001332 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001333 }
1334 repCbs.addAll(cbs);
1335 }
David Braunf5d83192013-09-16 13:43:51 -07001336 if (mode == AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001337 // If going into the default mode, prune this op
1338 // if there is nothing else interesting in it.
Dianne Hackborn607b4142013-08-02 18:10:10 -07001339 pruneOp(op, uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001340 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001341 scheduleFastWriteLocked();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001342 }
1343 }
1344 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001345 if (repCbs != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001346 mHandler.sendMessage(PooledLambda.obtainMessage(
1347 AppOpsService::notifyOpChanged,
1348 this, repCbs, code, uid, packageName));
Dianne Hackbornc2293022013-02-06 23:14:49 -08001349 }
1350 }
1351
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001352 private void notifyOpChanged(ArraySet<ModeCallback> callbacks, int code,
1353 int uid, String packageName) {
1354 for (int i = 0; i < callbacks.size(); i++) {
1355 final ModeCallback callback = callbacks.valueAt(i);
1356 notifyOpChanged(callback, code, uid, packageName);
1357 }
1358 }
1359
1360 private void notifyOpChanged(ModeCallback callback, int code,
1361 int uid, String packageName) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001362 if (uid != UID_ANY && callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001363 return;
1364 }
1365 // There are components watching for mode changes such as window manager
1366 // and location manager which are in our process. The callbacks in these
1367 // components may require permissions our remote caller does not have.
1368 final long identity = Binder.clearCallingIdentity();
1369 try {
1370 callback.mCallback.opChanged(code, uid, packageName);
1371 } catch (RemoteException e) {
1372 /* ignore */
1373 } finally {
1374 Binder.restoreCallingIdentity(identity);
1375 }
1376 }
1377
1378 private static HashMap<ModeCallback, ArrayList<ChangeRec>> addCallbacks(
1379 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks,
1380 int op, int uid, String packageName, ArraySet<ModeCallback> cbs) {
Dianne Hackborn607b4142013-08-02 18:10:10 -07001381 if (cbs == null) {
1382 return callbacks;
1383 }
1384 if (callbacks == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001385 callbacks = new HashMap<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001386 }
Svet Ganov2af57082015-07-30 08:44:20 -07001387 boolean duplicate = false;
Dianne Hackborn68d76552017-02-27 15:32:03 -08001388 final int N = cbs.size();
1389 for (int i=0; i<N; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001390 ModeCallback cb = cbs.valueAt(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001391 ArrayList<ChangeRec> reports = callbacks.get(cb);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001392 if (reports == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001393 reports = new ArrayList<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001394 callbacks.put(cb, reports);
Svet Ganov2af57082015-07-30 08:44:20 -07001395 } else {
1396 final int reportCount = reports.size();
1397 for (int j = 0; j < reportCount; j++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001398 ChangeRec report = reports.get(j);
1399 if (report.op == op && report.pkg.equals(packageName)) {
Svet Ganov2af57082015-07-30 08:44:20 -07001400 duplicate = true;
1401 break;
1402 }
1403 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001404 }
Svet Ganov2af57082015-07-30 08:44:20 -07001405 if (!duplicate) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001406 reports.add(new ChangeRec(op, uid, packageName));
Svet Ganov2af57082015-07-30 08:44:20 -07001407 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001408 }
1409 return callbacks;
1410 }
1411
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001412 static final class ChangeRec {
1413 final int op;
1414 final int uid;
1415 final String pkg;
1416
1417 ChangeRec(int _op, int _uid, String _pkg) {
1418 op = _op;
1419 uid = _uid;
1420 pkg = _pkg;
1421 }
1422 }
1423
Dianne Hackborn607b4142013-08-02 18:10:10 -07001424 @Override
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001425 public void resetAllModes(int reqUserId, String reqPackageName) {
1426 final int callingPid = Binder.getCallingPid();
1427 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001428 reqUserId = ActivityManager.handleIncomingUser(callingPid, callingUid, reqUserId,
1429 true, true, "resetAllModes", null);
Svet Ganov2af57082015-07-30 08:44:20 -07001430
1431 int reqUid = -1;
1432 if (reqPackageName != null) {
1433 try {
1434 reqUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -07001435 reqPackageName, PackageManager.MATCH_UNINSTALLED_PACKAGES, reqUserId);
Svet Ganov2af57082015-07-30 08:44:20 -07001436 } catch (RemoteException e) {
1437 /* ignore - local call */
1438 }
1439 }
1440
Dianne Hackbornd5254412018-05-11 18:02:58 -07001441 enforceManageAppOpsModes(callingPid, callingUid, reqUid);
1442
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001443 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks = null;
Dianne Hackborn607b4142013-08-02 18:10:10 -07001444 synchronized (this) {
1445 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -07001446 for (int i = mUidStates.size() - 1; i >= 0; i--) {
1447 UidState uidState = mUidStates.valueAt(i);
1448
1449 SparseIntArray opModes = uidState.opModes;
1450 if (opModes != null && (uidState.uid == reqUid || reqUid == -1)) {
1451 final int uidOpCount = opModes.size();
1452 for (int j = uidOpCount - 1; j >= 0; j--) {
1453 final int code = opModes.keyAt(j);
1454 if (AppOpsManager.opAllowsReset(code)) {
1455 opModes.removeAt(j);
1456 if (opModes.size() <= 0) {
1457 uidState.opModes = null;
1458 }
1459 for (String packageName : getPackagesForUid(uidState.uid)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001460 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -07001461 mOpModeWatchers.get(code));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001462 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -07001463 mPackageModeWatchers.get(packageName));
1464 }
1465 }
1466 }
1467 }
1468
1469 if (uidState.pkgOps == null) {
1470 continue;
1471 }
1472
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001473 if (reqUserId != UserHandle.USER_ALL
Svet Ganov2af57082015-07-30 08:44:20 -07001474 && reqUserId != UserHandle.getUserId(uidState.uid)) {
Alexandra Gherghinad6a98972014-08-04 17:05:34 +01001475 // Skip any ops for a different user
1476 continue;
1477 }
Svet Ganov2af57082015-07-30 08:44:20 -07001478
1479 Map<String, Ops> packages = uidState.pkgOps;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001480 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001481 boolean uidChanged = false;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001482 while (it.hasNext()) {
1483 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001484 String packageName = ent.getKey();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001485 if (reqPackageName != null && !reqPackageName.equals(packageName)) {
1486 // Skip any ops for a different package
1487 continue;
1488 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001489 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001490 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -07001491 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -07001492 if (AppOpsManager.opAllowsReset(curOp.op)
1493 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -07001494 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001495 changed = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001496 uidChanged = true;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001497 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -07001498 mOpModeWatchers.get(curOp.op));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001499 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -07001500 mPackageModeWatchers.get(packageName));
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001501 if (!curOp.hasAnyTime()) {
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001502 pkgOps.removeAt(j);
1503 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001504 }
1505 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001506 if (pkgOps.size() == 0) {
1507 it.remove();
1508 }
1509 }
Svet Ganov2af57082015-07-30 08:44:20 -07001510 if (uidState.isDefault()) {
1511 mUidStates.remove(uidState.uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001512 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001513 if (uidChanged) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001514 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001515 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001516 }
Svet Ganov2af57082015-07-30 08:44:20 -07001517
Dianne Hackborn607b4142013-08-02 18:10:10 -07001518 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001519 scheduleFastWriteLocked();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001520 }
1521 }
1522 if (callbacks != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001523 for (Map.Entry<ModeCallback, ArrayList<ChangeRec>> ent : callbacks.entrySet()) {
1524 ModeCallback cb = ent.getKey();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001525 ArrayList<ChangeRec> reports = ent.getValue();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001526 for (int i=0; i<reports.size(); i++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001527 ChangeRec rep = reports.get(i);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001528 mHandler.sendMessage(PooledLambda.obtainMessage(
1529 AppOpsService::notifyOpChanged,
1530 this, cb, rep.op, rep.uid, rep.pkg));
Dianne Hackborn607b4142013-08-02 18:10:10 -07001531 }
1532 }
1533 }
1534 }
1535
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001536 private void evalAllForegroundOpsLocked() {
1537 for (int uidi = mUidStates.size() - 1; uidi >= 0; uidi--) {
1538 final UidState uidState = mUidStates.valueAt(uidi);
1539 if (uidState.foregroundOps != null) {
1540 uidState.evalForegroundOps(mOpModeWatchers);
1541 }
1542 }
1543 }
1544
Dianne Hackbornc2293022013-02-06 23:14:49 -08001545 @Override
1546 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001547 startWatchingModeWithFlags(op, packageName, 0, callback);
1548 }
1549
1550 @Override
1551 public void startWatchingModeWithFlags(int op, String packageName, int flags,
1552 IAppOpsCallback callback) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001553 int watchedUid = -1;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001554 final int callingUid = Binder.getCallingUid();
1555 final int callingPid = Binder.getCallingPid();
Dianne Hackborn5376edd2018-06-05 13:21:16 -07001556 // TODO: should have a privileged permission to protect this.
1557 // Also, if the caller has requested WATCH_FOREGROUND_CHANGES, should we require
1558 // the USAGE_STATS permission since this can provide information about when an
1559 // app is in the foreground?
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001560 Preconditions.checkArgumentInRange(op, AppOpsManager.OP_NONE,
1561 AppOpsManager._NUM_OP - 1, "Invalid op code: " + op);
Svetoslav Ganov8de59712015-12-09 18:25:13 -08001562 if (callback == null) {
1563 return;
1564 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001565 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -07001566 op = (op != AppOpsManager.OP_NONE) ? AppOpsManager.opToSwitch(op) : op;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001567 ModeCallback cb = mModeWatchers.get(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -08001568 if (cb == null) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001569 cb = new ModeCallback(callback, watchedUid, flags, callingUid, callingPid);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001570 mModeWatchers.put(callback.asBinder(), cb);
1571 }
1572 if (op != AppOpsManager.OP_NONE) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001573 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(op);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001574 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08001575 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001576 mOpModeWatchers.put(op, cbs);
1577 }
1578 cbs.add(cb);
1579 }
1580 if (packageName != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001581 ArraySet<ModeCallback> cbs = mPackageModeWatchers.get(packageName);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001582 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08001583 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001584 mPackageModeWatchers.put(packageName, cbs);
1585 }
1586 cbs.add(cb);
1587 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001588 evalAllForegroundOpsLocked();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001589 }
1590 }
1591
1592 @Override
1593 public void stopWatchingMode(IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -08001594 if (callback == null) {
1595 return;
1596 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001597 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001598 ModeCallback cb = mModeWatchers.remove(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -08001599 if (cb != null) {
1600 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001601 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001602 ArraySet<ModeCallback> cbs = mOpModeWatchers.valueAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001603 cbs.remove(cb);
1604 if (cbs.size() <= 0) {
1605 mOpModeWatchers.removeAt(i);
1606 }
1607 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001608 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001609 ArraySet<ModeCallback> cbs = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001610 cbs.remove(cb);
1611 if (cbs.size() <= 0) {
1612 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001613 }
1614 }
1615 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001616 evalAllForegroundOpsLocked();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001617 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001618 }
1619
1620 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001621 public IBinder getToken(IBinder clientToken) {
1622 synchronized (this) {
1623 ClientState cs = mClients.get(clientToken);
1624 if (cs == null) {
1625 cs = new ClientState(clientToken);
1626 mClients.put(clientToken, cs);
1627 }
1628 return cs;
1629 }
1630 }
1631
Svet Ganovd873ae62018-06-25 16:39:23 -07001632 public CheckOpsDelegate getAppOpsServiceDelegate() {
1633 synchronized (this) {
1634 return mCheckOpsDelegate;
1635 }
1636 }
1637
1638 public void setAppOpsServiceDelegate(CheckOpsDelegate delegate) {
1639 synchronized (this) {
1640 mCheckOpsDelegate = delegate;
1641 }
1642 }
1643
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001644 @Override
Svet Ganov9d528a12018-12-19 17:23:11 -08001645 public int checkOperationRaw(int code, int uid, String packageName) {
1646 return checkOperationInternal(code, uid, packageName, true /*raw*/);
1647 }
1648
1649 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -08001650 public int checkOperation(int code, int uid, String packageName) {
Svet Ganov9d528a12018-12-19 17:23:11 -08001651 return checkOperationInternal(code, uid, packageName, false /*raw*/);
1652 }
1653
1654 private int checkOperationInternal(int code, int uid, String packageName, boolean raw) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001655 final CheckOpsDelegate delegate;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001656 synchronized (this) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001657 delegate = mCheckOpsDelegate;
1658 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001659 if (delegate == null) {
Svet Ganov9d528a12018-12-19 17:23:11 -08001660 return checkOperationImpl(code, uid, packageName, raw);
Todd Kennedy556efba2018-11-15 07:43:55 -08001661 }
Svet Ganov9d528a12018-12-19 17:23:11 -08001662 return delegate.checkOperation(code, uid, packageName, raw,
Svet Ganovd873ae62018-06-25 16:39:23 -07001663 AppOpsService.this::checkOperationImpl);
1664 }
1665
Svet Ganov9d528a12018-12-19 17:23:11 -08001666 private int checkOperationImpl(int code, int uid, String packageName,
1667 boolean raw) {
Todd Kennedy556efba2018-11-15 07:43:55 -08001668 verifyIncomingUid(uid);
1669 verifyIncomingOp(code);
1670 String resolvedPackageName = resolvePackageName(uid, packageName);
1671 if (resolvedPackageName == null) {
1672 return AppOpsManager.MODE_IGNORED;
1673 }
Svet Ganov9d528a12018-12-19 17:23:11 -08001674 return checkOperationUnchecked(code, uid, resolvedPackageName, raw);
Todd Kennedy556efba2018-11-15 07:43:55 -08001675 }
1676
Svet Ganov9d528a12018-12-19 17:23:11 -08001677 private int checkOperationUnchecked(int code, int uid, String packageName,
1678 boolean raw) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001679 synchronized (this) {
Todd Kennedy556efba2018-11-15 07:43:55 -08001680 if (isOpRestrictedLocked(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001681 return AppOpsManager.MODE_IGNORED;
1682 }
Svet Ganov2af57082015-07-30 08:44:20 -07001683 code = AppOpsManager.opToSwitch(code);
1684 UidState uidState = getUidStateLocked(uid, false);
Svet Ganovee438d42017-01-19 18:04:38 -08001685 if (uidState != null && uidState.opModes != null
1686 && uidState.opModes.indexOfKey(code) >= 0) {
Svet Ganov9d528a12018-12-19 17:23:11 -08001687 final int rawMode = uidState.opModes.get(code);
1688 return raw ? rawMode : uidState.evalMode(rawMode);
Svet Ganov2af57082015-07-30 08:44:20 -07001689 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001690 Op op = getOpLocked(code, uid, packageName, false, true, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001691 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -07001692 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001693 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001694 return op.mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001695 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001696 }
1697
1698 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001699 public int checkAudioOperation(int code, int usage, int uid, String packageName) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001700 final CheckOpsDelegate delegate;
John Spurlock1af30c72014-03-10 08:33:35 -04001701 synchronized (this) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001702 delegate = mCheckOpsDelegate;
1703 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001704 if (delegate == null) {
1705 return checkAudioOperationImpl(code, usage, uid, packageName);
1706 }
Svet Ganovd873ae62018-06-25 16:39:23 -07001707 return delegate.checkAudioOperation(code, usage, uid, packageName,
1708 AppOpsService.this::checkAudioOperationImpl);
1709 }
1710
1711 private int checkAudioOperationImpl(int code, int usage, int uid, String packageName) {
Todd Kennedy556efba2018-11-15 07:43:55 -08001712 boolean suspended;
1713 try {
1714 suspended = isPackageSuspendedForUser(packageName, uid);
1715 } catch (IllegalArgumentException ex) {
1716 // Package not found.
1717 suspended = false;
1718 }
1719
1720 if (suspended) {
1721 Slog.i(TAG, "Audio disabled for suspended package=" + packageName
1722 + " for uid=" + uid);
1723 return AppOpsManager.MODE_IGNORED;
1724 }
1725
Svet Ganovd873ae62018-06-25 16:39:23 -07001726 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001727 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -04001728 if (mode != AppOpsManager.MODE_ALLOWED) {
1729 return mode;
1730 }
1731 }
1732 return checkOperation(code, uid, packageName);
1733 }
1734
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001735 private boolean isPackageSuspendedForUser(String pkg, int uid) {
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001736 try {
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001737 return AppGlobals.getPackageManager().isPackageSuspendedForUser(
1738 pkg, UserHandle.getUserId(uid));
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001739 } catch (RemoteException re) {
1740 throw new SecurityException("Could not talk to package manager service");
1741 }
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001742 }
1743
John Spurlock7b414672014-07-18 13:02:39 -04001744 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
1745 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1746 if (usageRestrictions != null) {
1747 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001748 if (r != null && !r.exceptionPackages.contains(packageName)) {
1749 return r.mode;
1750 }
1751 }
1752 return AppOpsManager.MODE_ALLOWED;
1753 }
1754
1755 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001756 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -04001757 String[] exceptionPackages) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07001758 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
John Spurlock1af30c72014-03-10 08:33:35 -04001759 verifyIncomingUid(uid);
1760 verifyIncomingOp(code);
1761 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001762 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1763 if (usageRestrictions == null) {
1764 usageRestrictions = new SparseArray<Restriction>();
1765 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -04001766 }
John Spurlock7b414672014-07-18 13:02:39 -04001767 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001768 if (mode != AppOpsManager.MODE_ALLOWED) {
1769 final Restriction r = new Restriction();
1770 r.mode = mode;
1771 if (exceptionPackages != null) {
1772 final int N = exceptionPackages.length;
1773 r.exceptionPackages = new ArraySet<String>(N);
1774 for (int i = 0; i < N; i++) {
1775 final String pkg = exceptionPackages[i];
1776 if (pkg != null) {
1777 r.exceptionPackages.add(pkg.trim());
1778 }
1779 }
1780 }
John Spurlock7b414672014-07-18 13:02:39 -04001781 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -04001782 }
1783 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001784
1785 mHandler.sendMessage(PooledLambda.obtainMessage(
Svet Ganov3a95f832018-03-23 17:44:30 -07001786 AppOpsService::notifyWatchersOfChange, this, code, UID_ANY));
John Spurlock1af30c72014-03-10 08:33:35 -04001787 }
1788
1789 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001790 public int checkPackage(int uid, String packageName) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001791 Preconditions.checkNotNull(packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001792 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001793 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1794 true /* uidMismatchExpected */);
1795 if (ops != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001796 return AppOpsManager.MODE_ALLOWED;
1797 } else {
1798 return AppOpsManager.MODE_ERRORED;
1799 }
1800 }
1801 }
1802
1803 @Override
Svet Ganovd873ae62018-06-25 16:39:23 -07001804 public int noteProxyOperation(int code, int proxyUid,
1805 String proxyPackageName, int proxiedUid, String proxiedPackageName) {
1806 verifyIncomingUid(proxyUid);
Svet Ganov99b60432015-06-27 13:15:22 -07001807 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001808 String resolveProxyPackageName = resolvePackageName(proxyUid, proxyPackageName);
1809 if (resolveProxyPackageName == null) {
1810 return AppOpsManager.MODE_IGNORED;
1811 }
1812 final int proxyMode = noteOperationUnchecked(code, proxyUid,
1813 resolveProxyPackageName, -1, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001814 if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
1815 return proxyMode;
1816 }
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001817 String resolveProxiedPackageName = resolvePackageName(proxiedUid, proxiedPackageName);
1818 if (resolveProxiedPackageName == null) {
1819 return AppOpsManager.MODE_IGNORED;
1820 }
1821 return noteOperationUnchecked(code, proxiedUid, resolveProxiedPackageName,
1822 proxyMode, resolveProxyPackageName);
Svet Ganov99b60432015-06-27 13:15:22 -07001823 }
1824
1825 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001826 public int noteOperation(int code, int uid, String packageName) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001827 final CheckOpsDelegate delegate;
1828 synchronized (this) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001829 delegate = mCheckOpsDelegate;
1830 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001831 if (delegate == null) {
1832 return noteOperationImpl(code, uid, packageName);
1833 }
Svet Ganovd873ae62018-06-25 16:39:23 -07001834 return delegate.noteOperation(code, uid, packageName,
1835 AppOpsService.this::noteOperationImpl);
1836 }
1837
1838 private int noteOperationImpl(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001839 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001840 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001841 String resolvedPackageName = resolvePackageName(uid, packageName);
1842 if (resolvedPackageName == null) {
1843 return AppOpsManager.MODE_IGNORED;
1844 }
1845 return noteOperationUnchecked(code, uid, resolvedPackageName, 0, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001846 }
1847
1848 private int noteOperationUnchecked(int code, int uid, String packageName,
1849 int proxyUid, String proxyPackageName) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001850 synchronized (this) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001851 final Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
Yohei Yukawaa965d652017-10-12 15:02:26 -07001852 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001853 if (ops == null) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -08001854 scheduleOpNotedIfNeededLocked(code, uid, packageName,
1855 AppOpsManager.MODE_IGNORED);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001856 if (DEBUG) Slog.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001857 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001858 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001859 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001860 final Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07001861 if (isOpRestrictedLocked(uid, code, packageName)) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -08001862 scheduleOpNotedIfNeededLocked(code, uid, packageName,
1863 AppOpsManager.MODE_IGNORED);
Jason Monk62062992014-05-06 09:55:28 -04001864 return AppOpsManager.MODE_IGNORED;
1865 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001866 final UidState uidState = ops.uidState;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001867 if (op.duration == -1) {
1868 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001869 + " code " + code + " time=" + op.time[uidState.state]
1870 + " duration=" + op.duration);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001871 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001872 op.duration = 0;
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001873 final int switchCode = AppOpsManager.opToSwitch(code);
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001874 // If there is a non-default per UID policy (we set UID op mode only if
1875 // non-default) it takes over, otherwise use the per package policy.
1876 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001877 final int uidMode = uidState.evalMode(uidState.opModes.get(switchCode));
Svet Ganov2af57082015-07-30 08:44:20 -07001878 if (uidMode != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001879 if (DEBUG) Slog.d(TAG, "noteOperation: uid reject #" + uidMode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07001880 + switchCode + " (" + code + ") uid " + uid + " package "
1881 + packageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001882 op.rejectTime[uidState.state] = System.currentTimeMillis();
Svet Ganovb3d2ae22018-12-17 22:06:15 -08001883 scheduleOpNotedIfNeededLocked(code, uid, packageName, uidMode);
Svet Ganov8455ba22019-01-02 13:05:56 -08001884 mHistoricalRegistry.incrementOpRejected(op.op, uid, packageName,
1885 uidState.state);
Svet Ganov2af57082015-07-30 08:44:20 -07001886 return uidMode;
1887 }
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001888 } else {
1889 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001890 final int mode = switchOp.getMode();
1891 if (mode != AppOpsManager.MODE_ALLOWED) {
1892 if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + mode + " for code "
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001893 + switchCode + " (" + code + ") uid " + uid + " package "
1894 + packageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001895 op.rejectTime[uidState.state] = System.currentTimeMillis();
Svet Ganovb3d2ae22018-12-17 22:06:15 -08001896 scheduleOpNotedIfNeededLocked(op.op, uid, packageName, mode);
Svet Ganov8455ba22019-01-02 13:05:56 -08001897 mHistoricalRegistry.incrementOpRejected(op.op, uid, packageName,
1898 uidState.state);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001899 return mode;
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001900 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001901 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001902 if (DEBUG) Slog.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001903 + " package " + packageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001904 op.time[uidState.state] = System.currentTimeMillis();
Svet Ganov8455ba22019-01-02 13:05:56 -08001905 mHistoricalRegistry.incrementOpAccessedCount(op.op, uid, packageName,
1906 uidState.state);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001907 op.rejectTime[uidState.state] = 0;
Svet Ganov99b60432015-06-27 13:15:22 -07001908 op.proxyUid = proxyUid;
1909 op.proxyPackageName = proxyPackageName;
Svet Ganovb3d2ae22018-12-17 22:06:15 -08001910 scheduleOpNotedIfNeededLocked(code, uid, packageName,
1911 AppOpsManager.MODE_ALLOWED);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001912 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001913 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001914 }
1915
1916 @Override
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001917 public void startWatchingActive(int[] ops, IAppOpsActiveCallback callback) {
Svet Ganovf7b47252018-02-26 11:11:27 -08001918 int watchedUid = -1;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001919 final int callingUid = Binder.getCallingUid();
1920 final int callingPid = Binder.getCallingPid();
Svet Ganovf7b47252018-02-26 11:11:27 -08001921 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
1922 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001923 watchedUid = callingUid;
Svet Ganovf7b47252018-02-26 11:11:27 -08001924 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001925 if (ops != null) {
1926 Preconditions.checkArrayElementsInRange(ops, 0,
1927 AppOpsManager._NUM_OP - 1, "Invalid op code in: " + Arrays.toString(ops));
1928 }
1929 if (callback == null) {
1930 return;
1931 }
1932 synchronized (this) {
1933 SparseArray<ActiveCallback> callbacks = mActiveWatchers.get(callback.asBinder());
1934 if (callbacks == null) {
1935 callbacks = new SparseArray<>();
1936 mActiveWatchers.put(callback.asBinder(), callbacks);
1937 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001938 final ActiveCallback activeCallback = new ActiveCallback(callback, watchedUid,
1939 callingUid, callingPid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001940 for (int op : ops) {
1941 callbacks.put(op, activeCallback);
1942 }
1943 }
1944 }
1945
1946 @Override
1947 public void stopWatchingActive(IAppOpsActiveCallback callback) {
1948 if (callback == null) {
1949 return;
1950 }
1951 synchronized (this) {
1952 final SparseArray<ActiveCallback> activeCallbacks =
1953 mActiveWatchers.remove(callback.asBinder());
1954 if (activeCallbacks == null) {
1955 return;
1956 }
1957 final int callbackCount = activeCallbacks.size();
1958 for (int i = 0; i < callbackCount; i++) {
Svet Ganovb3d2ae22018-12-17 22:06:15 -08001959 activeCallbacks.valueAt(i).destroy();
1960 }
1961 }
1962 }
1963
1964 @Override
1965 public void startWatchingNoted(@NonNull int[] ops, @NonNull IAppOpsNotedCallback callback) {
1966 int watchedUid = Process.INVALID_UID;
1967 final int callingUid = Binder.getCallingUid();
1968 final int callingPid = Binder.getCallingPid();
1969 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
1970 != PackageManager.PERMISSION_GRANTED) {
1971 watchedUid = callingUid;
1972 }
1973 Preconditions.checkArgument(!ArrayUtils.isEmpty(ops), "Ops cannot be null or empty");
1974 Preconditions.checkArrayElementsInRange(ops, 0, AppOpsManager._NUM_OP - 1,
1975 "Invalid op code in: " + Arrays.toString(ops));
1976 Preconditions.checkNotNull(callback, "Callback cannot be null");
1977 synchronized (this) {
1978 SparseArray<NotedCallback> callbacks = mNotedWatchers.get(callback.asBinder());
1979 if (callbacks == null) {
1980 callbacks = new SparseArray<>();
1981 mNotedWatchers.put(callback.asBinder(), callbacks);
1982 }
1983 final NotedCallback notedCallback = new NotedCallback(callback, watchedUid,
1984 callingUid, callingPid);
1985 for (int op : ops) {
1986 callbacks.put(op, notedCallback);
1987 }
1988 }
1989 }
1990
1991 @Override
1992 public void stopWatchingNoted(IAppOpsNotedCallback callback) {
1993 Preconditions.checkNotNull(callback, "Callback cannot be null");
1994 synchronized (this) {
1995 final SparseArray<NotedCallback> notedCallbacks =
1996 mNotedWatchers.remove(callback.asBinder());
1997 if (notedCallbacks == null) {
1998 return;
1999 }
2000 final int callbackCount = notedCallbacks.size();
2001 for (int i = 0; i < callbackCount; i++) {
2002 notedCallbacks.valueAt(i).destroy();
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002003 }
2004 }
2005 }
2006
2007 @Override
Svet Ganovf7b47252018-02-26 11:11:27 -08002008 public int startOperation(IBinder token, int code, int uid, String packageName,
2009 boolean startIfModeDefault) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002010 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08002011 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002012 String resolvedPackageName = resolvePackageName(uid, packageName);
2013 if (resolvedPackageName == null) {
2014 return AppOpsManager.MODE_IGNORED;
2015 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002016 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002017 synchronized (this) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002018 final Ops ops = getOpsRawLocked(uid, resolvedPackageName, true /* edit */,
Yohei Yukawaa965d652017-10-12 15:02:26 -07002019 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002020 if (ops == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002021 if (DEBUG) Slog.d(TAG, "startOperation: no op for code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002022 + " package " + resolvedPackageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07002023 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002024 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002025 final Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07002026 if (isOpRestrictedLocked(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -04002027 return AppOpsManager.MODE_IGNORED;
2028 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002029 final int switchCode = AppOpsManager.opToSwitch(code);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002030 final UidState uidState = ops.uidState;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002031 // If there is a non-default per UID policy (we set UID op mode only if
2032 // non-default) it takes over, otherwise use the per package policy.
2033 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002034 final int uidMode = uidState.evalMode(uidState.opModes.get(switchCode));
Svet Ganovf7b47252018-02-26 11:11:27 -08002035 if (uidMode != AppOpsManager.MODE_ALLOWED
2036 && (!startIfModeDefault || uidMode != AppOpsManager.MODE_DEFAULT)) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002037 if (DEBUG) Slog.d(TAG, "noteOperation: uid reject #" + uidMode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07002038 + switchCode + " (" + code + ") uid " + uid + " package "
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002039 + resolvedPackageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002040 op.rejectTime[uidState.state] = System.currentTimeMillis();
Svet Ganov8455ba22019-01-02 13:05:56 -08002041 mHistoricalRegistry.incrementOpRejected(op.op, uid, packageName,
2042 uidState.state);
Svet Ganov2af57082015-07-30 08:44:20 -07002043 return uidMode;
2044 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002045 } else {
2046 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002047 final int mode = switchOp.getMode();
2048 if (mode != AppOpsManager.MODE_ALLOWED
2049 && (!startIfModeDefault || mode != AppOpsManager.MODE_DEFAULT)) {
2050 if (DEBUG) Slog.d(TAG, "startOperation: reject #" + mode + " for code "
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002051 + switchCode + " (" + code + ") uid " + uid + " package "
2052 + resolvedPackageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002053 op.rejectTime[uidState.state] = System.currentTimeMillis();
Svet Ganov8455ba22019-01-02 13:05:56 -08002054 mHistoricalRegistry.incrementOpRejected(op.op, uid, packageName,
2055 uidState.state);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002056 return mode;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002057 }
Svet Ganov2af57082015-07-30 08:44:20 -07002058 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002059 if (DEBUG) Slog.d(TAG, "startOperation: allowing code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002060 + " package " + resolvedPackageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002061 if (op.startNesting == 0) {
2062 op.startRealtime = SystemClock.elapsedRealtime();
2063 op.time[uidState.state] = System.currentTimeMillis();
Svet Ganov8455ba22019-01-02 13:05:56 -08002064 mHistoricalRegistry.incrementOpAccessedCount(op.op, uid, packageName,
2065 uidState.state);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002066 op.rejectTime[uidState.state] = 0;
Dianne Hackborn35654b62013-01-14 17:38:02 -08002067 op.duration = -1;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002068 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002069 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002070 op.startNesting++;
2071 uidState.startNesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002072 if (client.mStartedOps != null) {
2073 client.mStartedOps.add(op);
2074 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002075 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002076
2077 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002078 }
2079
2080 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002081 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002082 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08002083 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002084 String resolvedPackageName = resolvePackageName(uid, packageName);
2085 if (resolvedPackageName == null) {
2086 return;
2087 }
2088 if (!(token instanceof ClientState)) {
2089 return;
2090 }
2091 ClientState client = (ClientState) token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002092 synchronized (this) {
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07002093 Op op = getOpLocked(code, uid, resolvedPackageName, true, true, false);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002094 if (op == null) {
2095 return;
2096 }
Svet Ganovf7b47252018-02-26 11:11:27 -08002097 if (!client.mStartedOps.remove(op)) {
Svet Ganovf5d5af12018-03-18 11:51:17 -07002098 // We finish ops when packages get removed to guarantee no dangling
2099 // started ops. However, some part of the system may asynchronously
2100 // finish ops for an already gone package. Hence, finishing an op
2101 // for a non existing package is fine and we don't log as a wtf.
2102 final long identity = Binder.clearCallingIdentity();
2103 try {
2104 if (LocalServices.getService(PackageManagerInternal.class).getPackageUid(
2105 resolvedPackageName, 0, UserHandle.getUserId(uid)) < 0) {
2106 Slog.i(TAG, "Finishing op=" + AppOpsManager.opToName(code)
2107 + " for non-existing package=" + resolvedPackageName
2108 + " in uid=" + uid);
2109 return;
2110 }
2111 } finally {
2112 Binder.restoreCallingIdentity(identity);
2113 }
2114 Slog.wtf(TAG, "Operation not started: uid=" + op.uid + " pkg="
2115 + op.packageName + " op=" + AppOpsManager.opToName(op.op));
Svet Ganov31d83ae2018-03-15 10:45:56 -07002116 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002117 }
Svet Ganova7a0db62018-02-27 20:08:01 -08002118 finishOperationLocked(op, /*finishNested*/ false);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002119 if (op.startNesting <= 0) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002120 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, false);
2121 }
2122 }
2123 }
2124
2125 private void scheduleOpActiveChangedIfNeededLocked(int code, int uid, String packageName,
2126 boolean active) {
2127 ArraySet<ActiveCallback> dispatchedCallbacks = null;
2128 final int callbackListCount = mActiveWatchers.size();
2129 for (int i = 0; i < callbackListCount; i++) {
2130 final SparseArray<ActiveCallback> callbacks = mActiveWatchers.valueAt(i);
2131 ActiveCallback callback = callbacks.get(code);
2132 if (callback != null) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002133 if (callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
Svet Ganovf7b47252018-02-26 11:11:27 -08002134 continue;
2135 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002136 if (dispatchedCallbacks == null) {
2137 dispatchedCallbacks = new ArraySet<>();
2138 }
2139 dispatchedCallbacks.add(callback);
2140 }
2141 }
2142 if (dispatchedCallbacks == null) {
2143 return;
2144 }
2145 mHandler.sendMessage(PooledLambda.obtainMessage(
2146 AppOpsService::notifyOpActiveChanged,
2147 this, dispatchedCallbacks, code, uid, packageName, active));
2148 }
2149
2150 private void notifyOpActiveChanged(ArraySet<ActiveCallback> callbacks,
2151 int code, int uid, String packageName, boolean active) {
2152 // There are components watching for mode changes such as window manager
2153 // and location manager which are in our process. The callbacks in these
2154 // components may require permissions our remote caller does not have.
2155 final long identity = Binder.clearCallingIdentity();
2156 try {
2157 final int callbackCount = callbacks.size();
2158 for (int i = 0; i < callbackCount; i++) {
2159 final ActiveCallback callback = callbacks.valueAt(i);
2160 try {
2161 callback.mCallback.opActiveChanged(code, uid, packageName, active);
2162 } catch (RemoteException e) {
2163 /* do nothing */
2164 }
2165 }
2166 } finally {
2167 Binder.restoreCallingIdentity(identity);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002168 }
2169 }
2170
Svet Ganovb3d2ae22018-12-17 22:06:15 -08002171 private void scheduleOpNotedIfNeededLocked(int code, int uid, String packageName,
2172 int result) {
2173 ArraySet<NotedCallback> dispatchedCallbacks = null;
2174 final int callbackListCount = mNotedWatchers.size();
2175 for (int i = 0; i < callbackListCount; i++) {
2176 final SparseArray<NotedCallback> callbacks = mNotedWatchers.valueAt(i);
2177 final NotedCallback callback = callbacks.get(code);
2178 if (callback != null) {
2179 if (callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
2180 continue;
2181 }
2182 if (dispatchedCallbacks == null) {
2183 dispatchedCallbacks = new ArraySet<>();
2184 }
2185 dispatchedCallbacks.add(callback);
2186 }
2187 }
2188 if (dispatchedCallbacks == null) {
2189 return;
2190 }
2191 mHandler.sendMessage(PooledLambda.obtainMessage(
2192 AppOpsService::notifyOpChecked,
2193 this, dispatchedCallbacks, code, uid, packageName, result));
2194 }
2195
2196 private void notifyOpChecked(ArraySet<NotedCallback> callbacks,
2197 int code, int uid, String packageName, int result) {
2198 // There are components watching for checks in our process. The callbacks in
2199 // these components may require permissions our remote caller does not have.
2200 final long identity = Binder.clearCallingIdentity();
2201 try {
2202 final int callbackCount = callbacks.size();
2203 for (int i = 0; i < callbackCount; i++) {
2204 final NotedCallback callback = callbacks.valueAt(i);
2205 try {
2206 callback.mCallback.opNoted(code, uid, packageName, result);
2207 } catch (RemoteException e) {
2208 /* do nothing */
2209 }
2210 }
2211 } finally {
2212 Binder.restoreCallingIdentity(identity);
2213 }
2214 }
2215
Svet Ganovb9d71a62015-04-30 10:38:13 -07002216 @Override
2217 public int permissionToOpCode(String permission) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002218 if (permission == null) {
2219 return AppOpsManager.OP_NONE;
2220 }
Svet Ganovb9d71a62015-04-30 10:38:13 -07002221 return AppOpsManager.permissionToOpCode(permission);
2222 }
2223
Svet Ganova7a0db62018-02-27 20:08:01 -08002224 void finishOperationLocked(Op op, boolean finishNested) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002225 if (op.startNesting <= 1 || finishNested) {
2226 if (op.startNesting == 1 || finishNested) {
2227 op.duration = (int)(SystemClock.elapsedRealtime() - op.startRealtime);
Svet Ganov8455ba22019-01-02 13:05:56 -08002228 mHistoricalRegistry.increaseOpAccessDuration(op.op, op.uid, op.packageName,
2229 op.uidState.state, op.duration);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002230 op.time[op.uidState.state] = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002231 } else {
2232 Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
2233 + op.packageName + " code " + op.op + " time=" + op.time
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002234 + " duration=" + op.duration + " nesting=" + op.startNesting);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002235 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002236 if (op.startNesting >= 1) {
2237 op.uidState.startNesting -= op.startNesting;
2238 }
2239 op.startNesting = 0;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002240 } else {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002241 op.startNesting--;
2242 op.uidState.startNesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002243 }
2244 }
2245
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002246 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002247 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002248 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002249 }
2250 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002251 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002252 }
2253 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
2254 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002255 }
2256
Dianne Hackborn961321f2013-02-05 17:22:41 -08002257 private void verifyIncomingOp(int op) {
2258 if (op >= 0 && op < AppOpsManager._NUM_OP) {
2259 return;
2260 }
2261 throw new IllegalArgumentException("Bad operation #" + op);
2262 }
2263
Svet Ganov2af57082015-07-30 08:44:20 -07002264 private UidState getUidStateLocked(int uid, boolean edit) {
2265 UidState uidState = mUidStates.get(uid);
2266 if (uidState == null) {
2267 if (!edit) {
2268 return null;
2269 }
2270 uidState = new UidState(uid);
2271 mUidStates.put(uid, uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002272 } else {
2273 if (uidState.pendingStateCommitTime != 0) {
Dianne Hackborn9fb93502018-06-18 12:29:44 -07002274 if (uidState.pendingStateCommitTime < mLastRealtime) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002275 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002276 } else {
Dianne Hackborn9fb93502018-06-18 12:29:44 -07002277 mLastRealtime = SystemClock.elapsedRealtime();
2278 if (uidState.pendingStateCommitTime < mLastRealtime) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002279 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002280 }
2281 }
2282 }
Svet Ganov2af57082015-07-30 08:44:20 -07002283 }
2284 return uidState;
2285 }
2286
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002287 private void commitUidPendingStateLocked(UidState uidState) {
Dianne Hackborne93ab412018-05-14 17:52:30 -07002288 final boolean lastForeground = uidState.state <= UID_STATE_LAST_NON_RESTRICTED;
2289 final boolean nowForeground = uidState.pendingState <= UID_STATE_LAST_NON_RESTRICTED;
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002290 uidState.state = uidState.pendingState;
2291 uidState.pendingStateCommitTime = 0;
Dianne Hackborne93ab412018-05-14 17:52:30 -07002292 if (uidState.hasForegroundWatchers && lastForeground != nowForeground) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002293 for (int fgi = uidState.foregroundOps.size() - 1; fgi >= 0; fgi--) {
2294 if (!uidState.foregroundOps.valueAt(fgi)) {
2295 continue;
2296 }
2297 final int code = uidState.foregroundOps.keyAt(fgi);
2298
2299 final ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
2300 if (callbacks != null) {
2301 for (int cbi = callbacks.size() - 1; cbi >= 0; cbi--) {
2302 final ModeCallback callback = callbacks.valueAt(cbi);
2303 if ((callback.mFlags & AppOpsManager.WATCH_FOREGROUND_CHANGES) == 0
2304 || !callback.isWatchingUid(uidState.uid)) {
2305 continue;
2306 }
2307 boolean doAllPackages = uidState.opModes != null
Hai Zhang2b98fb32018-09-21 15:18:46 -07002308 && uidState.opModes.indexOfKey(code) >= 0
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002309 && uidState.opModes.get(code) == AppOpsManager.MODE_FOREGROUND;
2310 if (uidState.pkgOps != null) {
2311 for (int pkgi = uidState.pkgOps.size() - 1; pkgi >= 0; pkgi--) {
2312 final Op op = uidState.pkgOps.valueAt(pkgi).get(code);
2313 if (doAllPackages || (op != null
2314 && op.mode == AppOpsManager.MODE_FOREGROUND)) {
2315 mHandler.sendMessage(PooledLambda.obtainMessage(
2316 AppOpsService::notifyOpChanged,
2317 this, callback, code, uidState.uid,
2318 uidState.pkgOps.keyAt(pkgi)));
2319 }
2320 }
2321 }
2322 }
2323 }
2324 }
2325 }
2326 }
2327
Yohei Yukawaa965d652017-10-12 15:02:26 -07002328 private Ops getOpsRawLocked(int uid, String packageName, boolean edit,
2329 boolean uidMismatchExpected) {
Svet Ganov2af57082015-07-30 08:44:20 -07002330 UidState uidState = getUidStateLocked(uid, edit);
2331 if (uidState == null) {
2332 return null;
2333 }
2334
2335 if (uidState.pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002336 if (!edit) {
2337 return null;
2338 }
Svet Ganov2af57082015-07-30 08:44:20 -07002339 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002340 }
Svet Ganov2af57082015-07-30 08:44:20 -07002341
2342 Ops ops = uidState.pkgOps.get(packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002343 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002344 if (!edit) {
2345 return null;
2346 }
Jason Monk1c7c3192014-06-26 12:52:18 -04002347 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002348 // This is the first time we have seen this package name under this uid,
2349 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -08002350 if (uid != 0) {
2351 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002352 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -08002353 int pkgUid = -1;
2354 try {
Jason Monk1c7c3192014-06-26 12:52:18 -04002355 ApplicationInfo appInfo = ActivityThread.getPackageManager()
Jeff Sharkeycd654482016-01-08 17:42:11 -07002356 .getApplicationInfo(packageName,
Svet Ganovad0a49b2018-10-29 10:07:08 -07002357 PackageManager.MATCH_DIRECT_BOOT_AWARE
Svet Ganov8455ba22019-01-02 13:05:56 -08002358 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkeycd654482016-01-08 17:42:11 -07002359 UserHandle.getUserId(uid));
Jason Monk1c7c3192014-06-26 12:52:18 -04002360 if (appInfo != null) {
2361 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002362 isPrivileged = (appInfo.privateFlags
2363 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04002364 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08002365 pkgUid = resolveUid(packageName);
2366 if (pkgUid >= 0) {
Chien-Yu Chen75cade02016-01-11 10:56:21 -08002367 isPrivileged = false;
Jason Monk1c7c3192014-06-26 12:52:18 -04002368 }
Dianne Hackborn713df152013-05-17 11:27:57 -07002369 }
Jason Monk1c7c3192014-06-26 12:52:18 -04002370 } catch (RemoteException e) {
2371 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08002372 }
2373 if (pkgUid != uid) {
2374 // Oops! The package name is not valid for the uid they are calling
2375 // under. Abort.
Yohei Yukawaa965d652017-10-12 15:02:26 -07002376 if (!uidMismatchExpected) {
2377 RuntimeException ex = new RuntimeException("here");
2378 ex.fillInStackTrace();
2379 Slog.w(TAG, "Bad call: specified package " + packageName
2380 + " under uid " + uid + " but it is really " + pkgUid, ex);
2381 }
Dianne Hackborn514074f2013-02-11 10:52:46 -08002382 return null;
2383 }
2384 } finally {
2385 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002386 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002387 }
Svet Ganov2af57082015-07-30 08:44:20 -07002388 ops = new Ops(packageName, uidState, isPrivileged);
2389 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002390 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08002391 return ops;
2392 }
2393
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07002394 /**
2395 * Get the state of all ops for a package, <b>don't verify that package belongs to uid</b>.
2396 *
2397 * <p>Usually callers should use {@link #getOpLocked} and not call this directly.
2398 *
2399 * @param uid The uid the of the package
2400 * @param packageName The package name for which to get the state for
2401 * @param edit Iff {@code true} create the {@link Ops} object if not yet created
2402 * @param isPrivileged Whether the package is privileged or not
2403 *
2404 * @return The {@link Ops state} of all ops for the package
2405 */
2406 private @Nullable Ops getOpsRawNoVerifyLocked(int uid, @NonNull String packageName,
2407 boolean edit, boolean isPrivileged) {
2408 UidState uidState = getUidStateLocked(uid, edit);
2409 if (uidState == null) {
2410 return null;
2411 }
2412
2413 if (uidState.pkgOps == null) {
2414 if (!edit) {
2415 return null;
2416 }
2417 uidState.pkgOps = new ArrayMap<>();
2418 }
2419
2420 Ops ops = uidState.pkgOps.get(packageName);
2421 if (ops == null) {
2422 if (!edit) {
2423 return null;
2424 }
2425 ops = new Ops(packageName, uidState, isPrivileged);
2426 uidState.pkgOps.put(packageName, ops);
2427 }
2428 return ops;
2429 }
2430
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002431 private void scheduleWriteLocked() {
2432 if (!mWriteScheduled) {
2433 mWriteScheduled = true;
2434 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
2435 }
2436 }
2437
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002438 private void scheduleFastWriteLocked() {
2439 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002440 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002441 mFastWriteScheduled = true;
2442 mHandler.removeCallbacks(mWriteRunner);
2443 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002444 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002445 }
2446
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07002447 /**
2448 * Get the state of an op for a uid.
2449 *
2450 * @param code The code of the op
2451 * @param uid The uid the of the package
2452 * @param packageName The package name for which to get the state for
2453 * @param edit Iff {@code true} create the {@link Op} object if not yet created
2454 * @param verifyUid Iff {@code true} check that the package belongs to the uid
2455 * @param isPrivileged Whether the package is privileged or not (only used if {@code verifyUid
2456 * == false})
2457 *
2458 * @return The {@link Op state} of the op
2459 */
2460 private @Nullable Op getOpLocked(int code, int uid, @NonNull String packageName, boolean edit,
2461 boolean verifyUid, boolean isPrivileged) {
2462 Ops ops;
2463
2464 if (verifyUid) {
2465 ops = getOpsRawLocked(uid, packageName, edit, false /* uidMismatchExpected */);
2466 } else {
2467 ops = getOpsRawNoVerifyLocked(uid, packageName, edit, isPrivileged);
2468 }
2469
Dianne Hackborn72e39832013-01-18 18:36:09 -08002470 if (ops == null) {
2471 return null;
2472 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002473 return getOpLocked(ops, code, edit);
2474 }
2475
2476 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002477 Op op = ops.get(code);
2478 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002479 if (!edit) {
2480 return null;
2481 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002482 op = new Op(ops.uidState, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002483 ops.put(code, op);
2484 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002485 if (edit) {
2486 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002487 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002488 return op;
2489 }
2490
Svet Ganov442ed572016-08-17 17:29:43 -07002491 private boolean isOpRestrictedLocked(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04002492 int userHandle = UserHandle.getUserId(uid);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002493 final int restrictionSetCount = mOpUserRestrictions.size();
Ruben Brunk29931bc2016-03-11 00:24:26 -08002494
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002495 for (int i = 0; i < restrictionSetCount; i++) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002496 // For each client, check that the given op is not restricted, or that the given
2497 // package is exempt from the restriction.
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002498 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07002499 if (restrictionState.hasRestriction(code, packageName, userHandle)) {
2500 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
2501 // If we are the system, bypass user restrictions for certain codes
2502 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07002503 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
2504 false /* uidMismatchExpected */);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07002505 if ((ops != null) && ops.isPrivileged) {
2506 return false;
2507 }
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002508 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002509 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002510 return true;
Jason Monk1c7c3192014-06-26 12:52:18 -04002511 }
Jason Monk62062992014-05-06 09:55:28 -04002512 }
2513 return false;
2514 }
2515
Dianne Hackborn35654b62013-01-14 17:38:02 -08002516 void readState() {
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002517 int oldVersion = NO_VERSION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08002518 synchronized (mFile) {
2519 synchronized (this) {
2520 FileInputStream stream;
2521 try {
2522 stream = mFile.openRead();
2523 } catch (FileNotFoundException e) {
2524 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
2525 return;
2526 }
2527 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002528 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002529 try {
2530 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002531 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08002532 int type;
2533 while ((type = parser.next()) != XmlPullParser.START_TAG
2534 && type != XmlPullParser.END_DOCUMENT) {
2535 ;
2536 }
2537
2538 if (type != XmlPullParser.START_TAG) {
2539 throw new IllegalStateException("no start tag found");
2540 }
2541
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002542 final String versionString = parser.getAttributeValue(null, "v");
2543 if (versionString != null) {
2544 oldVersion = Integer.parseInt(versionString);
2545 }
2546
Dianne Hackborn35654b62013-01-14 17:38:02 -08002547 int outerDepth = parser.getDepth();
2548 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2549 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2550 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2551 continue;
2552 }
2553
2554 String tagName = parser.getName();
2555 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00002556 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07002557 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07002558 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002559 } else {
2560 Slog.w(TAG, "Unknown element under <app-ops>: "
2561 + parser.getName());
2562 XmlUtils.skipCurrentTag(parser);
2563 }
2564 }
2565 success = true;
2566 } catch (IllegalStateException e) {
2567 Slog.w(TAG, "Failed parsing " + e);
2568 } catch (NullPointerException e) {
2569 Slog.w(TAG, "Failed parsing " + e);
2570 } catch (NumberFormatException e) {
2571 Slog.w(TAG, "Failed parsing " + e);
2572 } catch (XmlPullParserException e) {
2573 Slog.w(TAG, "Failed parsing " + e);
2574 } catch (IOException e) {
2575 Slog.w(TAG, "Failed parsing " + e);
2576 } catch (IndexOutOfBoundsException e) {
2577 Slog.w(TAG, "Failed parsing " + e);
2578 } finally {
2579 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07002580 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002581 }
2582 try {
2583 stream.close();
2584 } catch (IOException e) {
2585 }
2586 }
2587 }
2588 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002589 synchronized (this) {
2590 upgradeLocked(oldVersion);
2591 }
2592 }
2593
2594 private void upgradeRunAnyInBackgroundLocked() {
2595 for (int i = 0; i < mUidStates.size(); i++) {
2596 final UidState uidState = mUidStates.valueAt(i);
2597 if (uidState == null) {
2598 continue;
2599 }
2600 if (uidState.opModes != null) {
2601 final int idx = uidState.opModes.indexOfKey(AppOpsManager.OP_RUN_IN_BACKGROUND);
2602 if (idx >= 0) {
2603 uidState.opModes.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND,
2604 uidState.opModes.valueAt(idx));
2605 }
2606 }
2607 if (uidState.pkgOps == null) {
2608 continue;
2609 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002610 boolean changed = false;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002611 for (int j = 0; j < uidState.pkgOps.size(); j++) {
2612 Ops ops = uidState.pkgOps.valueAt(j);
2613 if (ops != null) {
2614 final Op op = ops.get(AppOpsManager.OP_RUN_IN_BACKGROUND);
2615 if (op != null && op.mode != AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002616 final Op copy = new Op(op.uidState, op.packageName,
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002617 AppOpsManager.OP_RUN_ANY_IN_BACKGROUND);
2618 copy.mode = op.mode;
2619 ops.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, copy);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002620 changed = true;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002621 }
2622 }
2623 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002624 if (changed) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002625 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002626 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002627 }
2628 }
2629
2630 private void upgradeLocked(int oldVersion) {
2631 if (oldVersion >= CURRENT_VERSION) {
2632 return;
2633 }
2634 Slog.d(TAG, "Upgrading app-ops xml from version " + oldVersion + " to " + CURRENT_VERSION);
2635 switch (oldVersion) {
2636 case NO_VERSION:
2637 upgradeRunAnyInBackgroundLocked();
2638 // fall through
2639 case 1:
2640 // for future upgrades
2641 }
2642 scheduleFastWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002643 }
2644
Svet Ganov2af57082015-07-30 08:44:20 -07002645 void readUidOps(XmlPullParser parser) throws NumberFormatException,
2646 XmlPullParserException, IOException {
2647 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
2648 int outerDepth = parser.getDepth();
2649 int type;
2650 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2651 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2652 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2653 continue;
2654 }
2655
2656 String tagName = parser.getName();
2657 if (tagName.equals("op")) {
2658 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
2659 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
2660 UidState uidState = getUidStateLocked(uid, true);
2661 if (uidState.opModes == null) {
2662 uidState.opModes = new SparseIntArray();
2663 }
2664 uidState.opModes.put(code, mode);
2665 } else {
2666 Slog.w(TAG, "Unknown element under <uid-ops>: "
2667 + parser.getName());
2668 XmlUtils.skipCurrentTag(parser);
2669 }
2670 }
2671 }
2672
Dave Burke0997c5bd2013-08-02 20:25:02 +00002673 void readPackage(XmlPullParser parser) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08002674 XmlPullParserException, IOException {
2675 String pkgName = parser.getAttributeValue(null, "n");
2676 int outerDepth = parser.getDepth();
2677 int type;
2678 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2679 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2680 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2681 continue;
2682 }
2683
2684 String tagName = parser.getName();
2685 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00002686 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002687 } else {
2688 Slog.w(TAG, "Unknown element under <pkg>: "
2689 + parser.getName());
2690 XmlUtils.skipCurrentTag(parser);
2691 }
2692 }
2693 }
2694
Dave Burke0997c5bd2013-08-02 20:25:02 +00002695 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08002696 XmlPullParserException, IOException {
2697 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Jason Monk1c7c3192014-06-26 12:52:18 -04002698 String isPrivilegedString = parser.getAttributeValue(null, "p");
2699 boolean isPrivileged = false;
2700 if (isPrivilegedString == null) {
2701 try {
2702 IPackageManager packageManager = ActivityThread.getPackageManager();
2703 if (packageManager != null) {
2704 ApplicationInfo appInfo = ActivityThread.getPackageManager()
2705 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
2706 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002707 isPrivileged = (appInfo.privateFlags
2708 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04002709 }
2710 } else {
2711 // Could not load data, don't add to cache so it will be loaded later.
2712 return;
2713 }
2714 } catch (RemoteException e) {
2715 Slog.w(TAG, "Could not contact PackageManager", e);
2716 }
2717 } else {
2718 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
2719 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002720 int outerDepth = parser.getDepth();
2721 int type;
2722 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2723 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2724 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2725 continue;
2726 }
2727
2728 String tagName = parser.getName();
2729 if (tagName.equals("op")) {
Svet Ganov2af57082015-07-30 08:44:20 -07002730 UidState uidState = getUidStateLocked(uid, true);
2731 if (uidState.pkgOps == null) {
2732 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002733 }
Svet Ganov2af57082015-07-30 08:44:20 -07002734
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002735 Op op = new Op(uidState, pkgName,
2736 Integer.parseInt(parser.getAttributeValue(null, "n")));
2737
2738 for (int i = parser.getAttributeCount()-1; i >= 0; i--) {
2739 final String name = parser.getAttributeName(i);
2740 final String value = parser.getAttributeValue(i);
2741 switch (name) {
2742 case "m":
2743 op.mode = Integer.parseInt(value);
2744 break;
2745 case "d":
2746 op.duration = Integer.parseInt(value);
2747 break;
2748 case "pu":
2749 op.proxyUid = Integer.parseInt(value);
2750 break;
2751 case "pp":
2752 op.proxyPackageName = value;
2753 break;
2754 case "tp":
2755 op.time[AppOpsManager.UID_STATE_PERSISTENT] = Long.parseLong(value);
2756 break;
2757 case "tt":
2758 op.time[AppOpsManager.UID_STATE_TOP] = Long.parseLong(value);
2759 break;
Amith Yamasania0a30a12019-01-22 11:38:06 -08002760 case "tfsl":
2761 op.time[AppOpsManager.UID_STATE_FOREGROUND_SERVICE_LOCATION] =
2762 Long.parseLong(value);
2763 break;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002764 case "tfs":
Amith Yamasania0a30a12019-01-22 11:38:06 -08002765 op.time[AppOpsManager.UID_STATE_FOREGROUND_SERVICE] =
2766 Long.parseLong(value);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002767 break;
2768 case "tf":
2769 op.time[AppOpsManager.UID_STATE_FOREGROUND] = Long.parseLong(value);
2770 break;
2771 case "tb":
2772 op.time[AppOpsManager.UID_STATE_BACKGROUND] = Long.parseLong(value);
2773 break;
2774 case "tc":
2775 op.time[AppOpsManager.UID_STATE_CACHED] = Long.parseLong(value);
2776 break;
2777 case "rp":
Amith Yamasania0a30a12019-01-22 11:38:06 -08002778 op.rejectTime[AppOpsManager.UID_STATE_PERSISTENT] =
2779 Long.parseLong(value);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002780 break;
2781 case "rt":
2782 op.rejectTime[AppOpsManager.UID_STATE_TOP] = Long.parseLong(value);
2783 break;
Amith Yamasania0a30a12019-01-22 11:38:06 -08002784 case "rfsl":
2785 op.rejectTime[AppOpsManager.UID_STATE_FOREGROUND_SERVICE_LOCATION] =
2786 Long.parseLong(value);
2787 break;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002788 case "rfs":
Amith Yamasania0a30a12019-01-22 11:38:06 -08002789 op.rejectTime[AppOpsManager.UID_STATE_FOREGROUND_SERVICE] =
2790 Long.parseLong(value);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002791 break;
2792 case "rf":
Amith Yamasania0a30a12019-01-22 11:38:06 -08002793 op.rejectTime[AppOpsManager.UID_STATE_FOREGROUND] =
2794 Long.parseLong(value);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002795 break;
2796 case "rb":
Amith Yamasania0a30a12019-01-22 11:38:06 -08002797 op.rejectTime[AppOpsManager.UID_STATE_BACKGROUND] =
2798 Long.parseLong(value);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002799 break;
2800 case "rc":
Amith Yamasania0a30a12019-01-22 11:38:06 -08002801 op.rejectTime[AppOpsManager.UID_STATE_CACHED] =
2802 Long.parseLong(value);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002803 break;
2804 case "t":
2805 // Backwards compat.
2806 op.time[AppOpsManager.UID_STATE_TOP] = Long.parseLong(value);
2807 break;
2808 case "r":
2809 // Backwards compat.
2810 op.rejectTime[AppOpsManager.UID_STATE_TOP] = Long.parseLong(value);
2811 break;
2812 default:
2813 Slog.w(TAG, "Unknown attribute in 'op' tag: " + name);
2814 break;
2815 }
2816 }
2817
Svet Ganov2af57082015-07-30 08:44:20 -07002818 Ops ops = uidState.pkgOps.get(pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002819 if (ops == null) {
Svet Ganov2af57082015-07-30 08:44:20 -07002820 ops = new Ops(pkgName, uidState, isPrivileged);
2821 uidState.pkgOps.put(pkgName, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002822 }
2823 ops.put(op.op, op);
2824 } else {
2825 Slog.w(TAG, "Unknown element under <pkg>: "
2826 + parser.getName());
2827 XmlUtils.skipCurrentTag(parser);
2828 }
2829 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002830 UidState uidState = getUidStateLocked(uid, false);
2831 if (uidState != null) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002832 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002833 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002834 }
2835
2836 void writeState() {
2837 synchronized (mFile) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002838 FileOutputStream stream;
2839 try {
2840 stream = mFile.startWrite();
2841 } catch (IOException e) {
2842 Slog.w(TAG, "Failed to write state: " + e);
2843 return;
2844 }
2845
Dianne Hackborne17b4452018-01-10 13:15:40 -08002846 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
2847
Dianne Hackborn35654b62013-01-14 17:38:02 -08002848 try {
2849 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002850 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08002851 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002852 out.startTag(null, "app-ops");
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002853 out.attribute(null, "v", String.valueOf(CURRENT_VERSION));
Svet Ganov2af57082015-07-30 08:44:20 -07002854
2855 final int uidStateCount = mUidStates.size();
2856 for (int i = 0; i < uidStateCount; i++) {
2857 UidState uidState = mUidStates.valueAt(i);
2858 if (uidState.opModes != null && uidState.opModes.size() > 0) {
2859 out.startTag(null, "uid");
2860 out.attribute(null, "n", Integer.toString(uidState.uid));
2861 SparseIntArray uidOpModes = uidState.opModes;
2862 final int opCount = uidOpModes.size();
2863 for (int j = 0; j < opCount; j++) {
2864 final int op = uidOpModes.keyAt(j);
2865 final int mode = uidOpModes.valueAt(j);
2866 out.startTag(null, "op");
2867 out.attribute(null, "n", Integer.toString(op));
2868 out.attribute(null, "m", Integer.toString(mode));
2869 out.endTag(null, "op");
2870 }
2871 out.endTag(null, "uid");
2872 }
2873 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002874
2875 if (allOps != null) {
2876 String lastPkg = null;
2877 for (int i=0; i<allOps.size(); i++) {
2878 AppOpsManager.PackageOps pkg = allOps.get(i);
2879 if (!pkg.getPackageName().equals(lastPkg)) {
2880 if (lastPkg != null) {
2881 out.endTag(null, "pkg");
2882 }
2883 lastPkg = pkg.getPackageName();
2884 out.startTag(null, "pkg");
2885 out.attribute(null, "n", lastPkg);
2886 }
2887 out.startTag(null, "uid");
2888 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04002889 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07002890 Ops ops = getOpsRawLocked(pkg.getUid(), pkg.getPackageName(),
2891 false /* edit */, false /* uidMismatchExpected */);
Jason Monk1c7c3192014-06-26 12:52:18 -04002892 // Should always be present as the list of PackageOps is generated
2893 // from Ops.
2894 if (ops != null) {
2895 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
2896 } else {
2897 out.attribute(null, "p", Boolean.toString(false));
2898 }
2899 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002900 List<AppOpsManager.OpEntry> ops = pkg.getOps();
2901 for (int j=0; j<ops.size(); j++) {
2902 AppOpsManager.OpEntry op = ops.get(j);
2903 out.startTag(null, "op");
2904 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07002905 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002906 out.attribute(null, "m", Integer.toString(op.getMode()));
2907 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002908 for (int k = 0; k < _NUM_UID_STATE; k++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002909 final long time = op.getLastTimeFor(k);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002910 if (time != 0) {
2911 out.attribute(null, UID_STATE_TIME_ATTRS[k],
2912 Long.toString(time));
2913 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002914 final long rejectTime = op.getLastRejectTimeFor(k);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002915 if (rejectTime != 0) {
2916 out.attribute(null, UID_STATE_REJECT_ATTRS[k],
2917 Long.toString(rejectTime));
2918 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002919 }
2920 int dur = op.getDuration();
2921 if (dur != 0) {
2922 out.attribute(null, "d", Integer.toString(dur));
2923 }
Svet Ganov99b60432015-06-27 13:15:22 -07002924 int proxyUid = op.getProxyUid();
2925 if (proxyUid != -1) {
2926 out.attribute(null, "pu", Integer.toString(proxyUid));
2927 }
2928 String proxyPackageName = op.getProxyPackageName();
2929 if (proxyPackageName != null) {
2930 out.attribute(null, "pp", proxyPackageName);
2931 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002932 out.endTag(null, "op");
2933 }
2934 out.endTag(null, "uid");
2935 }
2936 if (lastPkg != null) {
2937 out.endTag(null, "pkg");
2938 }
2939 }
2940
2941 out.endTag(null, "app-ops");
2942 out.endDocument();
2943 mFile.finishWrite(stream);
2944 } catch (IOException e) {
2945 Slog.w(TAG, "Failed to write state, restoring backup.", e);
2946 mFile.failWrite(stream);
2947 }
2948 }
2949 }
2950
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002951 static class Shell extends ShellCommand {
2952 final IAppOpsService mInterface;
2953 final AppOpsService mInternal;
2954
2955 int userId = UserHandle.USER_SYSTEM;
2956 String packageName;
2957 String opStr;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002958 String modeStr;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002959 int op;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002960 int mode;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002961 int packageUid;
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002962 int nonpackageUid;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05002963 final static Binder sBinder = new Binder();
2964 IBinder mToken;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002965
2966 Shell(IAppOpsService iface, AppOpsService internal) {
2967 mInterface = iface;
2968 mInternal = internal;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05002969 try {
2970 mToken = mInterface.getToken(sBinder);
2971 } catch (RemoteException e) {
2972 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002973 }
2974
2975 @Override
2976 public int onCommand(String cmd) {
2977 return onShellCommand(this, cmd);
2978 }
2979
2980 @Override
2981 public void onHelp() {
2982 PrintWriter pw = getOutPrintWriter();
2983 dumpCommandHelp(pw);
2984 }
2985
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002986 static private int strOpToOp(String op, PrintWriter err) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002987 try {
2988 return AppOpsManager.strOpToOp(op);
2989 } catch (IllegalArgumentException e) {
2990 }
2991 try {
2992 return Integer.parseInt(op);
2993 } catch (NumberFormatException e) {
2994 }
2995 try {
2996 return AppOpsManager.strDebugOpToOp(op);
2997 } catch (IllegalArgumentException e) {
2998 err.println("Error: " + e.getMessage());
2999 return -1;
3000 }
3001 }
3002
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003003 static int strModeToMode(String modeStr, PrintWriter err) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003004 for (int i = AppOpsManager.MODE_NAMES.length - 1; i >= 0; i--) {
3005 if (AppOpsManager.MODE_NAMES[i].equals(modeStr)) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003006 return i;
3007 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003008 }
3009 try {
3010 return Integer.parseInt(modeStr);
3011 } catch (NumberFormatException e) {
3012 }
3013 err.println("Error: Mode " + modeStr + " is not valid");
3014 return -1;
3015 }
3016
3017 int parseUserOpMode(int defMode, PrintWriter err) throws RemoteException {
3018 userId = UserHandle.USER_CURRENT;
3019 opStr = null;
3020 modeStr = null;
3021 for (String argument; (argument = getNextArg()) != null;) {
3022 if ("--user".equals(argument)) {
3023 userId = UserHandle.parseUserArg(getNextArgRequired());
3024 } else {
3025 if (opStr == null) {
3026 opStr = argument;
3027 } else if (modeStr == null) {
3028 modeStr = argument;
3029 break;
3030 }
3031 }
3032 }
3033 if (opStr == null) {
3034 err.println("Error: Operation not specified.");
3035 return -1;
3036 }
3037 op = strOpToOp(opStr, err);
3038 if (op < 0) {
3039 return -1;
3040 }
3041 if (modeStr != null) {
3042 if ((mode=strModeToMode(modeStr, err)) < 0) {
3043 return -1;
3044 }
3045 } else {
3046 mode = defMode;
3047 }
3048 return 0;
3049 }
3050
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003051 int parseUserPackageOp(boolean reqOp, PrintWriter err) throws RemoteException {
3052 userId = UserHandle.USER_CURRENT;
3053 packageName = null;
3054 opStr = null;
3055 for (String argument; (argument = getNextArg()) != null;) {
3056 if ("--user".equals(argument)) {
3057 userId = UserHandle.parseUserArg(getNextArgRequired());
3058 } else {
3059 if (packageName == null) {
3060 packageName = argument;
3061 } else if (opStr == null) {
3062 opStr = argument;
3063 break;
3064 }
3065 }
3066 }
3067 if (packageName == null) {
3068 err.println("Error: Package name not specified.");
3069 return -1;
3070 } else if (opStr == null && reqOp) {
3071 err.println("Error: Operation not specified.");
3072 return -1;
3073 }
3074 if (opStr != null) {
3075 op = strOpToOp(opStr, err);
3076 if (op < 0) {
3077 return -1;
3078 }
3079 } else {
3080 op = AppOpsManager.OP_NONE;
3081 }
3082 if (userId == UserHandle.USER_CURRENT) {
3083 userId = ActivityManager.getCurrentUser();
3084 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003085 nonpackageUid = -1;
3086 try {
3087 nonpackageUid = Integer.parseInt(packageName);
3088 } catch (NumberFormatException e) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003089 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003090 if (nonpackageUid == -1 && packageName.length() > 1 && packageName.charAt(0) == 'u'
3091 && packageName.indexOf('.') < 0) {
3092 int i = 1;
3093 while (i < packageName.length() && packageName.charAt(i) >= '0'
3094 && packageName.charAt(i) <= '9') {
3095 i++;
3096 }
3097 if (i > 1 && i < packageName.length()) {
3098 String userStr = packageName.substring(1, i);
3099 try {
3100 int user = Integer.parseInt(userStr);
3101 char type = packageName.charAt(i);
3102 i++;
3103 int startTypeVal = i;
3104 while (i < packageName.length() && packageName.charAt(i) >= '0'
3105 && packageName.charAt(i) <= '9') {
3106 i++;
3107 }
3108 if (i > startTypeVal) {
3109 String typeValStr = packageName.substring(startTypeVal, i);
3110 try {
3111 int typeVal = Integer.parseInt(typeValStr);
3112 if (type == 'a') {
3113 nonpackageUid = UserHandle.getUid(user,
3114 typeVal + Process.FIRST_APPLICATION_UID);
3115 } else if (type == 's') {
3116 nonpackageUid = UserHandle.getUid(user, typeVal);
3117 }
3118 } catch (NumberFormatException e) {
3119 }
3120 }
3121 } catch (NumberFormatException e) {
3122 }
3123 }
3124 }
3125 if (nonpackageUid != -1) {
3126 packageName = null;
3127 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08003128 packageUid = resolveUid(packageName);
3129 if (packageUid < 0) {
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003130 packageUid = AppGlobals.getPackageManager().getPackageUid(packageName,
3131 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
3132 }
3133 if (packageUid < 0) {
3134 err.println("Error: No UID for " + packageName + " in user " + userId);
3135 return -1;
3136 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003137 }
3138 return 0;
3139 }
3140 }
3141
3142 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003143 FileDescriptor err, String[] args, ShellCallback callback,
3144 ResultReceiver resultReceiver) {
3145 (new Shell(this, this)).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003146 }
3147
3148 static void dumpCommandHelp(PrintWriter pw) {
3149 pw.println("AppOps service (appops) commands:");
3150 pw.println(" help");
3151 pw.println(" Print this help text.");
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003152 pw.println(" start [--user <USER_ID>] <PACKAGE | UID> <OP> ");
3153 pw.println(" Starts a given operation for a particular application.");
3154 pw.println(" stop [--user <USER_ID>] <PACKAGE | UID> <OP> ");
3155 pw.println(" Stops a given operation for a particular application.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003156 pw.println(" set [--user <USER_ID>] <PACKAGE | UID> <OP> <MODE>");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003157 pw.println(" Set the mode for a particular application and operation.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003158 pw.println(" get [--user <USER_ID>] <PACKAGE | UID> [<OP>]");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003159 pw.println(" Return the mode for a particular application and optional operation.");
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003160 pw.println(" query-op [--user <USER_ID>] <OP> [<MODE>]");
3161 pw.println(" Print all packages that currently have the given op in the given mode.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003162 pw.println(" reset [--user <USER_ID>] [<PACKAGE>]");
3163 pw.println(" Reset the given application or all applications to default modes.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003164 pw.println(" write-settings");
3165 pw.println(" Immediately write pending changes to storage.");
3166 pw.println(" read-settings");
3167 pw.println(" Read the last written settings, replacing current state in RAM.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003168 pw.println(" options:");
3169 pw.println(" <PACKAGE> an Android package name.");
3170 pw.println(" <OP> an AppOps operation.");
3171 pw.println(" <MODE> one of allow, ignore, deny, or default");
3172 pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
3173 pw.println(" specified, the current user is assumed.");
3174 }
3175
3176 static int onShellCommand(Shell shell, String cmd) {
3177 if (cmd == null) {
3178 return shell.handleDefaultCommands(cmd);
3179 }
3180 PrintWriter pw = shell.getOutPrintWriter();
3181 PrintWriter err = shell.getErrPrintWriter();
3182 try {
3183 switch (cmd) {
3184 case "set": {
3185 int res = shell.parseUserPackageOp(true, err);
3186 if (res < 0) {
3187 return res;
3188 }
3189 String modeStr = shell.getNextArg();
3190 if (modeStr == null) {
3191 err.println("Error: Mode not specified.");
3192 return -1;
3193 }
3194
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003195 final int mode = shell.strModeToMode(modeStr, err);
3196 if (mode < 0) {
3197 return -1;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003198 }
3199
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003200 if (shell.packageName != null) {
3201 shell.mInterface.setMode(shell.op, shell.packageUid, shell.packageName,
3202 mode);
3203 } else {
3204 shell.mInterface.setUidMode(shell.op, shell.nonpackageUid, mode);
3205 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003206 return 0;
3207 }
3208 case "get": {
3209 int res = shell.parseUserPackageOp(false, err);
3210 if (res < 0) {
3211 return res;
3212 }
3213
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003214 List<AppOpsManager.PackageOps> ops = new ArrayList<>();
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003215 if (shell.packageName != null) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003216 // Uid mode overrides package mode, so make sure it's also reported
3217 List<AppOpsManager.PackageOps> r = shell.mInterface.getUidOps(
3218 shell.packageUid,
3219 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
3220 if (r != null) {
3221 ops.addAll(r);
3222 }
3223 r = shell.mInterface.getOpsForPackage(
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003224 shell.packageUid, shell.packageName,
3225 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003226 if (r != null) {
3227 ops.addAll(r);
3228 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003229 } else {
3230 ops = shell.mInterface.getUidOps(
3231 shell.nonpackageUid,
3232 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
3233 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003234 if (ops == null || ops.size() <= 0) {
3235 pw.println("No operations.");
Svet Ganov82f09bc2018-01-12 22:08:40 -08003236 if (shell.op > AppOpsManager.OP_NONE && shell.op < AppOpsManager._NUM_OP) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003237 pw.println("Default mode: " + AppOpsManager.modeToName(
Svet Ganov82f09bc2018-01-12 22:08:40 -08003238 AppOpsManager.opToDefaultMode(shell.op)));
3239 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003240 return 0;
3241 }
3242 final long now = System.currentTimeMillis();
3243 for (int i=0; i<ops.size(); i++) {
Eugene Suslae4ee2c22018-11-05 12:23:30 -08003244 AppOpsManager.PackageOps packageOps = ops.get(i);
3245 if (packageOps.getPackageName() == null) {
3246 pw.print("Uid mode: ");
3247 }
3248 List<AppOpsManager.OpEntry> entries = packageOps.getOps();
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003249 for (int j=0; j<entries.size(); j++) {
3250 AppOpsManager.OpEntry ent = entries.get(j);
3251 pw.print(AppOpsManager.opToName(ent.getOp()));
3252 pw.print(": ");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003253 pw.print(AppOpsManager.modeToName(ent.getMode()));
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003254 if (ent.getTime() != 0) {
3255 pw.print("; time=");
3256 TimeUtils.formatDuration(now - ent.getTime(), pw);
3257 pw.print(" ago");
3258 }
3259 if (ent.getRejectTime() != 0) {
3260 pw.print("; rejectTime=");
3261 TimeUtils.formatDuration(now - ent.getRejectTime(), pw);
3262 pw.print(" ago");
3263 }
3264 if (ent.getDuration() == -1) {
3265 pw.print(" (running)");
3266 } else if (ent.getDuration() != 0) {
3267 pw.print("; duration=");
3268 TimeUtils.formatDuration(ent.getDuration(), pw);
3269 }
3270 pw.println();
3271 }
3272 }
3273 return 0;
3274 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003275 case "query-op": {
3276 int res = shell.parseUserOpMode(AppOpsManager.MODE_IGNORED, err);
3277 if (res < 0) {
3278 return res;
3279 }
3280 List<AppOpsManager.PackageOps> ops = shell.mInterface.getPackagesForOps(
3281 new int[] {shell.op});
3282 if (ops == null || ops.size() <= 0) {
3283 pw.println("No operations.");
3284 return 0;
3285 }
3286 for (int i=0; i<ops.size(); i++) {
3287 final AppOpsManager.PackageOps pkg = ops.get(i);
3288 boolean hasMatch = false;
3289 final List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
3290 for (int j=0; j<entries.size(); j++) {
3291 AppOpsManager.OpEntry ent = entries.get(j);
3292 if (ent.getOp() == shell.op && ent.getMode() == shell.mode) {
3293 hasMatch = true;
3294 break;
3295 }
3296 }
3297 if (hasMatch) {
3298 pw.println(pkg.getPackageName());
3299 }
3300 }
3301 return 0;
3302 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003303 case "reset": {
3304 String packageName = null;
3305 int userId = UserHandle.USER_CURRENT;
3306 for (String argument; (argument = shell.getNextArg()) != null;) {
3307 if ("--user".equals(argument)) {
3308 String userStr = shell.getNextArgRequired();
3309 userId = UserHandle.parseUserArg(userStr);
3310 } else {
3311 if (packageName == null) {
3312 packageName = argument;
3313 } else {
3314 err.println("Error: Unsupported argument: " + argument);
3315 return -1;
3316 }
3317 }
3318 }
3319
3320 if (userId == UserHandle.USER_CURRENT) {
3321 userId = ActivityManager.getCurrentUser();
3322 }
3323
3324 shell.mInterface.resetAllModes(userId, packageName);
3325 pw.print("Reset all modes for: ");
3326 if (userId == UserHandle.USER_ALL) {
3327 pw.print("all users");
3328 } else {
3329 pw.print("user "); pw.print(userId);
3330 }
3331 pw.print(", ");
3332 if (packageName == null) {
3333 pw.println("all packages");
3334 } else {
3335 pw.print("package "); pw.println(packageName);
3336 }
3337 return 0;
3338 }
3339 case "write-settings": {
Dianne Hackbornd5254412018-05-11 18:02:58 -07003340 shell.mInternal.enforceManageAppOpsModes(Binder.getCallingPid(),
3341 Binder.getCallingUid(), -1);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003342 long token = Binder.clearCallingIdentity();
3343 try {
3344 synchronized (shell.mInternal) {
3345 shell.mInternal.mHandler.removeCallbacks(shell.mInternal.mWriteRunner);
3346 }
3347 shell.mInternal.writeState();
3348 pw.println("Current settings written.");
3349 } finally {
3350 Binder.restoreCallingIdentity(token);
3351 }
3352 return 0;
3353 }
3354 case "read-settings": {
Dianne Hackbornd5254412018-05-11 18:02:58 -07003355 shell.mInternal.enforceManageAppOpsModes(Binder.getCallingPid(),
3356 Binder.getCallingUid(), -1);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003357 long token = Binder.clearCallingIdentity();
3358 try {
3359 shell.mInternal.readState();
3360 pw.println("Last settings read.");
3361 } finally {
3362 Binder.restoreCallingIdentity(token);
3363 }
3364 return 0;
3365 }
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003366 case "start": {
3367 int res = shell.parseUserPackageOp(true, err);
3368 if (res < 0) {
3369 return res;
3370 }
3371
3372 if (shell.packageName != null) {
3373 shell.mInterface.startOperation(shell.mToken,
3374 shell.op, shell.packageUid, shell.packageName, true);
3375 } else {
3376 return -1;
3377 }
3378 return 0;
3379 }
3380 case "stop": {
3381 int res = shell.parseUserPackageOp(true, err);
3382 if (res < 0) {
3383 return res;
3384 }
3385
3386 if (shell.packageName != null) {
3387 shell.mInterface.finishOperation(shell.mToken,
3388 shell.op, shell.packageUid, shell.packageName);
3389 } else {
3390 return -1;
3391 }
3392 return 0;
3393 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003394 default:
3395 return shell.handleDefaultCommands(cmd);
3396 }
3397 } catch (RemoteException e) {
3398 pw.println("Remote exception: " + e);
3399 }
3400 return -1;
3401 }
3402
3403 private void dumpHelp(PrintWriter pw) {
3404 pw.println("AppOps service (appops) dump options:");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003405 pw.println(" -h");
3406 pw.println(" Print this help text.");
3407 pw.println(" --op [OP]");
3408 pw.println(" Limit output to data associated with the given app op code.");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003409 pw.println(" --mode [MODE]");
3410 pw.println(" Limit output to data associated with the given app op mode.");
3411 pw.println(" --package [PACKAGE]");
3412 pw.println(" Limit output to data associated with the given package name.");
Dianne Hackborn125dc532019-01-09 13:31:48 -08003413 pw.println(" --watchers");
3414 pw.println(" Only output the watcher sections.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003415 }
3416
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003417 private void dumpTimesLocked(PrintWriter pw, String firstPrefix, String prefix, long[] times,
3418 long now, SimpleDateFormat sdf, Date date) {
3419 boolean hasTime = false;
3420 for (int i = 0; i < _NUM_UID_STATE; i++) {
3421 if (times[i] != 0) {
3422 hasTime = true;
3423 break;
3424 }
3425 }
3426 if (!hasTime) {
3427 return;
3428 }
3429 boolean first = true;
3430 for (int i = 0; i < _NUM_UID_STATE; i++) {
3431 if (times[i] != 0) {
3432 pw.print(first ? firstPrefix : prefix);
3433 first = false;
3434 pw.print(UID_STATE_NAMES[i]);
3435 pw.print(" = ");
3436 date.setTime(times[i]);
3437 pw.print(sdf.format(date));
3438 pw.print(" (");
3439 TimeUtils.formatDuration(times[i]-now, pw);
3440 pw.println(")");
3441 }
3442 }
3443 }
3444
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003445 @Override
3446 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06003447 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003448
Svet Ganov8455ba22019-01-02 13:05:56 -08003449 int dumpOp = OP_NONE;
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003450 String dumpPackage = null;
Svet Ganov8455ba22019-01-02 13:05:56 -08003451 int dumpUid = Process.INVALID_UID;
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003452 int dumpMode = -1;
Dianne Hackborn125dc532019-01-09 13:31:48 -08003453 boolean dumpWatchers = false;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003454
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003455 if (args != null) {
3456 for (int i=0; i<args.length; i++) {
3457 String arg = args[i];
3458 if ("-h".equals(arg)) {
3459 dumpHelp(pw);
3460 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07003461 } else if ("-a".equals(arg)) {
3462 // dump all data
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003463 } else if ("--op".equals(arg)) {
3464 i++;
3465 if (i >= args.length) {
3466 pw.println("No argument for --op option");
3467 return;
3468 }
3469 dumpOp = Shell.strOpToOp(args[i], pw);
3470 if (dumpOp < 0) {
3471 return;
3472 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003473 } else if ("--package".equals(arg)) {
3474 i++;
3475 if (i >= args.length) {
3476 pw.println("No argument for --package option");
3477 return;
3478 }
3479 dumpPackage = args[i];
3480 try {
3481 dumpUid = AppGlobals.getPackageManager().getPackageUid(dumpPackage,
3482 PackageManager.MATCH_KNOWN_PACKAGES | PackageManager.MATCH_INSTANT,
3483 0);
3484 } catch (RemoteException e) {
3485 }
3486 if (dumpUid < 0) {
3487 pw.println("Unknown package: " + dumpPackage);
3488 return;
3489 }
3490 dumpUid = UserHandle.getAppId(dumpUid);
3491 } else if ("--mode".equals(arg)) {
3492 i++;
3493 if (i >= args.length) {
3494 pw.println("No argument for --mode option");
3495 return;
3496 }
3497 dumpMode = Shell.strModeToMode(args[i], pw);
3498 if (dumpMode < 0) {
3499 return;
3500 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08003501 } else if ("--watchers".equals(arg)) {
3502 dumpWatchers = true;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003503 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
3504 pw.println("Unknown option: " + arg);
3505 return;
3506 } else {
3507 pw.println("Unknown command: " + arg);
3508 return;
3509 }
3510 }
3511 }
3512
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003513 synchronized (this) {
3514 pw.println("Current AppOps Service state:");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003515 mConstants.dump(pw);
3516 pw.println();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003517 final long now = System.currentTimeMillis();
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003518 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003519 final long nowUptime = SystemClock.uptimeMillis();
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003520 final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
3521 final Date date = new Date();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003522 boolean needSep = false;
Dianne Hackborn125dc532019-01-09 13:31:48 -08003523 if (dumpOp < 0 && dumpMode < 0 && dumpPackage == null && mProfileOwners != null
3524 && !dumpWatchers) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07003525 pw.println(" Profile owners:");
3526 for (int poi = 0; poi < mProfileOwners.size(); poi++) {
3527 pw.print(" User #");
3528 pw.print(mProfileOwners.keyAt(poi));
3529 pw.print(": ");
3530 UserHandle.formatUid(pw, mProfileOwners.valueAt(poi));
3531 pw.println();
3532 }
3533 pw.println();
3534 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003535 if (mOpModeWatchers.size() > 0) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003536 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003537 for (int i=0; i<mOpModeWatchers.size(); i++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003538 if (dumpOp >= 0 && dumpOp != mOpModeWatchers.keyAt(i)) {
3539 continue;
3540 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003541 boolean printedOpHeader = false;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003542 ArraySet<ModeCallback> callbacks = mOpModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003543 for (int j=0; j<callbacks.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003544 final ModeCallback cb = callbacks.valueAt(j);
Dianne Hackborn125dc532019-01-09 13:31:48 -08003545 if (dumpPackage != null
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003546 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3547 continue;
3548 }
3549 needSep = true;
3550 if (!printedHeader) {
3551 pw.println(" Op mode watchers:");
3552 printedHeader = true;
3553 }
3554 if (!printedOpHeader) {
3555 pw.print(" Op ");
3556 pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
3557 pw.println(":");
3558 printedOpHeader = true;
3559 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003560 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003561 pw.println(cb);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003562 }
3563 }
3564 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003565 if (mPackageModeWatchers.size() > 0 && dumpOp < 0) {
3566 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003567 for (int i=0; i<mPackageModeWatchers.size(); i++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003568 if (dumpPackage != null && !dumpPackage.equals(mPackageModeWatchers.keyAt(i))) {
3569 continue;
3570 }
3571 needSep = true;
3572 if (!printedHeader) {
3573 pw.println(" Package mode watchers:");
3574 printedHeader = true;
3575 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003576 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
3577 pw.println(":");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003578 ArraySet<ModeCallback> callbacks = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003579 for (int j=0; j<callbacks.size(); j++) {
3580 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08003581 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003582 }
3583 }
3584 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003585 if (mModeWatchers.size() > 0 && dumpOp < 0) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003586 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003587 for (int i=0; i<mModeWatchers.size(); i++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003588 final ModeCallback cb = mModeWatchers.valueAt(i);
Dianne Hackborn125dc532019-01-09 13:31:48 -08003589 if (dumpPackage != null
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003590 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3591 continue;
3592 }
3593 needSep = true;
3594 if (!printedHeader) {
3595 pw.println(" All op mode watchers:");
3596 printedHeader = true;
3597 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003598 pw.print(" ");
3599 pw.print(Integer.toHexString(System.identityHashCode(mModeWatchers.keyAt(i))));
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003600 pw.print(": "); pw.println(cb);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003601 }
3602 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003603 if (mActiveWatchers.size() > 0 && dumpMode < 0) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003604 needSep = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003605 boolean printedHeader = false;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003606 for (int i = 0; i < mActiveWatchers.size(); i++) {
3607 final SparseArray<ActiveCallback> activeWatchers = mActiveWatchers.valueAt(i);
3608 if (activeWatchers.size() <= 0) {
3609 continue;
3610 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003611 final ActiveCallback cb = activeWatchers.valueAt(0);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003612 if (dumpOp >= 0 && activeWatchers.indexOfKey(dumpOp) < 0) {
3613 continue;
3614 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08003615 if (dumpPackage != null
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003616 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3617 continue;
3618 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003619 if (!printedHeader) {
3620 pw.println(" All op active watchers:");
3621 printedHeader = true;
3622 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003623 pw.print(" ");
3624 pw.print(Integer.toHexString(System.identityHashCode(
3625 mActiveWatchers.keyAt(i))));
3626 pw.println(" ->");
3627 pw.print(" [");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003628 final int opCount = activeWatchers.size();
3629 for (i = 0; i < opCount; i++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003630 if (i > 0) {
3631 pw.print(' ');
3632 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003633 pw.print(AppOpsManager.opToName(activeWatchers.keyAt(i)));
3634 if (i < opCount - 1) {
3635 pw.print(',');
3636 }
3637 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003638 pw.println("]");
3639 pw.print(" ");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003640 pw.println(cb);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003641 }
3642 }
Svet Ganovb3d2ae22018-12-17 22:06:15 -08003643 if (mNotedWatchers.size() > 0 && dumpMode < 0) {
3644 needSep = true;
3645 boolean printedHeader = false;
3646 for (int i = 0; i < mNotedWatchers.size(); i++) {
3647 final SparseArray<NotedCallback> notedWatchers = mNotedWatchers.valueAt(i);
3648 if (notedWatchers.size() <= 0) {
3649 continue;
3650 }
3651 final NotedCallback cb = notedWatchers.valueAt(0);
3652 if (dumpOp >= 0 && notedWatchers.indexOfKey(dumpOp) < 0) {
3653 continue;
3654 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08003655 if (dumpPackage != null
Svet Ganovb3d2ae22018-12-17 22:06:15 -08003656 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3657 continue;
3658 }
3659 if (!printedHeader) {
3660 pw.println(" All op noted watchers:");
3661 printedHeader = true;
3662 }
3663 pw.print(" ");
3664 pw.print(Integer.toHexString(System.identityHashCode(
3665 mNotedWatchers.keyAt(i))));
3666 pw.println(" ->");
3667 pw.print(" [");
3668 final int opCount = notedWatchers.size();
3669 for (i = 0; i < opCount; i++) {
3670 if (i > 0) {
3671 pw.print(' ');
3672 }
3673 pw.print(AppOpsManager.opToName(notedWatchers.keyAt(i)));
3674 if (i < opCount - 1) {
3675 pw.print(',');
3676 }
3677 }
3678 pw.println("]");
3679 pw.print(" ");
3680 pw.println(cb);
3681 }
3682 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08003683 if (mClients.size() > 0 && dumpMode < 0 && !dumpWatchers) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003684 needSep = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003685 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003686 for (int i=0; i<mClients.size(); i++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003687 boolean printedClient = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003688 ClientState cs = mClients.valueAt(i);
Svet Ganovf7b47252018-02-26 11:11:27 -08003689 if (cs.mStartedOps.size() > 0) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003690 boolean printedStarted = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003691 for (int j=0; j<cs.mStartedOps.size(); j++) {
3692 Op op = cs.mStartedOps.get(j);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003693 if (dumpOp >= 0 && op.op != dumpOp) {
3694 continue;
3695 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003696 if (dumpPackage != null && !dumpPackage.equals(op.packageName)) {
3697 continue;
3698 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003699 if (!printedHeader) {
3700 pw.println(" Clients:");
3701 printedHeader = true;
3702 }
3703 if (!printedClient) {
3704 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
3705 pw.print(" "); pw.println(cs);
3706 printedClient = true;
3707 }
3708 if (!printedStarted) {
3709 pw.println(" Started ops:");
3710 printedStarted = true;
3711 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003712 pw.print(" "); pw.print("uid="); pw.print(op.uid);
3713 pw.print(" pkg="); pw.print(op.packageName);
3714 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
3715 }
3716 }
3717 }
3718 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003719 if (mAudioRestrictions.size() > 0 && dumpOp < 0 && dumpPackage != null
Dianne Hackborn125dc532019-01-09 13:31:48 -08003720 && dumpMode < 0 && !dumpWatchers) {
John Spurlock1af30c72014-03-10 08:33:35 -04003721 boolean printedHeader = false;
3722 for (int o=0; o<mAudioRestrictions.size(); o++) {
3723 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
3724 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
3725 for (int i=0; i<restrictions.size(); i++) {
3726 if (!printedHeader){
3727 pw.println(" Audio Restrictions:");
3728 printedHeader = true;
3729 needSep = true;
3730 }
John Spurlock7b414672014-07-18 13:02:39 -04003731 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04003732 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04003733 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04003734 Restriction r = restrictions.valueAt(i);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003735 pw.print(": mode="); pw.println(AppOpsManager.modeToName(r.mode));
John Spurlock1af30c72014-03-10 08:33:35 -04003736 if (!r.exceptionPackages.isEmpty()) {
3737 pw.println(" Exceptions:");
3738 for (int j=0; j<r.exceptionPackages.size(); j++) {
3739 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
3740 }
3741 }
3742 }
3743 }
3744 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003745 if (needSep) {
3746 pw.println();
3747 }
Svet Ganov2af57082015-07-30 08:44:20 -07003748 for (int i=0; i<mUidStates.size(); i++) {
3749 UidState uidState = mUidStates.valueAt(i);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003750 final SparseIntArray opModes = uidState.opModes;
3751 final ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
3752
Dianne Hackborn125dc532019-01-09 13:31:48 -08003753 if (dumpWatchers) {
3754 continue;
3755 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003756 if (dumpOp >= 0 || dumpPackage != null || dumpMode >= 0) {
3757 boolean hasOp = dumpOp < 0 || (uidState.opModes != null
3758 && uidState.opModes.indexOfKey(dumpOp) >= 0);
3759 boolean hasPackage = dumpPackage == null;
3760 boolean hasMode = dumpMode < 0;
3761 if (!hasMode && opModes != null) {
3762 for (int opi = 0; !hasMode && opi < opModes.size(); opi++) {
3763 if (opModes.valueAt(opi) == dumpMode) {
3764 hasMode = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003765 }
3766 }
3767 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003768 if (pkgOps != null) {
3769 for (int pkgi = 0;
Svet Ganov8455ba22019-01-02 13:05:56 -08003770 (!hasOp || !hasPackage || !hasMode) && pkgi < pkgOps.size();
3771 pkgi++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003772 Ops ops = pkgOps.valueAt(pkgi);
3773 if (!hasOp && ops != null && ops.indexOfKey(dumpOp) >= 0) {
3774 hasOp = true;
3775 }
3776 if (!hasMode) {
3777 for (int opi = 0; !hasMode && opi < ops.size(); opi++) {
3778 if (ops.valueAt(opi).mode == dumpMode) {
3779 hasMode = true;
3780 }
3781 }
3782 }
3783 if (!hasPackage && dumpPackage.equals(ops.packageName)) {
3784 hasPackage = true;
3785 }
3786 }
3787 }
3788 if (uidState.foregroundOps != null && !hasOp) {
3789 if (uidState.foregroundOps.indexOfKey(dumpOp) > 0) {
3790 hasOp = true;
3791 }
3792 }
3793 if (!hasOp || !hasPackage || !hasMode) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003794 continue;
3795 }
3796 }
Svet Ganov2af57082015-07-30 08:44:20 -07003797
3798 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003799 pw.print(" state=");
3800 pw.println(UID_STATE_NAMES[uidState.state]);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003801 if (uidState.state != uidState.pendingState) {
3802 pw.print(" pendingState=");
3803 pw.println(UID_STATE_NAMES[uidState.pendingState]);
3804 }
3805 if (uidState.pendingStateCommitTime != 0) {
3806 pw.print(" pendingStateCommitTime=");
Dianne Hackborn9fb93502018-06-18 12:29:44 -07003807 TimeUtils.formatDuration(uidState.pendingStateCommitTime, nowElapsed, pw);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003808 pw.println();
3809 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003810 if (uidState.startNesting != 0) {
3811 pw.print(" startNesting=");
3812 pw.println(uidState.startNesting);
3813 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003814 if (uidState.foregroundOps != null && (dumpMode < 0
3815 || dumpMode == AppOpsManager.MODE_FOREGROUND)) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003816 pw.println(" foregroundOps:");
3817 for (int j = 0; j < uidState.foregroundOps.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003818 if (dumpOp >= 0 && dumpOp != uidState.foregroundOps.keyAt(j)) {
3819 continue;
3820 }
3821 pw.print(" ");
3822 pw.print(AppOpsManager.opToName(uidState.foregroundOps.keyAt(j)));
3823 pw.print(": ");
3824 pw.println(uidState.foregroundOps.valueAt(j) ? "WATCHER" : "SILENT");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003825 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003826 pw.print(" hasForegroundWatchers=");
3827 pw.println(uidState.hasForegroundWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003828 }
Svet Ganovee438d42017-01-19 18:04:38 -08003829 needSep = true;
Svet Ganov2af57082015-07-30 08:44:20 -07003830
Svet Ganov2af57082015-07-30 08:44:20 -07003831 if (opModes != null) {
3832 final int opModeCount = opModes.size();
3833 for (int j = 0; j < opModeCount; j++) {
3834 final int code = opModes.keyAt(j);
3835 final int mode = opModes.valueAt(j);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003836 if (dumpOp >= 0 && dumpOp != code) {
3837 continue;
3838 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003839 if (dumpMode >= 0 && dumpMode != mode) {
3840 continue;
3841 }
Svet Ganov2af57082015-07-30 08:44:20 -07003842 pw.print(" "); pw.print(AppOpsManager.opToName(code));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003843 pw.print(": mode="); pw.println(AppOpsManager.modeToName(mode));
Svet Ganov2af57082015-07-30 08:44:20 -07003844 }
3845 }
3846
Svet Ganov2af57082015-07-30 08:44:20 -07003847 if (pkgOps == null) {
3848 continue;
3849 }
3850
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003851 for (int pkgi = 0; pkgi < pkgOps.size(); pkgi++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003852 final Ops ops = pkgOps.valueAt(pkgi);
3853 if (dumpPackage != null && !dumpPackage.equals(ops.packageName)) {
3854 continue;
3855 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003856 boolean printedPackage = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003857 for (int j=0; j<ops.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003858 final Op op = ops.valueAt(j);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003859 if (dumpOp >= 0 && dumpOp != op.op) {
3860 continue;
3861 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003862 if (dumpMode >= 0 && dumpMode != op.mode) {
3863 continue;
3864 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003865 if (!printedPackage) {
3866 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
3867 printedPackage = true;
3868 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003869 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003870 pw.print(" ("); pw.print(AppOpsManager.modeToName(op.mode));
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003871 final int switchOp = AppOpsManager.opToSwitch(op.op);
3872 if (switchOp != op.op) {
3873 pw.print(" / switch ");
3874 pw.print(AppOpsManager.opToName(switchOp));
3875 final Op switchObj = ops.get(switchOp);
3876 int mode = switchObj != null
3877 ? switchObj.mode : AppOpsManager.opToDefaultMode(switchOp);
3878 pw.print("="); pw.print(AppOpsManager.modeToName(mode));
3879 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003880 pw.println("): ");
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003881 dumpTimesLocked(pw,
3882 " Access: ",
3883 " ", op.time, now, sdf, date);
3884 dumpTimesLocked(pw,
3885 " Reject: ",
3886 " ", op.rejectTime, now, sdf, date);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003887 if (op.duration == -1) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003888 pw.print(" Running start at: ");
3889 TimeUtils.formatDuration(nowElapsed-op.startRealtime, pw);
3890 pw.println();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08003891 } else if (op.duration != 0) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003892 pw.print(" duration=");
3893 TimeUtils.formatDuration(op.duration, pw);
3894 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003895 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003896 if (op.startNesting != 0) {
3897 pw.print(" startNesting=");
3898 pw.println(op.startNesting);
3899 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003900 }
3901 }
3902 }
Svet Ganovee438d42017-01-19 18:04:38 -08003903 if (needSep) {
3904 pw.println();
3905 }
3906
3907 final int userRestrictionCount = mOpUserRestrictions.size();
3908 for (int i = 0; i < userRestrictionCount; i++) {
3909 IBinder token = mOpUserRestrictions.keyAt(i);
3910 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
Dianne Hackborn125dc532019-01-09 13:31:48 -08003911 boolean printedTokenHeader = false;
3912
3913 if (dumpMode >= 0 || dumpWatchers) {
3914 continue;
3915 }
Svet Ganovee438d42017-01-19 18:04:38 -08003916
3917 final int restrictionCount = restrictionState.perUserRestrictions != null
3918 ? restrictionState.perUserRestrictions.size() : 0;
Dianne Hackborn125dc532019-01-09 13:31:48 -08003919 if (restrictionCount > 0 && dumpPackage == null) {
3920 boolean printedOpsHeader = false;
Svet Ganovee438d42017-01-19 18:04:38 -08003921 for (int j = 0; j < restrictionCount; j++) {
3922 int userId = restrictionState.perUserRestrictions.keyAt(j);
3923 boolean[] restrictedOps = restrictionState.perUserRestrictions.valueAt(j);
3924 if (restrictedOps == null) {
3925 continue;
3926 }
Dianne Hackborn125dc532019-01-09 13:31:48 -08003927 if (dumpOp >= 0 && (dumpOp >= restrictedOps.length
3928 || !restrictedOps[dumpOp])) {
3929 continue;
3930 }
3931 if (!printedTokenHeader) {
3932 pw.println(" User restrictions for token " + token + ":");
3933 printedTokenHeader = true;
3934 }
3935 if (!printedOpsHeader) {
3936 pw.println(" Restricted ops:");
3937 printedOpsHeader = true;
3938 }
Svet Ganovee438d42017-01-19 18:04:38 -08003939 StringBuilder restrictedOpsValue = new StringBuilder();
3940 restrictedOpsValue.append("[");
3941 final int restrictedOpCount = restrictedOps.length;
3942 for (int k = 0; k < restrictedOpCount; k++) {
3943 if (restrictedOps[k]) {
3944 if (restrictedOpsValue.length() > 1) {
3945 restrictedOpsValue.append(", ");
3946 }
3947 restrictedOpsValue.append(AppOpsManager.opToName(k));
3948 }
3949 }
3950 restrictedOpsValue.append("]");
3951 pw.print(" "); pw.print("user: "); pw.print(userId);
3952 pw.print(" restricted ops: "); pw.println(restrictedOpsValue);
3953 }
3954 }
3955
3956 final int excludedPackageCount = restrictionState.perUserExcludedPackages != null
3957 ? restrictionState.perUserExcludedPackages.size() : 0;
Dianne Hackborn125dc532019-01-09 13:31:48 -08003958 if (excludedPackageCount > 0 && dumpOp < 0) {
3959 boolean printedPackagesHeader = false;
Svet Ganovee438d42017-01-19 18:04:38 -08003960 for (int j = 0; j < excludedPackageCount; j++) {
3961 int userId = restrictionState.perUserExcludedPackages.keyAt(j);
3962 String[] packageNames = restrictionState.perUserExcludedPackages.valueAt(j);
Dianne Hackborn125dc532019-01-09 13:31:48 -08003963 if (packageNames == null) {
3964 continue;
3965 }
3966 boolean hasPackage;
3967 if (dumpPackage != null) {
3968 hasPackage = false;
3969 for (String pkg : packageNames) {
3970 if (dumpPackage.equals(pkg)) {
3971 hasPackage = true;
3972 break;
3973 }
3974 }
3975 } else {
3976 hasPackage = true;
3977 }
3978 if (!hasPackage) {
3979 continue;
3980 }
3981 if (!printedTokenHeader) {
3982 pw.println(" User restrictions for token " + token + ":");
3983 printedTokenHeader = true;
3984 }
3985 if (!printedPackagesHeader) {
3986 pw.println(" Excluded packages:");
3987 printedPackagesHeader = true;
3988 }
Svet Ganovee438d42017-01-19 18:04:38 -08003989 pw.print(" "); pw.print("user: "); pw.print(userId);
3990 pw.print(" packages: "); pw.println(Arrays.toString(packageNames));
3991 }
3992 }
3993 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003994 }
Svet Ganov8455ba22019-01-02 13:05:56 -08003995
3996 // Must not hold the appops lock
3997 mHistoricalRegistry.dump(" ", pw, dumpUid, dumpPackage, dumpOp);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003998 }
John Spurlock1af30c72014-03-10 08:33:35 -04003999
4000 private static final class Restriction {
4001 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
4002 int mode;
4003 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
4004 }
Jason Monk62062992014-05-06 09:55:28 -04004005
4006 @Override
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004007 public void setUserRestrictions(Bundle restrictions, IBinder token, int userHandle) {
Jason Monk62062992014-05-06 09:55:28 -04004008 checkSystemUid("setUserRestrictions");
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004009 Preconditions.checkNotNull(restrictions);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004010 Preconditions.checkNotNull(token);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004011 for (int i = 0; i < AppOpsManager._NUM_OP; i++) {
Jason Monk62062992014-05-06 09:55:28 -04004012 String restriction = AppOpsManager.opToRestriction(i);
Suprabh Shukla64e0dcb2016-05-24 16:23:11 -07004013 if (restriction != null) {
4014 setUserRestrictionNoCheck(i, restrictions.getBoolean(restriction, false), token,
4015 userHandle, null);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004016 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004017 }
4018 }
4019
4020 @Override
Ruben Brunk29931bc2016-03-11 00:24:26 -08004021 public void setUserRestriction(int code, boolean restricted, IBinder token, int userHandle,
4022 String[] exceptionPackages) {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004023 if (Binder.getCallingPid() != Process.myPid()) {
4024 mContext.enforcePermission(Manifest.permission.MANAGE_APP_OPS_RESTRICTIONS,
4025 Binder.getCallingPid(), Binder.getCallingUid(), null);
4026 }
4027 if (userHandle != UserHandle.getCallingUserId()) {
4028 if (mContext.checkCallingOrSelfPermission(Manifest.permission
4029 .INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
4030 && mContext.checkCallingOrSelfPermission(Manifest.permission
4031 .INTERACT_ACROSS_USERS) != PackageManager.PERMISSION_GRANTED) {
4032 throw new SecurityException("Need INTERACT_ACROSS_USERS_FULL or"
4033 + " INTERACT_ACROSS_USERS to interact cross user ");
Jason Monk62062992014-05-06 09:55:28 -04004034 }
4035 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004036 verifyIncomingOp(code);
4037 Preconditions.checkNotNull(token);
Ruben Brunk29931bc2016-03-11 00:24:26 -08004038 setUserRestrictionNoCheck(code, restricted, token, userHandle, exceptionPackages);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004039 }
4040
4041 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
Ruben Brunk29931bc2016-03-11 00:24:26 -08004042 int userHandle, String[] exceptionPackages) {
Svet Ganov442ed572016-08-17 17:29:43 -07004043 synchronized (AppOpsService.this) {
4044 ClientRestrictionState restrictionState = mOpUserRestrictions.get(token);
4045
4046 if (restrictionState == null) {
4047 try {
4048 restrictionState = new ClientRestrictionState(token);
4049 } catch (RemoteException e) {
4050 return;
4051 }
4052 mOpUserRestrictions.put(token, restrictionState);
Ruben Brunk29931bc2016-03-11 00:24:26 -08004053 }
Svet Ganov442ed572016-08-17 17:29:43 -07004054
4055 if (restrictionState.setRestriction(code, restricted, exceptionPackages, userHandle)) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004056 mHandler.sendMessage(PooledLambda.obtainMessage(
Svet Ganov3a95f832018-03-23 17:44:30 -07004057 AppOpsService::notifyWatchersOfChange, this, code, UID_ANY));
Svet Ganov442ed572016-08-17 17:29:43 -07004058 }
4059
4060 if (restrictionState.isDefault()) {
4061 mOpUserRestrictions.remove(token);
4062 restrictionState.destroy();
4063 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08004064 }
Julia Reynoldsbb21c252016-04-05 16:01:49 -04004065 }
4066
Svet Ganov3a95f832018-03-23 17:44:30 -07004067 private void notifyWatchersOfChange(int code, int uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004068 final ArraySet<ModeCallback> clonedCallbacks;
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004069 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004070 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004071 if (callbacks == null) {
4072 return;
4073 }
Dianne Hackborn68d76552017-02-27 15:32:03 -08004074 clonedCallbacks = new ArraySet<>(callbacks);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004075 }
4076
Svet Ganov3a95f832018-03-23 17:44:30 -07004077 notifyOpChanged(clonedCallbacks, code, uid, null);
Jason Monk62062992014-05-06 09:55:28 -04004078 }
4079
4080 @Override
4081 public void removeUser(int userHandle) throws RemoteException {
4082 checkSystemUid("removeUser");
Svet Ganov442ed572016-08-17 17:29:43 -07004083 synchronized (AppOpsService.this) {
4084 final int tokenCount = mOpUserRestrictions.size();
4085 for (int i = tokenCount - 1; i >= 0; i--) {
4086 ClientRestrictionState opRestrictions = mOpUserRestrictions.valueAt(i);
4087 opRestrictions.removeUser(userHandle);
4088 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07004089 removeUidsForUserLocked(userHandle);
4090 }
4091 }
4092
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004093 @Override
4094 public boolean isOperationActive(int code, int uid, String packageName) {
Svet Ganovf7b47252018-02-26 11:11:27 -08004095 if (Binder.getCallingUid() != uid) {
4096 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
4097 != PackageManager.PERMISSION_GRANTED) {
4098 return false;
4099 }
4100 }
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004101 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004102 final String resolvedPackageName = resolvePackageName(uid, packageName);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004103 if (resolvedPackageName == null) {
4104 return false;
4105 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08004106 synchronized (AppOpsService.this) {
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004107 for (int i = mClients.size() - 1; i >= 0; i--) {
4108 final ClientState client = mClients.valueAt(i);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06004109 for (int j = client.mStartedOps.size() - 1; j >= 0; j--) {
4110 final Op op = client.mStartedOps.get(j);
4111 if (op.op == code && op.uid == uid) return true;
4112 }
4113 }
4114 }
4115 return false;
4116 }
4117
Svet Ganov8455ba22019-01-02 13:05:56 -08004118 @Override
4119 public void setHistoryParameters(@AppOpsManager.HistoricalMode int mode,
4120 long baseSnapshotInterval, int compressionStep) {
4121 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4122 "setHistoryParameters");
4123 // Must not hold the appops lock
4124 mHistoricalRegistry.setHistoryParameters(mode, baseSnapshotInterval, compressionStep);
4125 }
4126
4127 @Override
4128 public void offsetHistory(long offsetMillis) {
4129 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4130 "offsetHistory");
4131 // Must not hold the appops lock
4132 mHistoricalRegistry.offsetHistory(offsetMillis);
4133 }
4134
4135 @Override
4136 public void addHistoricalOps(HistoricalOps ops) {
4137 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4138 "addHistoricalOps");
4139 // Must not hold the appops lock
4140 mHistoricalRegistry.addHistoricalOps(ops);
4141 }
4142
4143 @Override
4144 public void resetHistoryParameters() {
4145 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4146 "resetHistoryParameters");
4147 // Must not hold the appops lock
4148 mHistoricalRegistry.resetHistoryParameters();
4149 }
4150
4151 @Override
4152 public void clearHistory() {
4153 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APPOPS,
4154 "clearHistory");
4155 // Must not hold the appops lock
4156 mHistoricalRegistry.clearHistory();
4157 }
4158
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07004159 private void removeUidsForUserLocked(int userHandle) {
4160 for (int i = mUidStates.size() - 1; i >= 0; --i) {
4161 final int uid = mUidStates.keyAt(i);
4162 if (UserHandle.getUserId(uid) == userHandle) {
4163 mUidStates.removeAt(i);
4164 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08004165 }
4166 }
4167
Jason Monk62062992014-05-06 09:55:28 -04004168 private void checkSystemUid(String function) {
4169 int uid = Binder.getCallingUid();
4170 if (uid != Process.SYSTEM_UID) {
4171 throw new SecurityException(function + " must by called by the system");
4172 }
4173 }
4174
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004175 private static String resolvePackageName(int uid, String packageName) {
Svet Ganov82f09bc2018-01-12 22:08:40 -08004176 if (uid == Process.ROOT_UID) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004177 return "root";
4178 } else if (uid == Process.SHELL_UID) {
4179 return "com.android.shell";
Svet Ganov82f09bc2018-01-12 22:08:40 -08004180 } else if (uid == Process.MEDIA_UID) {
4181 return "media";
4182 } else if (uid == Process.AUDIOSERVER_UID) {
4183 return "audioserver";
4184 } else if (uid == Process.CAMERASERVER_UID) {
4185 return "cameraserver";
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00004186 } else if (uid == Process.SYSTEM_UID && packageName == null) {
4187 return "android";
4188 }
4189 return packageName;
4190 }
4191
Svet Ganov82f09bc2018-01-12 22:08:40 -08004192 private static int resolveUid(String packageName) {
4193 if (packageName == null) {
4194 return -1;
4195 }
4196 switch (packageName) {
4197 case "root":
4198 return Process.ROOT_UID;
4199 case "shell":
4200 return Process.SHELL_UID;
4201 case "media":
4202 return Process.MEDIA_UID;
4203 case "audioserver":
4204 return Process.AUDIOSERVER_UID;
4205 case "cameraserver":
4206 return Process.CAMERASERVER_UID;
4207 }
4208 return -1;
4209 }
4210
Svet Ganov2af57082015-07-30 08:44:20 -07004211 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07004212 String[] packageNames = null;
Philip P. Moltmann159d98b2018-12-20 08:30:53 -08004213
4214 // Very early during boot the package manager is not yet or not yet fully started. At this
4215 // time there are no packages yet.
4216 if (AppGlobals.getPackageManager() != null) {
4217 try {
4218 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
4219 } catch (RemoteException e) {
4220 /* ignore - local call */
4221 }
Svet Ganov2af57082015-07-30 08:44:20 -07004222 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07004223 if (packageNames == null) {
4224 return EmptyArray.STRING;
4225 }
4226 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07004227 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004228
Svet Ganov8455ba22019-01-02 13:05:56 -08004229 private static void checkValidOpsOrNull(String[] opNames) {
4230 if (opNames != null) {
4231 for (String opName : opNames) {
4232 if (AppOpsManager.strOpToOp(opName) == AppOpsManager.OP_NONE) {
4233 throw new IllegalArgumentException("Unknown op: " + opName);
4234 }
4235 }
4236 }
4237 }
4238
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004239 private final class ClientRestrictionState implements DeathRecipient {
4240 private final IBinder token;
4241 SparseArray<boolean[]> perUserRestrictions;
4242 SparseArray<String[]> perUserExcludedPackages;
4243
4244 public ClientRestrictionState(IBinder token)
4245 throws RemoteException {
4246 token.linkToDeath(this, 0);
4247 this.token = token;
4248 }
4249
4250 public boolean setRestriction(int code, boolean restricted,
4251 String[] excludedPackages, int userId) {
4252 boolean changed = false;
4253
4254 if (perUserRestrictions == null && restricted) {
4255 perUserRestrictions = new SparseArray<>();
4256 }
4257
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004258 int[] users;
4259 if (userId == UserHandle.USER_ALL) {
4260 List<UserInfo> liveUsers = UserManager.get(mContext).getUsers(false);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004261
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004262 users = new int[liveUsers.size()];
4263 for (int i = 0; i < liveUsers.size(); i++) {
4264 users[i] = liveUsers.get(i).id;
4265 }
4266 } else {
4267 users = new int[]{userId};
4268 }
4269
4270 if (perUserRestrictions != null) {
4271 int numUsers = users.length;
4272
4273 for (int i = 0; i < numUsers; i++) {
4274 int thisUserId = users[i];
4275
4276 boolean[] userRestrictions = perUserRestrictions.get(thisUserId);
4277 if (userRestrictions == null && restricted) {
4278 userRestrictions = new boolean[AppOpsManager._NUM_OP];
4279 perUserRestrictions.put(thisUserId, userRestrictions);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004280 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004281 if (userRestrictions != null && userRestrictions[code] != restricted) {
4282 userRestrictions[code] = restricted;
4283 if (!restricted && isDefault(userRestrictions)) {
4284 perUserRestrictions.remove(thisUserId);
4285 userRestrictions = null;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004286 }
4287 changed = true;
4288 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07004289
4290 if (userRestrictions != null) {
4291 final boolean noExcludedPackages = ArrayUtils.isEmpty(excludedPackages);
4292 if (perUserExcludedPackages == null && !noExcludedPackages) {
4293 perUserExcludedPackages = new SparseArray<>();
4294 }
4295 if (perUserExcludedPackages != null && !Arrays.equals(excludedPackages,
4296 perUserExcludedPackages.get(thisUserId))) {
4297 if (noExcludedPackages) {
4298 perUserExcludedPackages.remove(thisUserId);
4299 if (perUserExcludedPackages.size() <= 0) {
4300 perUserExcludedPackages = null;
4301 }
4302 } else {
4303 perUserExcludedPackages.put(thisUserId, excludedPackages);
4304 }
4305 changed = true;
4306 }
4307 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004308 }
4309 }
4310
4311 return changed;
4312 }
4313
4314 public boolean hasRestriction(int restriction, String packageName, int userId) {
4315 if (perUserRestrictions == null) {
4316 return false;
4317 }
4318 boolean[] restrictions = perUserRestrictions.get(userId);
4319 if (restrictions == null) {
4320 return false;
4321 }
4322 if (!restrictions[restriction]) {
4323 return false;
4324 }
4325 if (perUserExcludedPackages == null) {
4326 return true;
4327 }
4328 String[] perUserExclusions = perUserExcludedPackages.get(userId);
4329 if (perUserExclusions == null) {
4330 return true;
4331 }
4332 return !ArrayUtils.contains(perUserExclusions, packageName);
4333 }
4334
4335 public void removeUser(int userId) {
4336 if (perUserExcludedPackages != null) {
4337 perUserExcludedPackages.remove(userId);
4338 if (perUserExcludedPackages.size() <= 0) {
4339 perUserExcludedPackages = null;
4340 }
4341 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07004342 if (perUserRestrictions != null) {
4343 perUserRestrictions.remove(userId);
4344 if (perUserRestrictions.size() <= 0) {
4345 perUserRestrictions = null;
4346 }
4347 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004348 }
4349
4350 public boolean isDefault() {
4351 return perUserRestrictions == null || perUserRestrictions.size() <= 0;
4352 }
4353
4354 @Override
4355 public void binderDied() {
4356 synchronized (AppOpsService.this) {
4357 mOpUserRestrictions.remove(token);
4358 if (perUserRestrictions == null) {
4359 return;
4360 }
4361 final int userCount = perUserRestrictions.size();
4362 for (int i = 0; i < userCount; i++) {
4363 final boolean[] restrictions = perUserRestrictions.valueAt(i);
4364 final int restrictionCount = restrictions.length;
4365 for (int j = 0; j < restrictionCount; j++) {
4366 if (restrictions[j]) {
4367 final int changedCode = j;
Svet Ganov3a95f832018-03-23 17:44:30 -07004368 mHandler.post(() -> notifyWatchersOfChange(changedCode, UID_ANY));
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004369 }
4370 }
4371 }
4372 destroy();
4373 }
4374 }
4375
4376 public void destroy() {
4377 token.unlinkToDeath(this, 0);
4378 }
4379
4380 private boolean isDefault(boolean[] array) {
4381 if (ArrayUtils.isEmpty(array)) {
4382 return true;
4383 }
4384 for (boolean value : array) {
4385 if (value) {
4386 return false;
4387 }
4388 }
4389 return true;
4390 }
4391 }
Dianne Hackbornd5254412018-05-11 18:02:58 -07004392
4393 private final class AppOpsManagerInternalImpl extends AppOpsManagerInternal {
4394 @Override public void setDeviceAndProfileOwners(SparseIntArray owners) {
4395 synchronized (AppOpsService.this) {
4396 mProfileOwners = owners;
4397 }
4398 }
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07004399
4400 @Override
Philip P. Moltmann159d98b2018-12-20 08:30:53 -08004401 public void setUidMode(int code, int uid, int mode) {
4402 AppOpsService.this.setUidMode(code, uid, mode);
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07004403 }
Dianne Hackbornd5254412018-05-11 18:02:58 -07004404 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004405}