blob: fa98da541e57925100df5cc2b38c4c9a511b268d [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
17package com.android.server;
18
Suprabh Shukla3017fe42018-11-08 19:00:01 -080019import static android.app.AppOpsManager.OP_PLAY_AUDIO;
Hai Zhang2b98fb32018-09-21 15:18:46 -070020import static android.app.AppOpsManager.UID_STATE_BACKGROUND;
21import static android.app.AppOpsManager.UID_STATE_CACHED;
22import static android.app.AppOpsManager.UID_STATE_FOREGROUND;
23import static android.app.AppOpsManager.UID_STATE_FOREGROUND_SERVICE;
24import static android.app.AppOpsManager.UID_STATE_LAST_NON_RESTRICTED;
25import static android.app.AppOpsManager.UID_STATE_PERSISTENT;
26import static android.app.AppOpsManager.UID_STATE_TOP;
27import static android.app.AppOpsManager._NUM_UID_STATE;
28
Philip P. Moltmanne683f192017-06-23 14:05:04 -070029import android.Manifest;
Svet Ganovad0a49b2018-10-29 10:07:08 -070030import android.annotation.NonNull;
31import android.annotation.Nullable;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070032import android.app.ActivityManager;
33import android.app.ActivityThread;
34import android.app.AppGlobals;
35import android.app.AppOpsManager;
Svet Ganovad0a49b2018-10-29 10:07:08 -070036import android.app.AppOpsManager.HistoricalOpEntry;
37import android.app.AppOpsManager.HistoricalPackageOps;
Dianne Hackbornd5254412018-05-11 18:02:58 -070038import android.app.AppOpsManagerInternal;
Svet Ganovd873ae62018-06-25 16:39:23 -070039import android.app.AppOpsManagerInternal.CheckOpsDelegate;
Suprabh Shukla3017fe42018-11-08 19:00:01 -080040import android.content.BroadcastReceiver;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070041import android.content.ContentResolver;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070042import android.content.Context;
Suprabh Shukla3017fe42018-11-08 19:00:01 -080043import android.content.Intent;
44import android.content.IntentFilter;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070045import android.content.pm.ApplicationInfo;
46import android.content.pm.IPackageManager;
47import android.content.pm.PackageManager;
48import android.content.pm.PackageManagerInternal;
Svet Ganovad0a49b2018-10-29 10:07:08 -070049import android.content.pm.ParceledListSlice;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070050import android.content.pm.UserInfo;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070051import android.database.ContentObserver;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070052import android.media.AudioAttributes;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070053import android.net.Uri;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070054import android.os.AsyncTask;
55import android.os.Binder;
56import android.os.Bundle;
57import android.os.Handler;
58import android.os.IBinder;
59import android.os.Process;
60import android.os.RemoteException;
61import android.os.ResultReceiver;
62import android.os.ServiceManager;
63import android.os.ShellCallback;
64import android.os.ShellCommand;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -070065import android.os.SystemClock;
Sudheer Shanka98cb3f02018-08-17 16:10:29 -070066import android.os.SystemProperties;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070067import android.os.UserHandle;
68import android.os.UserManager;
Sudheer Shanka98cb3f02018-08-17 16:10:29 -070069import android.os.storage.StorageManager;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070070import android.os.storage.StorageManagerInternal;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070071import android.provider.Settings;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070072import android.util.ArrayMap;
73import android.util.ArraySet;
74import android.util.AtomicFile;
Dianne Hackborn65a4f252018-05-08 17:30:48 -070075import android.util.KeyValueListParser;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070076import android.util.Slog;
77import android.util.SparseArray;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -070078import android.util.SparseBooleanArray;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070079import android.util.SparseIntArray;
80import android.util.TimeUtils;
81import android.util.Xml;
82
Todd Kennedy556efba2018-11-15 07:43:55 -080083import com.android.internal.annotations.GuardedBy;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070084import com.android.internal.annotations.VisibleForTesting;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -080085import com.android.internal.app.IAppOpsActiveCallback;
Philip P. Moltmanne683f192017-06-23 14:05:04 -070086import com.android.internal.app.IAppOpsCallback;
87import com.android.internal.app.IAppOpsService;
88import com.android.internal.os.Zygote;
89import com.android.internal.util.ArrayUtils;
90import com.android.internal.util.DumpUtils;
91import com.android.internal.util.FastXmlSerializer;
92import com.android.internal.util.Preconditions;
93import com.android.internal.util.XmlUtils;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -080094import com.android.internal.util.function.pooled.PooledLambda;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -050095
Philip P. Moltmanne683f192017-06-23 14:05:04 -070096import libcore.util.EmptyArray;
97
98import org.xmlpull.v1.XmlPullParser;
99import org.xmlpull.v1.XmlPullParserException;
100import org.xmlpull.v1.XmlSerializer;
101
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800102import java.io.File;
103import java.io.FileDescriptor;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800104import java.io.FileInputStream;
105import java.io.FileNotFoundException;
106import java.io.FileOutputStream;
107import java.io.IOException;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800108import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100109import java.nio.charset.StandardCharsets;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700110import java.text.SimpleDateFormat;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800111import java.util.ArrayList;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -0700112import java.util.Arrays;
Svetoslav215b44a2015-08-04 19:03:40 -0700113import java.util.Collections;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700114import java.util.Date;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800115import java.util.HashMap;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800116import java.util.Iterator;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800117import java.util.List;
Dianne Hackborn607b4142013-08-02 18:10:10 -0700118import java.util.Map;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800119
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800120public class AppOpsService extends IAppOpsService.Stub {
121 static final String TAG = "AppOps";
Dianne Hackborn35654b62013-01-14 17:38:02 -0800122 static final boolean DEBUG = false;
123
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700124 private static final int NO_VERSION = -1;
125 /** Increment by one every time and add the corresponding upgrade logic in
126 * {@link #upgradeLocked(int)} below. The first version was 1 */
127 private static final int CURRENT_VERSION = 1;
128
Dianne Hackborn35654b62013-01-14 17:38:02 -0800129 // Write at most every 30 minutes.
130 static final long WRITE_DELAY = DEBUG ? 1000 : 30*60*1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800131
Svet Ganov3a95f832018-03-23 17:44:30 -0700132 // Constant meaning that any UID should be matched when dispatching callbacks
133 private static final int UID_ANY = -2;
134
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700135 // Map from process states to the uid states we track.
136 private static final int[] PROCESS_STATE_TO_UID_STATE = new int[] {
137 UID_STATE_PERSISTENT, // ActivityManager.PROCESS_STATE_PERSISTENT
138 UID_STATE_PERSISTENT, // ActivityManager.PROCESS_STATE_PERSISTENT_UI
139 UID_STATE_TOP, // ActivityManager.PROCESS_STATE_TOP
140 UID_STATE_FOREGROUND_SERVICE, // ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
141 UID_STATE_FOREGROUND, // ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
142 UID_STATE_FOREGROUND, // ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND
143 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND
144 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_TRANSIENT_BACKGROUND
145 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_BACKUP
146 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_SERVICE
147 UID_STATE_BACKGROUND, // ActivityManager.PROCESS_STATE_RECEIVER
148 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_TOP_SLEEPING
149 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_HEAVY_WEIGHT
150 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_HOME
151 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_LAST_ACTIVITY
152 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY
153 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT
154 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_RECENT
155 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_CACHED_EMPTY
156 UID_STATE_CACHED, // ActivityManager.PROCESS_STATE_NONEXISTENT
157 };
158
159 static final String[] UID_STATE_NAMES = new String[] {
160 "pers ", // UID_STATE_PERSISTENT
161 "top ", // UID_STATE_TOP
162 "fgsvc", // UID_STATE_FOREGROUND_SERVICE
163 "fg ", // UID_STATE_FOREGROUND
164 "bg ", // UID_STATE_BACKGROUND
165 "cch ", // UID_STATE_CACHED
166 };
167
168 static final String[] UID_STATE_TIME_ATTRS = new String[] {
169 "tp", // UID_STATE_PERSISTENT
170 "tt", // UID_STATE_TOP
171 "tfs", // UID_STATE_FOREGROUND_SERVICE
172 "tf", // UID_STATE_FOREGROUND
173 "tb", // UID_STATE_BACKGROUND
174 "tc", // UID_STATE_CACHED
175 };
176
177 static final String[] UID_STATE_REJECT_ATTRS = new String[] {
178 "rp", // UID_STATE_PERSISTENT
179 "rt", // UID_STATE_TOP
180 "rfs", // UID_STATE_FOREGROUND_SERVICE
181 "rf", // UID_STATE_FOREGROUND
182 "rb", // UID_STATE_BACKGROUND
183 "rc", // UID_STATE_CACHED
184 };
185
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800186 Context mContext;
187 final AtomicFile mFile;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800188 final Handler mHandler;
189
Dianne Hackbornd5254412018-05-11 18:02:58 -0700190 private final AppOpsManagerInternalImpl mAppOpsManagerInternal
191 = new AppOpsManagerInternalImpl();
192
Dianne Hackborn35654b62013-01-14 17:38:02 -0800193 boolean mWriteScheduled;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800194 boolean mFastWriteScheduled;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800195 final Runnable mWriteRunner = new Runnable() {
196 public void run() {
197 synchronized (AppOpsService.this) {
198 mWriteScheduled = false;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800199 mFastWriteScheduled = false;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800200 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
201 @Override protected Void doInBackground(Void... params) {
202 writeState();
203 return null;
204 }
205 };
206 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
207 }
208 }
209 };
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800210
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700211 @VisibleForTesting
212 final SparseArray<UidState> mUidStates = new SparseArray<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800213
Dianne Hackborn9fb93502018-06-18 12:29:44 -0700214 long mLastRealtime;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700215
Ruben Brunk29931bc2016-03-11 00:24:26 -0800216 /*
217 * These are app op restrictions imposed per user from various parties.
Ruben Brunk29931bc2016-03-11 00:24:26 -0800218 */
Svetoslav Ganova8bbd762016-05-13 17:08:16 -0700219 private final ArrayMap<IBinder, ClientRestrictionState> mOpUserRestrictions = new ArrayMap<>();
Jason Monk62062992014-05-06 09:55:28 -0400220
Dianne Hackbornd5254412018-05-11 18:02:58 -0700221 SparseIntArray mProfileOwners;
222
Todd Kennedy556efba2018-11-15 07:43:55 -0800223 @GuardedBy("this")
Svet Ganovd873ae62018-06-25 16:39:23 -0700224 private CheckOpsDelegate mCheckOpsDelegate;
225
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700226 /**
227 * All times are in milliseconds. These constants are kept synchronized with the system
228 * global Settings. Any access to this class or its fields should be done while
229 * holding the AppOpsService lock.
230 */
231 private final class Constants extends ContentObserver {
232 // Key names stored in the settings value.
Dianne Hackborne93ab412018-05-14 17:52:30 -0700233 private static final String KEY_TOP_STATE_SETTLE_TIME = "top_state_settle_time";
234 private static final String KEY_FG_SERVICE_STATE_SETTLE_TIME
235 = "fg_service_state_settle_time";
236 private static final String KEY_BG_STATE_SETTLE_TIME = "bg_state_settle_time";
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700237
238 /**
Dianne Hackborne93ab412018-05-14 17:52:30 -0700239 * How long we want for a drop in uid state from top to settle before applying it.
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700240 * @see Settings.Global#APP_OPS_CONSTANTS
Dianne Hackborne93ab412018-05-14 17:52:30 -0700241 * @see #KEY_TOP_STATE_SETTLE_TIME
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700242 */
Dianne Hackborne93ab412018-05-14 17:52:30 -0700243 public long TOP_STATE_SETTLE_TIME;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700244
Dianne Hackborne93ab412018-05-14 17:52:30 -0700245 /**
246 * How long we want for a drop in uid state from foreground to settle before applying it.
247 * @see Settings.Global#APP_OPS_CONSTANTS
248 * @see #KEY_FG_SERVICE_STATE_SETTLE_TIME
249 */
250 public long FG_SERVICE_STATE_SETTLE_TIME;
251
252 /**
253 * How long we want for a drop in uid state from background to settle before applying it.
254 * @see Settings.Global#APP_OPS_CONSTANTS
255 * @see #KEY_BG_STATE_SETTLE_TIME
256 */
257 public long BG_STATE_SETTLE_TIME;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700258
259 private final KeyValueListParser mParser = new KeyValueListParser(',');
260 private ContentResolver mResolver;
261
262 public Constants(Handler handler) {
263 super(handler);
264 updateConstants();
265 }
266
267 public void startMonitoring(ContentResolver resolver) {
268 mResolver = resolver;
269 mResolver.registerContentObserver(
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700270 Settings.Global.getUriFor(Settings.Global.APP_OPS_CONSTANTS),
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700271 false, this);
272 updateConstants();
273 }
274
275 @Override
276 public void onChange(boolean selfChange, Uri uri) {
277 updateConstants();
278 }
279
280 private void updateConstants() {
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700281 String value = mResolver != null ? Settings.Global.getString(mResolver,
282 Settings.Global.APP_OPS_CONSTANTS) : "";
283
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700284 synchronized (AppOpsService.this) {
285 try {
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700286 mParser.setString(value);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700287 } catch (IllegalArgumentException e) {
288 // Failed to parse the settings string, log this and move on
289 // with defaults.
290 Slog.e(TAG, "Bad app ops settings", e);
291 }
Dianne Hackborne93ab412018-05-14 17:52:30 -0700292 TOP_STATE_SETTLE_TIME = mParser.getDurationMillis(
293 KEY_TOP_STATE_SETTLE_TIME, 30 * 1000L);
294 FG_SERVICE_STATE_SETTLE_TIME = mParser.getDurationMillis(
295 KEY_FG_SERVICE_STATE_SETTLE_TIME, 10 * 1000L);
296 BG_STATE_SETTLE_TIME = mParser.getDurationMillis(
297 KEY_BG_STATE_SETTLE_TIME, 1 * 1000L);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700298 }
299 }
300
301 void dump(PrintWriter pw) {
302 pw.println(" Settings:");
303
Dianne Hackborne93ab412018-05-14 17:52:30 -0700304 pw.print(" "); pw.print(KEY_TOP_STATE_SETTLE_TIME); pw.print("=");
305 TimeUtils.formatDuration(TOP_STATE_SETTLE_TIME, pw);
Dianne Hackbornb94d82f2018-05-16 17:03:01 -0700306 pw.println();
Dianne Hackborne93ab412018-05-14 17:52:30 -0700307 pw.print(" "); pw.print(KEY_FG_SERVICE_STATE_SETTLE_TIME); pw.print("=");
308 TimeUtils.formatDuration(FG_SERVICE_STATE_SETTLE_TIME, pw);
Dianne Hackbornb94d82f2018-05-16 17:03:01 -0700309 pw.println();
Dianne Hackborne93ab412018-05-14 17:52:30 -0700310 pw.print(" "); pw.print(KEY_BG_STATE_SETTLE_TIME); pw.print("=");
311 TimeUtils.formatDuration(BG_STATE_SETTLE_TIME, pw);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700312 pw.println();
313 }
314 }
315
316 private final Constants mConstants;
317
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700318 @VisibleForTesting
319 static final class UidState {
Svet Ganov2af57082015-07-30 08:44:20 -0700320 public final int uid;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700321
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700322 public int state = UID_STATE_CACHED;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700323 public int pendingState = UID_STATE_CACHED;
324 public long pendingStateCommitTime;
325
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700326 public int startNesting;
Svet Ganov2af57082015-07-30 08:44:20 -0700327 public ArrayMap<String, Ops> pkgOps;
328 public SparseIntArray opModes;
329
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700330 // true indicates there is an interested observer, false there isn't but it has such an op
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700331 public SparseBooleanArray foregroundOps;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700332 public boolean hasForegroundWatchers;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700333
Svet Ganov2af57082015-07-30 08:44:20 -0700334 public UidState(int uid) {
335 this.uid = uid;
336 }
337
338 public void clear() {
339 pkgOps = null;
340 opModes = null;
341 }
342
343 public boolean isDefault() {
344 return (pkgOps == null || pkgOps.isEmpty())
345 && (opModes == null || opModes.size() <= 0);
346 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700347
348 int evalMode(int mode) {
349 if (mode == AppOpsManager.MODE_FOREGROUND) {
Dianne Hackborne93ab412018-05-14 17:52:30 -0700350 return state <= UID_STATE_LAST_NON_RESTRICTED
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700351 ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED;
352 }
353 return mode;
354 }
355
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700356 private void evalForegroundWatchers(int op, SparseArray<ArraySet<ModeCallback>> watchers,
357 SparseBooleanArray which) {
358 boolean curValue = which.get(op, false);
359 ArraySet<ModeCallback> callbacks = watchers.get(op);
360 if (callbacks != null) {
361 for (int cbi = callbacks.size() - 1; !curValue && cbi >= 0; cbi--) {
362 if ((callbacks.valueAt(cbi).mFlags
363 & AppOpsManager.WATCH_FOREGROUND_CHANGES) != 0) {
364 hasForegroundWatchers = true;
365 curValue = true;
366 }
367 }
368 }
369 which.put(op, curValue);
370 }
371
372 public void evalForegroundOps(SparseArray<ArraySet<ModeCallback>> watchers) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700373 SparseBooleanArray which = null;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700374 hasForegroundWatchers = false;
375 if (opModes != null) {
376 for (int i = opModes.size() - 1; i >= 0; i--) {
377 if (opModes.valueAt(i) == AppOpsManager.MODE_FOREGROUND) {
378 if (which == null) {
379 which = new SparseBooleanArray();
380 }
381 evalForegroundWatchers(opModes.keyAt(i), watchers, which);
382 }
383 }
384 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700385 if (pkgOps != null) {
386 for (int i = pkgOps.size() - 1; i >= 0; i--) {
387 Ops ops = pkgOps.valueAt(i);
388 for (int j = ops.size() - 1; j >= 0; j--) {
389 if (ops.valueAt(j).mode == AppOpsManager.MODE_FOREGROUND) {
390 if (which == null) {
391 which = new SparseBooleanArray();
392 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700393 evalForegroundWatchers(ops.keyAt(j), watchers, which);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700394 }
395 }
396 }
397 }
398 foregroundOps = which;
399 }
Svet Ganov2af57082015-07-30 08:44:20 -0700400 }
401
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700402 final static class Ops extends SparseArray<Op> {
403 final String packageName;
404 final UidState uidState;
405 final boolean isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800406
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700407 Ops(String _packageName, UidState _uidState, boolean _isPrivileged) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800408 packageName = _packageName;
Svet Ganov2af57082015-07-30 08:44:20 -0700409 uidState = _uidState;
Jason Monk1c7c3192014-06-26 12:52:18 -0400410 isPrivileged = _isPrivileged;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800411 }
412 }
413
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700414 final static class Op {
415 final UidState uidState;
416 final int uid;
417 final String packageName;
418 final int op;
419 int proxyUid = -1;
420 String proxyPackageName;
421 int mode;
422 int duration;
423 long time[] = new long[_NUM_UID_STATE];
424 long rejectTime[] = new long[_NUM_UID_STATE];
425 int startNesting;
426 long startRealtime;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800427
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700428 Op(UidState _uidState, String _packageName, int _op) {
429 uidState = _uidState;
430 uid = _uidState.uid;
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700431 packageName = _packageName;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800432 op = _op;
David Braunf5d83192013-09-16 13:43:51 -0700433 mode = AppOpsManager.opToDefaultMode(op);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800434 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700435
436 boolean hasAnyTime() {
437 for (int i = 0; i < AppOpsManager._NUM_UID_STATE; i++) {
438 if (time[i] != 0) {
439 return true;
440 }
441 if (rejectTime[i] != 0) {
442 return true;
443 }
444 }
445 return false;
446 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700447
448 int getMode() {
449 return uidState.evalMode(mode);
450 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800451 }
452
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800453 final SparseArray<ArraySet<ModeCallback>> mOpModeWatchers = new SparseArray<>();
454 final ArrayMap<String, ArraySet<ModeCallback>> mPackageModeWatchers = new ArrayMap<>();
455 final ArrayMap<IBinder, ModeCallback> mModeWatchers = new ArrayMap<>();
456 final ArrayMap<IBinder, SparseArray<ActiveCallback>> mActiveWatchers = new ArrayMap<>();
Dianne Hackborn68d76552017-02-27 15:32:03 -0800457 final SparseArray<SparseArray<Restriction>> mAudioRestrictions = new SparseArray<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -0800458
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700459 final class ModeCallback implements DeathRecipient {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800460 final IAppOpsCallback mCallback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700461 final int mWatchingUid;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700462 final int mFlags;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700463 final int mCallingUid;
464 final int mCallingPid;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800465
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700466 ModeCallback(IAppOpsCallback callback, int watchingUid, int flags, int callingUid,
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700467 int callingPid) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800468 mCallback = callback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700469 mWatchingUid = watchingUid;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700470 mFlags = flags;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700471 mCallingUid = callingUid;
472 mCallingPid = callingPid;
Dianne Hackbornc2293022013-02-06 23:14:49 -0800473 try {
474 mCallback.asBinder().linkToDeath(this, 0);
475 } catch (RemoteException e) {
476 }
477 }
478
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700479 public boolean isWatchingUid(int uid) {
480 return uid == UID_ANY || mWatchingUid < 0 || mWatchingUid == uid;
481 }
482
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700483 @Override
484 public String toString() {
485 StringBuilder sb = new StringBuilder(128);
486 sb.append("ModeCallback{");
487 sb.append(Integer.toHexString(System.identityHashCode(this)));
488 sb.append(" watchinguid=");
489 UserHandle.formatUid(sb, mWatchingUid);
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700490 sb.append(" flags=0x");
491 sb.append(Integer.toHexString(mFlags));
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700492 sb.append(" from uid=");
493 UserHandle.formatUid(sb, mCallingUid);
494 sb.append(" pid=");
495 sb.append(mCallingPid);
496 sb.append('}');
497 return sb.toString();
498 }
499
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700500 void unlinkToDeath() {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800501 mCallback.asBinder().unlinkToDeath(this, 0);
502 }
503
504 @Override
505 public void binderDied() {
506 stopWatchingMode(mCallback);
507 }
508 }
509
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700510 final class ActiveCallback implements DeathRecipient {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800511 final IAppOpsActiveCallback mCallback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700512 final int mWatchingUid;
513 final int mCallingUid;
514 final int mCallingPid;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800515
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700516 ActiveCallback(IAppOpsActiveCallback callback, int watchingUid, int callingUid,
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700517 int callingPid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800518 mCallback = callback;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700519 mWatchingUid = watchingUid;
520 mCallingUid = callingUid;
521 mCallingPid = callingPid;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800522 try {
523 mCallback.asBinder().linkToDeath(this, 0);
524 } catch (RemoteException e) {
525 }
526 }
527
Dianne Hackborn3b563fc2018-04-16 17:17:14 -0700528 @Override
529 public String toString() {
530 StringBuilder sb = new StringBuilder(128);
531 sb.append("ActiveCallback{");
532 sb.append(Integer.toHexString(System.identityHashCode(this)));
533 sb.append(" watchinguid=");
534 UserHandle.formatUid(sb, mWatchingUid);
535 sb.append(" from uid=");
536 UserHandle.formatUid(sb, mCallingUid);
537 sb.append(" pid=");
538 sb.append(mCallingPid);
539 sb.append('}');
540 return sb.toString();
541 }
542
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700543 void destroy() {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800544 mCallback.asBinder().unlinkToDeath(this, 0);
545 }
546
547 @Override
548 public void binderDied() {
549 stopWatchingActive(mCallback);
550 }
551 }
552
Svet Ganova7a0db62018-02-27 20:08:01 -0800553 final ArrayMap<IBinder, ClientState> mClients = new ArrayMap<>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700554
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700555 final class ClientState extends Binder implements DeathRecipient {
Svet Ganovf7b47252018-02-26 11:11:27 -0800556 final ArrayList<Op> mStartedOps = new ArrayList<>();
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700557 final IBinder mAppToken;
558 final int mPid;
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700559
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700560 ClientState(IBinder appToken) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700561 mAppToken = appToken;
562 mPid = Binder.getCallingPid();
Svet Ganovf7b47252018-02-26 11:11:27 -0800563 // Watch only for remote processes dying
564 if (!(appToken instanceof Binder)) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700565 try {
566 mAppToken.linkToDeath(this, 0);
567 } catch (RemoteException e) {
Svet Ganovf7b47252018-02-26 11:11:27 -0800568 /* do nothing */
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700569 }
570 }
571 }
572
573 @Override
574 public String toString() {
575 return "ClientState{" +
576 "mAppToken=" + mAppToken +
Svet Ganovf7b47252018-02-26 11:11:27 -0800577 ", " + "pid=" + mPid +
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700578 '}';
579 }
580
581 @Override
582 public void binderDied() {
583 synchronized (AppOpsService.this) {
584 for (int i=mStartedOps.size()-1; i>=0; i--) {
Svet Ganova7a0db62018-02-27 20:08:01 -0800585 finishOperationLocked(mStartedOps.get(i), /*finishNested*/ true);
Dianne Hackborne98f5db2013-07-17 17:23:25 -0700586 }
587 mClients.remove(mAppToken);
588 }
589 }
590 }
591
Jeff Brown6f357d32014-01-15 20:40:55 -0800592 public AppOpsService(File storagePath, Handler handler) {
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600593 LockGuard.installLock(this, LockGuard.INDEX_APP_OPS);
Dianne Hackborne17b4452018-01-10 13:15:40 -0800594 mFile = new AtomicFile(storagePath, "appops");
Jeff Brown6f357d32014-01-15 20:40:55 -0800595 mHandler = handler;
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700596 mConstants = new Constants(mHandler);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800597 readState();
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800598 }
David Braunf5d83192013-09-16 13:43:51 -0700599
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800600 public void publish(Context context) {
601 mContext = context;
602 ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
Dianne Hackbornd5254412018-05-11 18:02:58 -0700603 LocalServices.addService(AppOpsManagerInternal.class, mAppOpsManagerInternal);
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800604 }
605
Dianne Hackborn514074f2013-02-11 10:52:46 -0800606 public void systemReady() {
Dianne Hackborn45c79b02018-05-11 09:46:13 -0700607 mConstants.startMonitoring(mContext.getContentResolver());
608
Dianne Hackborn514074f2013-02-11 10:52:46 -0800609 synchronized (this) {
610 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -0700611 for (int i = mUidStates.size() - 1; i >= 0; i--) {
612 UidState uidState = mUidStates.valueAt(i);
613
614 String[] packageNames = getPackagesForUid(uidState.uid);
615 if (ArrayUtils.isEmpty(packageNames)) {
616 uidState.clear();
617 mUidStates.removeAt(i);
618 changed = true;
619 continue;
620 }
621
622 ArrayMap<String, Ops> pkgs = uidState.pkgOps;
623 if (pkgs == null) {
624 continue;
625 }
626
Dianne Hackborn514074f2013-02-11 10:52:46 -0800627 Iterator<Ops> it = pkgs.values().iterator();
628 while (it.hasNext()) {
629 Ops ops = it.next();
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700630 int curUid = -1;
Dianne Hackborn514074f2013-02-11 10:52:46 -0800631 try {
Jeff Sharkeycd654482016-01-08 17:42:11 -0700632 curUid = AppGlobals.getPackageManager().getPackageUid(ops.packageName,
633 PackageManager.MATCH_UNINSTALLED_PACKAGES,
Svet Ganov2af57082015-07-30 08:44:20 -0700634 UserHandle.getUserId(ops.uidState.uid));
Jeff Sharkeye2ed23e2015-10-29 19:00:44 -0700635 } catch (RemoteException ignored) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800636 }
Svet Ganov2af57082015-07-30 08:44:20 -0700637 if (curUid != ops.uidState.uid) {
Dianne Hackborn514074f2013-02-11 10:52:46 -0800638 Slog.i(TAG, "Pruning old package " + ops.packageName
Svet Ganov2af57082015-07-30 08:44:20 -0700639 + "/" + ops.uidState + ": new uid=" + curUid);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800640 it.remove();
641 changed = true;
642 }
643 }
Svet Ganov2af57082015-07-30 08:44:20 -0700644
645 if (uidState.isDefault()) {
646 mUidStates.removeAt(i);
Dianne Hackborn514074f2013-02-11 10:52:46 -0800647 }
648 }
649 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800650 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800651 }
652 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700653
Suprabh Shukla3017fe42018-11-08 19:00:01 -0800654 final IntentFilter packageSuspendFilter = new IntentFilter();
655 packageSuspendFilter.addAction(Intent.ACTION_PACKAGES_UNSUSPENDED);
656 packageSuspendFilter.addAction(Intent.ACTION_PACKAGES_SUSPENDED);
657 mContext.registerReceiver(new BroadcastReceiver() {
658 @Override
659 public void onReceive(Context context, Intent intent) {
660 final int[] changedUids = intent.getIntArrayExtra(Intent.EXTRA_CHANGED_UID_LIST);
661 final String[] changedPkgs = intent.getStringArrayExtra(
662 Intent.EXTRA_CHANGED_PACKAGE_LIST);
663 final ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(OP_PLAY_AUDIO);
664 for (int i = 0; i < changedUids.length; i++) {
665 final int changedUid = changedUids[i];
666 final String changedPkg = changedPkgs[i];
667 // We trust packagemanager to insert matching uid and packageNames in the extras
668 mHandler.sendMessage(PooledLambda.obtainMessage(AppOpsService::notifyOpChanged,
669 AppOpsService.this, callbacks, OP_PLAY_AUDIO, changedUid, changedPkg));
670 }
671 }
672 }, packageSuspendFilter);
673
Suprabh Shuklaaef25132017-01-23 18:09:03 -0800674 PackageManagerInternal packageManagerInternal = LocalServices.getService(
675 PackageManagerInternal.class);
676 packageManagerInternal.setExternalSourcesPolicy(
677 new PackageManagerInternal.ExternalSourcesPolicy() {
678 @Override
679 public int getPackageTrustedToInstallApps(String packageName, int uid) {
680 int appOpMode = checkOperation(AppOpsManager.OP_REQUEST_INSTALL_PACKAGES,
681 uid, packageName);
682 switch (appOpMode) {
683 case AppOpsManager.MODE_ALLOWED:
684 return PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
685 case AppOpsManager.MODE_ERRORED:
686 return PackageManagerInternal.ExternalSourcesPolicy.USER_BLOCKED;
687 default:
688 return PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT;
689 }
690 }
691 });
692
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700693 if (!SystemProperties.getBoolean(StorageManager.PROP_ISOLATED_STORAGE, false)) {
694 StorageManagerInternal storageManagerInternal = LocalServices.getService(
695 StorageManagerInternal.class);
696 storageManagerInternal.addExternalStoragePolicy(
697 new StorageManagerInternal.ExternalStorageMountPolicy() {
698 @Override
699 public int getMountMode(int uid, String packageName) {
700 if (Process.isIsolated(uid)) {
701 return Zygote.MOUNT_EXTERNAL_NONE;
702 }
703 if (noteOperation(AppOpsManager.OP_READ_EXTERNAL_STORAGE, uid,
704 packageName) != AppOpsManager.MODE_ALLOWED) {
705 return Zygote.MOUNT_EXTERNAL_NONE;
706 }
707 if (noteOperation(AppOpsManager.OP_WRITE_EXTERNAL_STORAGE, uid,
708 packageName) != AppOpsManager.MODE_ALLOWED) {
709 return Zygote.MOUNT_EXTERNAL_READ;
710 }
711 return Zygote.MOUNT_EXTERNAL_WRITE;
Svet Ganov6ee871e2015-07-10 14:29:33 -0700712 }
Svet Ganov6ee871e2015-07-10 14:29:33 -0700713
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700714 @Override
715 public boolean hasExternalStorage(int uid, String packageName) {
716 final int mountMode = getMountMode(uid, packageName);
717 return mountMode == Zygote.MOUNT_EXTERNAL_READ
718 || mountMode == Zygote.MOUNT_EXTERNAL_WRITE;
719 }
720 });
721 }
Dianne Hackborn514074f2013-02-11 10:52:46 -0800722 }
723
724 public void packageRemoved(int uid, String packageName) {
725 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700726 UidState uidState = mUidStates.get(uid);
727 if (uidState == null) {
728 return;
729 }
730
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800731 Ops ops = null;
Svet Ganov2af57082015-07-30 08:44:20 -0700732
733 // Remove any package state if such.
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800734 if (uidState.pkgOps != null) {
735 ops = uidState.pkgOps.remove(packageName);
Svet Ganov2af57082015-07-30 08:44:20 -0700736 }
737
738 // If we just nuked the last package state check if the UID is valid.
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800739 if (ops != null && uidState.pkgOps.isEmpty()
Svet Ganov2af57082015-07-30 08:44:20 -0700740 && getPackagesForUid(uid).length <= 0) {
741 mUidStates.remove(uid);
742 }
743
Svet Ganova7a0db62018-02-27 20:08:01 -0800744 // Finish ops other packages started on behalf of the package.
745 final int clientCount = mClients.size();
746 for (int i = 0; i < clientCount; i++) {
747 final ClientState client = mClients.valueAt(i);
748 if (client.mStartedOps == null) {
749 continue;
750 }
751 final int opCount = client.mStartedOps.size();
752 for (int j = opCount - 1; j >= 0; j--) {
753 final Op op = client.mStartedOps.get(j);
754 if (uid == op.uid && packageName.equals(op.packageName)) {
755 finishOperationLocked(op, /*finishNested*/ true);
756 client.mStartedOps.remove(j);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700757 if (op.startNesting <= 0) {
Svet Ganova7a0db62018-02-27 20:08:01 -0800758 scheduleOpActiveChangedIfNeededLocked(op.op,
759 uid, packageName, false);
760 }
761 }
762 }
763 }
764
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800765 if (ops != null) {
Svet Ganov2af57082015-07-30 08:44:20 -0700766 scheduleFastWriteLocked();
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -0800767
768 final int opCount = ops.size();
769 for (int i = 0; i < opCount; i++) {
770 final Op op = ops.valueAt(i);
771 if (op.duration == -1) {
772 scheduleOpActiveChangedIfNeededLocked(
773 op.op, op.uid, op.packageName, false);
774 }
775 }
Dianne Hackborn514074f2013-02-11 10:52:46 -0800776 }
777 }
778 }
779
780 public void uidRemoved(int uid) {
781 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700782 if (mUidStates.indexOfKey(uid) >= 0) {
783 mUidStates.remove(uid);
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -0800784 scheduleFastWriteLocked();
Dianne Hackborn514074f2013-02-11 10:52:46 -0800785 }
786 }
787 }
788
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700789 public void updateUidProcState(int uid, int procState) {
790 synchronized (this) {
791 final UidState uidState = getUidStateLocked(uid, true);
792 final int newState = PROCESS_STATE_TO_UID_STATE[procState];
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700793 if (uidState != null && uidState.pendingState != newState) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700794 final int oldPendingState = uidState.pendingState;
795 uidState.pendingState = newState;
Dianne Hackborne93ab412018-05-14 17:52:30 -0700796 if (newState < uidState.state || newState <= UID_STATE_LAST_NON_RESTRICTED) {
797 // We are moving to a more important state, or the new state is in the
798 // foreground, then always do it immediately.
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700799 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700800 } else if (uidState.pendingStateCommitTime == 0) {
801 // We are moving to a less important state for the first time,
802 // delay the application for a bit.
Dianne Hackborne93ab412018-05-14 17:52:30 -0700803 final long settleTime;
804 if (uidState.state <= UID_STATE_TOP) {
805 settleTime = mConstants.TOP_STATE_SETTLE_TIME;
806 } else if (uidState.state <= UID_STATE_FOREGROUND_SERVICE) {
807 settleTime = mConstants.FG_SERVICE_STATE_SETTLE_TIME;
808 } else {
809 settleTime = mConstants.BG_STATE_SETTLE_TIME;
810 }
Dianne Hackborn9fb93502018-06-18 12:29:44 -0700811 uidState.pendingStateCommitTime = SystemClock.elapsedRealtime() + settleTime;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -0700812 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700813 if (uidState.startNesting != 0) {
814 // There is some actively running operation... need to find it
815 // and appropriately update its state.
816 final long now = System.currentTimeMillis();
817 for (int i = uidState.pkgOps.size() - 1; i >= 0; i--) {
818 final Ops ops = uidState.pkgOps.valueAt(i);
819 for (int j = ops.size() - 1; j >= 0; j--) {
820 final Op op = ops.valueAt(j);
821 if (op.startNesting > 0) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -0700822 op.time[oldPendingState] = now;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700823 op.time[newState] = now;
824 }
825 }
826 }
827 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700828 }
829 }
830 }
831
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800832 public void shutdown() {
833 Slog.w(TAG, "Writing app ops before shutdown...");
Dianne Hackborn35654b62013-01-14 17:38:02 -0800834 boolean doWrite = false;
835 synchronized (this) {
836 if (mWriteScheduled) {
837 mWriteScheduled = false;
838 doWrite = true;
839 }
840 }
841 if (doWrite) {
842 writeState();
843 }
844 }
845
Dianne Hackborn72e39832013-01-18 18:36:09 -0800846 private ArrayList<AppOpsManager.OpEntry> collectOps(Ops pkgOps, int[] ops) {
847 ArrayList<AppOpsManager.OpEntry> resOps = null;
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700848 final long elapsedNow = SystemClock.elapsedRealtime();
Dianne Hackborn72e39832013-01-18 18:36:09 -0800849 if (ops == null) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700850 resOps = new ArrayList<>();
Dianne Hackborn72e39832013-01-18 18:36:09 -0800851 for (int j=0; j<pkgOps.size(); j++) {
852 Op curOp = pkgOps.valueAt(j);
Amith Yamasania1ce9632018-05-28 20:50:48 -0700853 final boolean running = curOp.duration == -1;
854 long duration = running
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700855 ? (elapsedNow - curOp.startRealtime)
856 : curOp.duration;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800857 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Amith Yamasania1ce9632018-05-28 20:50:48 -0700858 curOp.rejectTime, (int) duration, running, curOp.proxyUid,
Svet Ganov99b60432015-06-27 13:15:22 -0700859 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800860 }
861 } else {
862 for (int j=0; j<ops.length; j++) {
863 Op curOp = pkgOps.get(ops[j]);
864 if (curOp != null) {
865 if (resOps == null) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700866 resOps = new ArrayList<>();
Dianne Hackborn72e39832013-01-18 18:36:09 -0800867 }
Amith Yamasania1ce9632018-05-28 20:50:48 -0700868 final boolean running = curOp.duration == -1;
869 final long duration = running
Dianne Hackborncd1f30b2018-04-23 17:38:09 -0700870 ? (elapsedNow - curOp.startRealtime)
871 : curOp.duration;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800872 resOps.add(new AppOpsManager.OpEntry(curOp.op, curOp.mode, curOp.time,
Amith Yamasania1ce9632018-05-28 20:50:48 -0700873 curOp.rejectTime, (int) duration, running, curOp.proxyUid,
Svet Ganov99b60432015-06-27 13:15:22 -0700874 curOp.proxyPackageName));
Dianne Hackborn72e39832013-01-18 18:36:09 -0800875 }
876 }
877 }
878 return resOps;
879 }
880
Dianne Hackbornc7214a32017-04-11 13:32:47 -0700881 private ArrayList<AppOpsManager.OpEntry> collectOps(SparseIntArray uidOps, int[] ops) {
882 ArrayList<AppOpsManager.OpEntry> resOps = null;
883 if (ops == null) {
884 resOps = new ArrayList<>();
885 for (int j=0; j<uidOps.size(); j++) {
886 resOps.add(new AppOpsManager.OpEntry(uidOps.keyAt(j), uidOps.valueAt(j),
887 0, 0, 0, -1, null));
888 }
889 } else {
890 for (int j=0; j<ops.length; j++) {
891 int index = uidOps.indexOfKey(ops[j]);
892 if (index >= 0) {
893 if (resOps == null) {
894 resOps = new ArrayList<>();
895 }
896 resOps.add(new AppOpsManager.OpEntry(uidOps.keyAt(index), uidOps.valueAt(index),
897 0, 0, 0, -1, null));
898 }
899 }
900 }
901 return resOps;
902 }
903
Dianne Hackborn35654b62013-01-14 17:38:02 -0800904 @Override
905 public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
906 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
907 Binder.getCallingPid(), Binder.getCallingUid(), null);
908 ArrayList<AppOpsManager.PackageOps> res = null;
909 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -0700910 final int uidStateCount = mUidStates.size();
911 for (int i = 0; i < uidStateCount; i++) {
912 UidState uidState = mUidStates.valueAt(i);
913 if (uidState.pkgOps == null || uidState.pkgOps.isEmpty()) {
914 continue;
915 }
916 ArrayMap<String, Ops> packages = uidState.pkgOps;
917 final int packageCount = packages.size();
918 for (int j = 0; j < packageCount; j++) {
919 Ops pkgOps = packages.valueAt(j);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800920 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800921 if (resOps != null) {
922 if (res == null) {
923 res = new ArrayList<AppOpsManager.PackageOps>();
924 }
925 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700926 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800927 res.add(resPackage);
928 }
929 }
930 }
931 }
932 return res;
933 }
934
935 @Override
Dianne Hackborn72e39832013-01-18 18:36:09 -0800936 public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName,
937 int[] ops) {
938 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
939 Binder.getCallingPid(), Binder.getCallingUid(), null);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +0000940 String resolvedPackageName = resolvePackageName(uid, packageName);
941 if (resolvedPackageName == null) {
942 return Collections.emptyList();
943 }
Dianne Hackborn72e39832013-01-18 18:36:09 -0800944 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -0700945 Ops pkgOps = getOpsRawLocked(uid, resolvedPackageName, false /* edit */,
946 false /* uidMismatchExpected */);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800947 if (pkgOps == null) {
948 return null;
949 }
950 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(pkgOps, ops);
951 if (resOps == null) {
952 return null;
953 }
954 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
955 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
Svet Ganov2af57082015-07-30 08:44:20 -0700956 pkgOps.packageName, pkgOps.uidState.uid, resOps);
Dianne Hackborn72e39832013-01-18 18:36:09 -0800957 res.add(resPackage);
958 return res;
959 }
960 }
961
Dianne Hackbornc7214a32017-04-11 13:32:47 -0700962 @Override
Svet Ganovad0a49b2018-10-29 10:07:08 -0700963 public @Nullable ParceledListSlice getAllHistoricalPackagesOps(@Nullable String[] opNames,
964 long beginTimeMillis, long endTimeMillis) {
965 Preconditions.checkArgument(beginTimeMillis >= 0 && beginTimeMillis < endTimeMillis,
966 "beginTimeMillis must be non negative and lesser than endTimeMillis");
967
968 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
969 Binder.getCallingPid(), Binder.getCallingUid(), "getAllHistoricalPackagesOps");
970
971 ArrayList<HistoricalPackageOps> historicalPackageOpsList = null;
972
973 final int uidStateCount = mUidStates.size();
974 for (int i = 0; i < uidStateCount; i++) {
975 final UidState uidState = mUidStates.valueAt(i);
976 if (uidState.pkgOps == null || uidState.pkgOps.isEmpty()) {
977 continue;
978 }
979 final ArrayMap<String, Ops> packages = uidState.pkgOps;
980 final int packageCount = packages.size();
981 for (int j = 0; j < packageCount; j++) {
982 final Ops pkgOps = packages.valueAt(j);
983 final AppOpsManager.HistoricalPackageOps historicalPackageOps =
984 createHistoricalPackageOps(uidState.uid, pkgOps, opNames,
985 beginTimeMillis, endTimeMillis);
986 if (historicalPackageOps != null) {
987 if (historicalPackageOpsList == null) {
988 historicalPackageOpsList = new ArrayList<>();
989 }
990 historicalPackageOpsList.add(historicalPackageOps);
991 }
992 }
993 }
994
995 if (historicalPackageOpsList == null) {
996 return null;
997 }
998
999 return new ParceledListSlice<>(historicalPackageOpsList);
1000 }
1001
1002 private static @Nullable HistoricalPackageOps createHistoricalPackageOps(int uid,
1003 @Nullable Ops pkgOps, @Nullable String[] opNames, long beginTimeMillis,
1004 long endTimeMillis) {
1005 // TODO: Implement historical data collection
1006 if (pkgOps == null) {
1007 return null;
1008 }
1009
1010 final HistoricalPackageOps historicalPackageOps = new HistoricalPackageOps(uid,
1011 pkgOps.packageName);
1012
1013 if (opNames == null) {
1014 opNames = AppOpsManager.getOpStrs();
1015 }
1016 for (String opName : opNames) {
1017 addHistoricOpEntry(AppOpsManager.strOpToOp(opName), pkgOps, historicalPackageOps);
1018 }
1019
1020 return historicalPackageOps;
1021 }
1022
1023 @Override
1024 public @Nullable HistoricalPackageOps getHistoricalPackagesOps(int uid,
1025 @NonNull String packageName, @Nullable String[] opNames,
1026 long beginTimeMillis, long endTimeMillis) {
1027 Preconditions.checkNotNull(packageName,
1028 "packageName cannot be null");
1029 Preconditions.checkArgument(beginTimeMillis >= 0 && beginTimeMillis < endTimeMillis,
1030 "beginTimeMillis must be non negative and lesser than endTimeMillis");
1031
1032 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
1033 Binder.getCallingPid(), Binder.getCallingUid(), "getHistoricalPackagesOps");
1034
1035 final String resolvedPackageName = resolvePackageName(uid, packageName);
1036 if (resolvedPackageName == null) {
1037 return null;
1038 }
1039
1040 // TODO: Implement historical data collection
1041 final Ops pkgOps = getOpsRawLocked(uid, resolvedPackageName, false /* edit */,
1042 false /* uidMismatchExpected */);
1043 return createHistoricalPackageOps(uid, pkgOps, opNames, beginTimeMillis, endTimeMillis);
1044 }
1045
1046 private static void addHistoricOpEntry(int opCode, @NonNull Ops ops,
1047 @NonNull HistoricalPackageOps outHistoricalPackageOps) {
1048 final Op op = ops.get(opCode);
1049 if (op == null) {
1050 return;
1051 }
1052
1053 final HistoricalOpEntry historicalOpEntry = new HistoricalOpEntry(opCode);
1054
1055 // TODO: Keep per UID state duration
1056 for (int uidState = 0; uidState < AppOpsManager._NUM_UID_STATE; uidState++) {
1057 final int acceptCount;
1058 final int rejectCount;
1059 if (op.rejectTime[uidState] == 0) {
1060 acceptCount = 1;
1061 rejectCount = 0;
1062 } else {
1063 acceptCount = 0;
1064 rejectCount = 1;
1065 }
1066 historicalOpEntry.addEntry(uidState, acceptCount, rejectCount, 0);
1067 }
1068
1069 outHistoricalPackageOps.addEntry(historicalOpEntry);
1070 }
1071
1072 @Override
Dianne Hackbornc7214a32017-04-11 13:32:47 -07001073 public List<AppOpsManager.PackageOps> getUidOps(int uid, int[] ops) {
1074 mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
1075 Binder.getCallingPid(), Binder.getCallingUid(), null);
1076 synchronized (this) {
1077 UidState uidState = getUidStateLocked(uid, false);
1078 if (uidState == null) {
1079 return null;
1080 }
1081 ArrayList<AppOpsManager.OpEntry> resOps = collectOps(uidState.opModes, ops);
1082 if (resOps == null) {
1083 return null;
1084 }
1085 ArrayList<AppOpsManager.PackageOps> res = new ArrayList<AppOpsManager.PackageOps>();
1086 AppOpsManager.PackageOps resPackage = new AppOpsManager.PackageOps(
1087 null, uidState.uid, resOps);
1088 res.add(resPackage);
1089 return res;
1090 }
1091 }
1092
Dianne Hackborn607b4142013-08-02 18:10:10 -07001093 private void pruneOp(Op op, int uid, String packageName) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001094 if (!op.hasAnyTime()) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001095 Ops ops = getOpsRawLocked(uid, packageName, false /* edit */,
1096 false /* uidMismatchExpected */);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001097 if (ops != null) {
1098 ops.remove(op.op);
1099 if (ops.size() <= 0) {
Svet Ganov2af57082015-07-30 08:44:20 -07001100 UidState uidState = ops.uidState;
1101 ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
Dianne Hackborn607b4142013-08-02 18:10:10 -07001102 if (pkgOps != null) {
1103 pkgOps.remove(ops.packageName);
Svet Ganov2af57082015-07-30 08:44:20 -07001104 if (pkgOps.isEmpty()) {
1105 uidState.pkgOps = null;
1106 }
1107 if (uidState.isDefault()) {
1108 mUidStates.remove(uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001109 }
1110 }
1111 }
1112 }
1113 }
1114 }
1115
Dianne Hackbornd5254412018-05-11 18:02:58 -07001116 void enforceManageAppOpsModes(int callingPid, int callingUid, int targetUid) {
1117 if (callingPid == Process.myPid()) {
1118 return;
1119 }
1120 final int callingUser = UserHandle.getUserId(callingUid);
1121 synchronized (this) {
1122 if (mProfileOwners != null && mProfileOwners.get(callingUser, -1) == callingUid) {
1123 if (targetUid >= 0 && callingUser == UserHandle.getUserId(targetUid)) {
1124 // Profile owners are allowed to change modes but only for apps
1125 // within their user.
1126 return;
1127 }
1128 }
1129 }
1130 mContext.enforcePermission(android.Manifest.permission.MANAGE_APP_OPS_MODES,
1131 Binder.getCallingPid(), Binder.getCallingUid(), null);
1132 }
1133
Dianne Hackborn72e39832013-01-18 18:36:09 -08001134 @Override
Svet Ganov2af57082015-07-30 08:44:20 -07001135 public void setUidMode(int code, int uid, int mode) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07001136 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
Svet Ganov2af57082015-07-30 08:44:20 -07001137 verifyIncomingOp(code);
1138 code = AppOpsManager.opToSwitch(code);
1139
1140 synchronized (this) {
1141 final int defaultMode = AppOpsManager.opToDefaultMode(code);
1142
1143 UidState uidState = getUidStateLocked(uid, false);
1144 if (uidState == null) {
1145 if (mode == defaultMode) {
1146 return;
1147 }
1148 uidState = new UidState(uid);
1149 uidState.opModes = new SparseIntArray();
1150 uidState.opModes.put(code, mode);
1151 mUidStates.put(uid, uidState);
1152 scheduleWriteLocked();
1153 } else if (uidState.opModes == null) {
1154 if (mode != defaultMode) {
1155 uidState.opModes = new SparseIntArray();
1156 uidState.opModes.put(code, mode);
1157 scheduleWriteLocked();
1158 }
1159 } else {
Hai Zhang2b98fb32018-09-21 15:18:46 -07001160 if (uidState.opModes.indexOfKey(code) >= 0 && uidState.opModes.get(code) == mode) {
Svet Ganov2af57082015-07-30 08:44:20 -07001161 return;
1162 }
1163 if (mode == defaultMode) {
1164 uidState.opModes.delete(code);
1165 if (uidState.opModes.size() <= 0) {
1166 uidState.opModes = null;
1167 }
1168 } else {
1169 uidState.opModes.put(code, mode);
1170 }
1171 scheduleWriteLocked();
1172 }
1173 }
1174
Svetoslav215b44a2015-08-04 19:03:40 -07001175 String[] uidPackageNames = getPackagesForUid(uid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001176 ArrayMap<ModeCallback, ArraySet<String>> callbackSpecs = null;
Svet Ganov2af57082015-07-30 08:44:20 -07001177
riddle_hsu40b300f2015-11-23 13:22:03 +08001178 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001179 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001180 if (callbacks != null) {
Svet Ganov2af57082015-07-30 08:44:20 -07001181 final int callbackCount = callbacks.size();
1182 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001183 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +08001184 ArraySet<String> changedPackages = new ArraySet<>();
1185 Collections.addAll(changedPackages, uidPackageNames);
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001186 if (callbackSpecs == null) {
1187 callbackSpecs = new ArrayMap<>();
1188 }
riddle_hsu40b300f2015-11-23 13:22:03 +08001189 callbackSpecs.put(callback, changedPackages);
1190 }
1191 }
1192
1193 for (String uidPackageName : uidPackageNames) {
1194 callbacks = mPackageModeWatchers.get(uidPackageName);
1195 if (callbacks != null) {
1196 if (callbackSpecs == null) {
1197 callbackSpecs = new ArrayMap<>();
Svet Ganov2af57082015-07-30 08:44:20 -07001198 }
riddle_hsu40b300f2015-11-23 13:22:03 +08001199 final int callbackCount = callbacks.size();
1200 for (int i = 0; i < callbackCount; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001201 ModeCallback callback = callbacks.valueAt(i);
riddle_hsu40b300f2015-11-23 13:22:03 +08001202 ArraySet<String> changedPackages = callbackSpecs.get(callback);
1203 if (changedPackages == null) {
1204 changedPackages = new ArraySet<>();
1205 callbackSpecs.put(callback, changedPackages);
1206 }
1207 changedPackages.add(uidPackageName);
1208 }
Svet Ganov2af57082015-07-30 08:44:20 -07001209 }
1210 }
1211 }
1212
1213 if (callbackSpecs == null) {
1214 return;
1215 }
1216
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001217 for (int i = 0; i < callbackSpecs.size(); i++) {
1218 final ModeCallback callback = callbackSpecs.keyAt(i);
1219 final ArraySet<String> reportedPackageNames = callbackSpecs.valueAt(i);
1220 if (reportedPackageNames == null) {
1221 mHandler.sendMessage(PooledLambda.obtainMessage(
1222 AppOpsService::notifyOpChanged,
1223 this, callback, code, uid, (String) null));
1224
1225 } else {
1226 final int reportedPackageCount = reportedPackageNames.size();
1227 for (int j = 0; j < reportedPackageCount; j++) {
1228 final String reportedPackageName = reportedPackageNames.valueAt(j);
1229 mHandler.sendMessage(PooledLambda.obtainMessage(
1230 AppOpsService::notifyOpChanged,
1231 this, callback, code, uid, reportedPackageName));
Svet Ganov2af57082015-07-30 08:44:20 -07001232 }
1233 }
Svet Ganov2af57082015-07-30 08:44:20 -07001234 }
1235 }
1236
1237 @Override
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001238 public void setMode(int code, int uid, String packageName, int mode) {
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07001239 setMode(code, uid, packageName, mode, true, false);
1240 }
1241
1242 /**
1243 * Sets the mode for a certain op and uid.
1244 *
1245 * @param code The op code to set
1246 * @param uid The UID for which to set
1247 * @param packageName The package for which to set
1248 * @param mode The new mode to set
1249 * @param verifyUid Iff {@code true}, check that the package name belongs to the uid
1250 * @param isPrivileged Whether the package is privileged. (Only used if {@code verifyUid ==
1251 * false})
1252 */
1253 private void setMode(int code, int uid, @NonNull String packageName, int mode,
1254 boolean verifyUid, boolean isPrivileged) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07001255 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001256 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001257 ArraySet<ModeCallback> repCbs = null;
Dianne Hackbornc2293022013-02-06 23:14:49 -08001258 code = AppOpsManager.opToSwitch(code);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001259 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -07001260 UidState uidState = getUidStateLocked(uid, false);
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07001261 Op op = getOpLocked(code, uid, packageName, true, verifyUid, isPrivileged);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001262 if (op != null) {
1263 if (op.mode != mode) {
1264 op.mode = mode;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001265 if (uidState != null) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001266 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001267 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001268 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(code);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001269 if (cbs != null) {
1270 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001271 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001272 }
1273 repCbs.addAll(cbs);
1274 }
1275 cbs = mPackageModeWatchers.get(packageName);
1276 if (cbs != null) {
1277 if (repCbs == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001278 repCbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001279 }
1280 repCbs.addAll(cbs);
1281 }
David Braunf5d83192013-09-16 13:43:51 -07001282 if (mode == AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborn514074f2013-02-11 10:52:46 -08001283 // If going into the default mode, prune this op
1284 // if there is nothing else interesting in it.
Dianne Hackborn607b4142013-08-02 18:10:10 -07001285 pruneOp(op, uid, packageName);
Dianne Hackborn514074f2013-02-11 10:52:46 -08001286 }
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001287 scheduleFastWriteLocked();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001288 }
1289 }
1290 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001291 if (repCbs != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001292 mHandler.sendMessage(PooledLambda.obtainMessage(
1293 AppOpsService::notifyOpChanged,
1294 this, repCbs, code, uid, packageName));
Dianne Hackbornc2293022013-02-06 23:14:49 -08001295 }
1296 }
1297
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001298 private void notifyOpChanged(ArraySet<ModeCallback> callbacks, int code,
1299 int uid, String packageName) {
1300 for (int i = 0; i < callbacks.size(); i++) {
1301 final ModeCallback callback = callbacks.valueAt(i);
1302 notifyOpChanged(callback, code, uid, packageName);
1303 }
1304 }
1305
1306 private void notifyOpChanged(ModeCallback callback, int code,
1307 int uid, String packageName) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001308 if (uid != UID_ANY && callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001309 return;
1310 }
1311 // There are components watching for mode changes such as window manager
1312 // and location manager which are in our process. The callbacks in these
1313 // components may require permissions our remote caller does not have.
1314 final long identity = Binder.clearCallingIdentity();
1315 try {
1316 callback.mCallback.opChanged(code, uid, packageName);
1317 } catch (RemoteException e) {
1318 /* ignore */
1319 } finally {
1320 Binder.restoreCallingIdentity(identity);
1321 }
1322 }
1323
1324 private static HashMap<ModeCallback, ArrayList<ChangeRec>> addCallbacks(
1325 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks,
1326 int op, int uid, String packageName, ArraySet<ModeCallback> cbs) {
Dianne Hackborn607b4142013-08-02 18:10:10 -07001327 if (cbs == null) {
1328 return callbacks;
1329 }
1330 if (callbacks == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001331 callbacks = new HashMap<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001332 }
Svet Ganov2af57082015-07-30 08:44:20 -07001333 boolean duplicate = false;
Dianne Hackborn68d76552017-02-27 15:32:03 -08001334 final int N = cbs.size();
1335 for (int i=0; i<N; i++) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001336 ModeCallback cb = cbs.valueAt(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001337 ArrayList<ChangeRec> reports = callbacks.get(cb);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001338 if (reports == null) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001339 reports = new ArrayList<>();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001340 callbacks.put(cb, reports);
Svet Ganov2af57082015-07-30 08:44:20 -07001341 } else {
1342 final int reportCount = reports.size();
1343 for (int j = 0; j < reportCount; j++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001344 ChangeRec report = reports.get(j);
1345 if (report.op == op && report.pkg.equals(packageName)) {
Svet Ganov2af57082015-07-30 08:44:20 -07001346 duplicate = true;
1347 break;
1348 }
1349 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001350 }
Svet Ganov2af57082015-07-30 08:44:20 -07001351 if (!duplicate) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001352 reports.add(new ChangeRec(op, uid, packageName));
Svet Ganov2af57082015-07-30 08:44:20 -07001353 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001354 }
1355 return callbacks;
1356 }
1357
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001358 static final class ChangeRec {
1359 final int op;
1360 final int uid;
1361 final String pkg;
1362
1363 ChangeRec(int _op, int _uid, String _pkg) {
1364 op = _op;
1365 uid = _uid;
1366 pkg = _pkg;
1367 }
1368 }
1369
Dianne Hackborn607b4142013-08-02 18:10:10 -07001370 @Override
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001371 public void resetAllModes(int reqUserId, String reqPackageName) {
1372 final int callingPid = Binder.getCallingPid();
1373 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001374 reqUserId = ActivityManager.handleIncomingUser(callingPid, callingUid, reqUserId,
1375 true, true, "resetAllModes", null);
Svet Ganov2af57082015-07-30 08:44:20 -07001376
1377 int reqUid = -1;
1378 if (reqPackageName != null) {
1379 try {
1380 reqUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -07001381 reqPackageName, PackageManager.MATCH_UNINSTALLED_PACKAGES, reqUserId);
Svet Ganov2af57082015-07-30 08:44:20 -07001382 } catch (RemoteException e) {
1383 /* ignore - local call */
1384 }
1385 }
1386
Dianne Hackbornd5254412018-05-11 18:02:58 -07001387 enforceManageAppOpsModes(callingPid, callingUid, reqUid);
1388
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001389 HashMap<ModeCallback, ArrayList<ChangeRec>> callbacks = null;
Dianne Hackborn607b4142013-08-02 18:10:10 -07001390 synchronized (this) {
1391 boolean changed = false;
Svet Ganov2af57082015-07-30 08:44:20 -07001392 for (int i = mUidStates.size() - 1; i >= 0; i--) {
1393 UidState uidState = mUidStates.valueAt(i);
1394
1395 SparseIntArray opModes = uidState.opModes;
1396 if (opModes != null && (uidState.uid == reqUid || reqUid == -1)) {
1397 final int uidOpCount = opModes.size();
1398 for (int j = uidOpCount - 1; j >= 0; j--) {
1399 final int code = opModes.keyAt(j);
1400 if (AppOpsManager.opAllowsReset(code)) {
1401 opModes.removeAt(j);
1402 if (opModes.size() <= 0) {
1403 uidState.opModes = null;
1404 }
1405 for (String packageName : getPackagesForUid(uidState.uid)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001406 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -07001407 mOpModeWatchers.get(code));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001408 callbacks = addCallbacks(callbacks, code, uidState.uid, packageName,
Svet Ganov2af57082015-07-30 08:44:20 -07001409 mPackageModeWatchers.get(packageName));
1410 }
1411 }
1412 }
1413 }
1414
1415 if (uidState.pkgOps == null) {
1416 continue;
1417 }
1418
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001419 if (reqUserId != UserHandle.USER_ALL
Svet Ganov2af57082015-07-30 08:44:20 -07001420 && reqUserId != UserHandle.getUserId(uidState.uid)) {
Alexandra Gherghinad6a98972014-08-04 17:05:34 +01001421 // Skip any ops for a different user
1422 continue;
1423 }
Svet Ganov2af57082015-07-30 08:44:20 -07001424
1425 Map<String, Ops> packages = uidState.pkgOps;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001426 Iterator<Map.Entry<String, Ops>> it = packages.entrySet().iterator();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001427 boolean uidChanged = false;
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001428 while (it.hasNext()) {
1429 Map.Entry<String, Ops> ent = it.next();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001430 String packageName = ent.getKey();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001431 if (reqPackageName != null && !reqPackageName.equals(packageName)) {
1432 // Skip any ops for a different package
1433 continue;
1434 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001435 Ops pkgOps = ent.getValue();
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001436 for (int j=pkgOps.size()-1; j>=0; j--) {
Dianne Hackborn607b4142013-08-02 18:10:10 -07001437 Op curOp = pkgOps.valueAt(j);
Dianne Hackborn8828d3a2013-09-25 16:47:10 -07001438 if (AppOpsManager.opAllowsReset(curOp.op)
1439 && curOp.mode != AppOpsManager.opToDefaultMode(curOp.op)) {
David Braunf5d83192013-09-16 13:43:51 -07001440 curOp.mode = AppOpsManager.opToDefaultMode(curOp.op);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001441 changed = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001442 uidChanged = true;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001443 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -07001444 mOpModeWatchers.get(curOp.op));
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001445 callbacks = addCallbacks(callbacks, curOp.op, curOp.uid, packageName,
Dianne Hackborn607b4142013-08-02 18:10:10 -07001446 mPackageModeWatchers.get(packageName));
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001447 if (!curOp.hasAnyTime()) {
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001448 pkgOps.removeAt(j);
1449 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001450 }
1451 }
Dianne Hackborn7f09ec32013-08-07 15:36:08 -07001452 if (pkgOps.size() == 0) {
1453 it.remove();
1454 }
1455 }
Svet Ganov2af57082015-07-30 08:44:20 -07001456 if (uidState.isDefault()) {
1457 mUidStates.remove(uidState.uid);
Dianne Hackborn607b4142013-08-02 18:10:10 -07001458 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001459 if (uidChanged) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001460 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001461 }
Dianne Hackborn607b4142013-08-02 18:10:10 -07001462 }
Svet Ganov2af57082015-07-30 08:44:20 -07001463
Dianne Hackborn607b4142013-08-02 18:10:10 -07001464 if (changed) {
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08001465 scheduleFastWriteLocked();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001466 }
1467 }
1468 if (callbacks != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001469 for (Map.Entry<ModeCallback, ArrayList<ChangeRec>> ent : callbacks.entrySet()) {
1470 ModeCallback cb = ent.getKey();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001471 ArrayList<ChangeRec> reports = ent.getValue();
Dianne Hackborn607b4142013-08-02 18:10:10 -07001472 for (int i=0; i<reports.size(); i++) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001473 ChangeRec rep = reports.get(i);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001474 mHandler.sendMessage(PooledLambda.obtainMessage(
1475 AppOpsService::notifyOpChanged,
1476 this, cb, rep.op, rep.uid, rep.pkg));
Dianne Hackborn607b4142013-08-02 18:10:10 -07001477 }
1478 }
1479 }
1480 }
1481
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001482 private void evalAllForegroundOpsLocked() {
1483 for (int uidi = mUidStates.size() - 1; uidi >= 0; uidi--) {
1484 final UidState uidState = mUidStates.valueAt(uidi);
1485 if (uidState.foregroundOps != null) {
1486 uidState.evalForegroundOps(mOpModeWatchers);
1487 }
1488 }
1489 }
1490
Dianne Hackbornc2293022013-02-06 23:14:49 -08001491 @Override
1492 public void startWatchingMode(int op, String packageName, IAppOpsCallback callback) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001493 startWatchingModeWithFlags(op, packageName, 0, callback);
1494 }
1495
1496 @Override
1497 public void startWatchingModeWithFlags(int op, String packageName, int flags,
1498 IAppOpsCallback callback) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001499 int watchedUid = -1;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001500 final int callingUid = Binder.getCallingUid();
1501 final int callingPid = Binder.getCallingPid();
Dianne Hackborn5376edd2018-06-05 13:21:16 -07001502 // TODO: should have a privileged permission to protect this.
1503 // Also, if the caller has requested WATCH_FOREGROUND_CHANGES, should we require
1504 // the USAGE_STATS permission since this can provide information about when an
1505 // app is in the foreground?
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001506 Preconditions.checkArgumentInRange(op, AppOpsManager.OP_NONE,
1507 AppOpsManager._NUM_OP - 1, "Invalid op code: " + op);
Svetoslav Ganov8de59712015-12-09 18:25:13 -08001508 if (callback == null) {
1509 return;
1510 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001511 synchronized (this) {
Svet Ganov2af57082015-07-30 08:44:20 -07001512 op = (op != AppOpsManager.OP_NONE) ? AppOpsManager.opToSwitch(op) : op;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001513 ModeCallback cb = mModeWatchers.get(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -08001514 if (cb == null) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001515 cb = new ModeCallback(callback, watchedUid, flags, callingUid, callingPid);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001516 mModeWatchers.put(callback.asBinder(), cb);
1517 }
1518 if (op != AppOpsManager.OP_NONE) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001519 ArraySet<ModeCallback> cbs = mOpModeWatchers.get(op);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001520 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08001521 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001522 mOpModeWatchers.put(op, cbs);
1523 }
1524 cbs.add(cb);
1525 }
1526 if (packageName != null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001527 ArraySet<ModeCallback> cbs = mPackageModeWatchers.get(packageName);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001528 if (cbs == null) {
Dianne Hackborn68d76552017-02-27 15:32:03 -08001529 cbs = new ArraySet<>();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001530 mPackageModeWatchers.put(packageName, cbs);
1531 }
1532 cbs.add(cb);
1533 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001534 evalAllForegroundOpsLocked();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001535 }
1536 }
1537
1538 @Override
1539 public void stopWatchingMode(IAppOpsCallback callback) {
Svetoslav Ganov8de59712015-12-09 18:25:13 -08001540 if (callback == null) {
1541 return;
1542 }
Dianne Hackbornc2293022013-02-06 23:14:49 -08001543 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001544 ModeCallback cb = mModeWatchers.remove(callback.asBinder());
Dianne Hackbornc2293022013-02-06 23:14:49 -08001545 if (cb != null) {
1546 cb.unlinkToDeath();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001547 for (int i=mOpModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001548 ArraySet<ModeCallback> cbs = mOpModeWatchers.valueAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001549 cbs.remove(cb);
1550 if (cbs.size() <= 0) {
1551 mOpModeWatchers.removeAt(i);
1552 }
1553 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001554 for (int i=mPackageModeWatchers.size()-1; i>=0; i--) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001555 ArraySet<ModeCallback> cbs = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001556 cbs.remove(cb);
1557 if (cbs.size() <= 0) {
1558 mPackageModeWatchers.removeAt(i);
Dianne Hackbornc2293022013-02-06 23:14:49 -08001559 }
1560 }
1561 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001562 evalAllForegroundOpsLocked();
Dianne Hackbornc2293022013-02-06 23:14:49 -08001563 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001564 }
1565
1566 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001567 public IBinder getToken(IBinder clientToken) {
1568 synchronized (this) {
1569 ClientState cs = mClients.get(clientToken);
1570 if (cs == null) {
1571 cs = new ClientState(clientToken);
1572 mClients.put(clientToken, cs);
1573 }
1574 return cs;
1575 }
1576 }
1577
Svet Ganovd873ae62018-06-25 16:39:23 -07001578 public CheckOpsDelegate getAppOpsServiceDelegate() {
1579 synchronized (this) {
1580 return mCheckOpsDelegate;
1581 }
1582 }
1583
1584 public void setAppOpsServiceDelegate(CheckOpsDelegate delegate) {
1585 synchronized (this) {
1586 mCheckOpsDelegate = delegate;
1587 }
1588 }
1589
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001590 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -08001591 public int checkOperation(int code, int uid, String packageName) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001592 final CheckOpsDelegate delegate;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001593 synchronized (this) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001594 delegate = mCheckOpsDelegate;
1595 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001596 if (delegate == null) {
1597 return checkOperationImpl(code, uid, packageName);
1598 }
Svet Ganovd873ae62018-06-25 16:39:23 -07001599 return delegate.checkOperation(code, uid, packageName,
1600 AppOpsService.this::checkOperationImpl);
1601 }
1602
1603 private int checkOperationImpl(int code, int uid, String packageName) {
Todd Kennedy556efba2018-11-15 07:43:55 -08001604 verifyIncomingUid(uid);
1605 verifyIncomingOp(code);
1606 String resolvedPackageName = resolvePackageName(uid, packageName);
1607 if (resolvedPackageName == null) {
1608 return AppOpsManager.MODE_IGNORED;
1609 }
1610 return checkOperationUnchecked(code, uid, resolvedPackageName);
1611 }
1612
1613 private int checkOperationUnchecked(int code, int uid, String packageName) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001614 synchronized (this) {
Todd Kennedy556efba2018-11-15 07:43:55 -08001615 if (isOpRestrictedLocked(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001616 return AppOpsManager.MODE_IGNORED;
1617 }
Svet Ganov2af57082015-07-30 08:44:20 -07001618 code = AppOpsManager.opToSwitch(code);
1619 UidState uidState = getUidStateLocked(uid, false);
Svet Ganovee438d42017-01-19 18:04:38 -08001620 if (uidState != null && uidState.opModes != null
1621 && uidState.opModes.indexOfKey(code) >= 0) {
1622 return uidState.opModes.get(code);
Svet Ganov2af57082015-07-30 08:44:20 -07001623 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001624 Op op = getOpLocked(code, uid, packageName, false, true, false);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001625 if (op == null) {
David Braunf5d83192013-09-16 13:43:51 -07001626 return AppOpsManager.opToDefaultMode(code);
Dianne Hackborn35654b62013-01-14 17:38:02 -08001627 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07001628 return op.mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001629 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001630 }
1631
1632 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001633 public int checkAudioOperation(int code, int usage, int uid, String packageName) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001634 final CheckOpsDelegate delegate;
John Spurlock1af30c72014-03-10 08:33:35 -04001635 synchronized (this) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001636 delegate = mCheckOpsDelegate;
1637 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001638 if (delegate == null) {
1639 return checkAudioOperationImpl(code, usage, uid, packageName);
1640 }
Svet Ganovd873ae62018-06-25 16:39:23 -07001641 return delegate.checkAudioOperation(code, usage, uid, packageName,
1642 AppOpsService.this::checkAudioOperationImpl);
1643 }
1644
1645 private int checkAudioOperationImpl(int code, int usage, int uid, String packageName) {
Todd Kennedy556efba2018-11-15 07:43:55 -08001646 boolean suspended;
1647 try {
1648 suspended = isPackageSuspendedForUser(packageName, uid);
1649 } catch (IllegalArgumentException ex) {
1650 // Package not found.
1651 suspended = false;
1652 }
1653
1654 if (suspended) {
1655 Slog.i(TAG, "Audio disabled for suspended package=" + packageName
1656 + " for uid=" + uid);
1657 return AppOpsManager.MODE_IGNORED;
1658 }
1659
Svet Ganovd873ae62018-06-25 16:39:23 -07001660 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001661 final int mode = checkRestrictionLocked(code, usage, uid, packageName);
John Spurlock1af30c72014-03-10 08:33:35 -04001662 if (mode != AppOpsManager.MODE_ALLOWED) {
1663 return mode;
1664 }
1665 }
1666 return checkOperation(code, uid, packageName);
1667 }
1668
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001669 private boolean isPackageSuspendedForUser(String pkg, int uid) {
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001670 try {
Andrei Stingaceanu355b2322016-02-12 16:43:51 +00001671 return AppGlobals.getPackageManager().isPackageSuspendedForUser(
1672 pkg, UserHandle.getUserId(uid));
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001673 } catch (RemoteException re) {
1674 throw new SecurityException("Could not talk to package manager service");
1675 }
Andrei Stingaceanu2bc2feb2016-02-11 16:23:49 +00001676 }
1677
John Spurlock7b414672014-07-18 13:02:39 -04001678 private int checkRestrictionLocked(int code, int usage, int uid, String packageName) {
1679 final SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1680 if (usageRestrictions != null) {
1681 final Restriction r = usageRestrictions.get(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001682 if (r != null && !r.exceptionPackages.contains(packageName)) {
1683 return r.mode;
1684 }
1685 }
1686 return AppOpsManager.MODE_ALLOWED;
1687 }
1688
1689 @Override
John Spurlock7b414672014-07-18 13:02:39 -04001690 public void setAudioRestriction(int code, int usage, int uid, int mode,
John Spurlock1af30c72014-03-10 08:33:35 -04001691 String[] exceptionPackages) {
Dianne Hackbornd5254412018-05-11 18:02:58 -07001692 enforceManageAppOpsModes(Binder.getCallingPid(), Binder.getCallingUid(), uid);
John Spurlock1af30c72014-03-10 08:33:35 -04001693 verifyIncomingUid(uid);
1694 verifyIncomingOp(code);
1695 synchronized (this) {
John Spurlock7b414672014-07-18 13:02:39 -04001696 SparseArray<Restriction> usageRestrictions = mAudioRestrictions.get(code);
1697 if (usageRestrictions == null) {
1698 usageRestrictions = new SparseArray<Restriction>();
1699 mAudioRestrictions.put(code, usageRestrictions);
John Spurlock1af30c72014-03-10 08:33:35 -04001700 }
John Spurlock7b414672014-07-18 13:02:39 -04001701 usageRestrictions.remove(usage);
John Spurlock1af30c72014-03-10 08:33:35 -04001702 if (mode != AppOpsManager.MODE_ALLOWED) {
1703 final Restriction r = new Restriction();
1704 r.mode = mode;
1705 if (exceptionPackages != null) {
1706 final int N = exceptionPackages.length;
1707 r.exceptionPackages = new ArraySet<String>(N);
1708 for (int i = 0; i < N; i++) {
1709 final String pkg = exceptionPackages[i];
1710 if (pkg != null) {
1711 r.exceptionPackages.add(pkg.trim());
1712 }
1713 }
1714 }
John Spurlock7b414672014-07-18 13:02:39 -04001715 usageRestrictions.put(usage, r);
John Spurlock1af30c72014-03-10 08:33:35 -04001716 }
1717 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001718
1719 mHandler.sendMessage(PooledLambda.obtainMessage(
Svet Ganov3a95f832018-03-23 17:44:30 -07001720 AppOpsService::notifyWatchersOfChange, this, code, UID_ANY));
John Spurlock1af30c72014-03-10 08:33:35 -04001721 }
1722
1723 @Override
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001724 public int checkPackage(int uid, String packageName) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001725 Preconditions.checkNotNull(packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001726 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07001727 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
1728 true /* uidMismatchExpected */);
1729 if (ops != null) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001730 return AppOpsManager.MODE_ALLOWED;
1731 } else {
1732 return AppOpsManager.MODE_ERRORED;
1733 }
1734 }
1735 }
1736
1737 @Override
Svet Ganovd873ae62018-06-25 16:39:23 -07001738 public int noteProxyOperation(int code, int proxyUid,
1739 String proxyPackageName, int proxiedUid, String proxiedPackageName) {
1740 verifyIncomingUid(proxyUid);
Svet Ganov99b60432015-06-27 13:15:22 -07001741 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001742 String resolveProxyPackageName = resolvePackageName(proxyUid, proxyPackageName);
1743 if (resolveProxyPackageName == null) {
1744 return AppOpsManager.MODE_IGNORED;
1745 }
1746 final int proxyMode = noteOperationUnchecked(code, proxyUid,
1747 resolveProxyPackageName, -1, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001748 if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
1749 return proxyMode;
1750 }
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001751 String resolveProxiedPackageName = resolvePackageName(proxiedUid, proxiedPackageName);
1752 if (resolveProxiedPackageName == null) {
1753 return AppOpsManager.MODE_IGNORED;
1754 }
1755 return noteOperationUnchecked(code, proxiedUid, resolveProxiedPackageName,
1756 proxyMode, resolveProxyPackageName);
Svet Ganov99b60432015-06-27 13:15:22 -07001757 }
1758
1759 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001760 public int noteOperation(int code, int uid, String packageName) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001761 final CheckOpsDelegate delegate;
1762 synchronized (this) {
Svet Ganovd873ae62018-06-25 16:39:23 -07001763 delegate = mCheckOpsDelegate;
1764 }
Todd Kennedy556efba2018-11-15 07:43:55 -08001765 if (delegate == null) {
1766 return noteOperationImpl(code, uid, packageName);
1767 }
Svet Ganovd873ae62018-06-25 16:39:23 -07001768 return delegate.noteOperation(code, uid, packageName,
1769 AppOpsService.this::noteOperationImpl);
1770 }
1771
1772 private int noteOperationImpl(int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001773 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001774 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001775 String resolvedPackageName = resolvePackageName(uid, packageName);
1776 if (resolvedPackageName == null) {
1777 return AppOpsManager.MODE_IGNORED;
1778 }
1779 return noteOperationUnchecked(code, uid, resolvedPackageName, 0, null);
Svet Ganov99b60432015-06-27 13:15:22 -07001780 }
1781
1782 private int noteOperationUnchecked(int code, int uid, String packageName,
1783 int proxyUid, String proxyPackageName) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001784 synchronized (this) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001785 final Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
Yohei Yukawaa965d652017-10-12 15:02:26 -07001786 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001787 if (ops == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001788 if (DEBUG) Slog.d(TAG, "noteOperation: no op for code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001789 + " package " + packageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001790 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001791 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001792 final Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07001793 if (isOpRestrictedLocked(uid, code, packageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001794 return AppOpsManager.MODE_IGNORED;
1795 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001796 final UidState uidState = ops.uidState;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001797 if (op.duration == -1) {
1798 Slog.w(TAG, "Noting op not finished: uid " + uid + " pkg " + packageName
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001799 + " code " + code + " time=" + op.time[uidState.state]
1800 + " duration=" + op.duration);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001801 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001802 op.duration = 0;
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001803 final int switchCode = AppOpsManager.opToSwitch(code);
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001804 // If there is a non-default per UID policy (we set UID op mode only if
1805 // non-default) it takes over, otherwise use the per package policy.
1806 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001807 final int uidMode = uidState.evalMode(uidState.opModes.get(switchCode));
Svet Ganov2af57082015-07-30 08:44:20 -07001808 if (uidMode != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001809 if (DEBUG) Slog.d(TAG, "noteOperation: uid reject #" + uidMode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07001810 + switchCode + " (" + code + ") uid " + uid + " package "
1811 + packageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001812 op.rejectTime[uidState.state] = System.currentTimeMillis();
Svet Ganov2af57082015-07-30 08:44:20 -07001813 return uidMode;
1814 }
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001815 } else {
1816 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001817 final int mode = switchOp.getMode();
1818 if (mode != AppOpsManager.MODE_ALLOWED) {
1819 if (DEBUG) Slog.d(TAG, "noteOperation: reject #" + mode + " for code "
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001820 + switchCode + " (" + code + ") uid " + uid + " package "
1821 + packageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001822 op.rejectTime[uidState.state] = System.currentTimeMillis();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001823 return mode;
Svetoslav Ganov1984bba2016-04-05 13:39:25 -07001824 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001825 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001826 if (DEBUG) Slog.d(TAG, "noteOperation: allowing code " + code + " uid " + uid
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001827 + " package " + packageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001828 op.time[uidState.state] = System.currentTimeMillis();
1829 op.rejectTime[uidState.state] = 0;
Svet Ganov99b60432015-06-27 13:15:22 -07001830 op.proxyUid = proxyUid;
1831 op.proxyPackageName = proxyPackageName;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001832 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001833 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001834 }
1835
1836 @Override
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001837 public void startWatchingActive(int[] ops, IAppOpsActiveCallback callback) {
Svet Ganovf7b47252018-02-26 11:11:27 -08001838 int watchedUid = -1;
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001839 final int callingUid = Binder.getCallingUid();
1840 final int callingPid = Binder.getCallingPid();
Svet Ganovf7b47252018-02-26 11:11:27 -08001841 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
1842 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001843 watchedUid = callingUid;
Svet Ganovf7b47252018-02-26 11:11:27 -08001844 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001845 if (ops != null) {
1846 Preconditions.checkArrayElementsInRange(ops, 0,
1847 AppOpsManager._NUM_OP - 1, "Invalid op code in: " + Arrays.toString(ops));
1848 }
1849 if (callback == null) {
1850 return;
1851 }
1852 synchronized (this) {
1853 SparseArray<ActiveCallback> callbacks = mActiveWatchers.get(callback.asBinder());
1854 if (callbacks == null) {
1855 callbacks = new SparseArray<>();
1856 mActiveWatchers.put(callback.asBinder(), callbacks);
1857 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07001858 final ActiveCallback activeCallback = new ActiveCallback(callback, watchedUid,
1859 callingUid, callingPid);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001860 for (int op : ops) {
1861 callbacks.put(op, activeCallback);
1862 }
1863 }
1864 }
1865
1866 @Override
1867 public void stopWatchingActive(IAppOpsActiveCallback callback) {
1868 if (callback == null) {
1869 return;
1870 }
1871 synchronized (this) {
1872 final SparseArray<ActiveCallback> activeCallbacks =
1873 mActiveWatchers.remove(callback.asBinder());
1874 if (activeCallbacks == null) {
1875 return;
1876 }
1877 final int callbackCount = activeCallbacks.size();
1878 for (int i = 0; i < callbackCount; i++) {
1879 // Apps ops are mapped to a singleton
1880 if (i == 0) {
1881 activeCallbacks.valueAt(i).destroy();
1882 }
1883 }
1884 }
1885 }
1886
1887 @Override
Svet Ganovf7b47252018-02-26 11:11:27 -08001888 public int startOperation(IBinder token, int code, int uid, String packageName,
1889 boolean startIfModeDefault) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001890 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001891 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001892 String resolvedPackageName = resolvePackageName(uid, packageName);
1893 if (resolvedPackageName == null) {
1894 return AppOpsManager.MODE_IGNORED;
1895 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001896 ClientState client = (ClientState)token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001897 synchronized (this) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001898 final Ops ops = getOpsRawLocked(uid, resolvedPackageName, true /* edit */,
Yohei Yukawaa965d652017-10-12 15:02:26 -07001899 false /* uidMismatchExpected */);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001900 if (ops == null) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001901 if (DEBUG) Slog.d(TAG, "startOperation: no op for code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001902 + " package " + resolvedPackageName);
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001903 return AppOpsManager.MODE_ERRORED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001904 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001905 final Op op = getOpLocked(ops, code, true);
Svet Ganov442ed572016-08-17 17:29:43 -07001906 if (isOpRestrictedLocked(uid, code, resolvedPackageName)) {
Jason Monk62062992014-05-06 09:55:28 -04001907 return AppOpsManager.MODE_IGNORED;
1908 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001909 final int switchCode = AppOpsManager.opToSwitch(code);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001910 final UidState uidState = ops.uidState;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001911 // If there is a non-default per UID policy (we set UID op mode only if
1912 // non-default) it takes over, otherwise use the per package policy.
1913 if (uidState.opModes != null && uidState.opModes.indexOfKey(switchCode) >= 0) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001914 final int uidMode = uidState.evalMode(uidState.opModes.get(switchCode));
Svet Ganovf7b47252018-02-26 11:11:27 -08001915 if (uidMode != AppOpsManager.MODE_ALLOWED
1916 && (!startIfModeDefault || uidMode != AppOpsManager.MODE_DEFAULT)) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001917 if (DEBUG) Slog.d(TAG, "noteOperation: uid reject #" + uidMode + " for code "
Svet Ganov2af57082015-07-30 08:44:20 -07001918 + switchCode + " (" + code + ") uid " + uid + " package "
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001919 + resolvedPackageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001920 op.rejectTime[uidState.state] = System.currentTimeMillis();
Svet Ganov2af57082015-07-30 08:44:20 -07001921 return uidMode;
1922 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001923 } else {
1924 final Op switchOp = switchCode != code ? getOpLocked(ops, switchCode, true) : op;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001925 final int mode = switchOp.getMode();
1926 if (mode != AppOpsManager.MODE_ALLOWED
1927 && (!startIfModeDefault || mode != AppOpsManager.MODE_DEFAULT)) {
1928 if (DEBUG) Slog.d(TAG, "startOperation: reject #" + mode + " for code "
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001929 + switchCode + " (" + code + ") uid " + uid + " package "
1930 + resolvedPackageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001931 op.rejectTime[uidState.state] = System.currentTimeMillis();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07001932 return mode;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001933 }
Svet Ganov2af57082015-07-30 08:44:20 -07001934 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001935 if (DEBUG) Slog.d(TAG, "startOperation: allowing code " + code + " uid " + uid
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001936 + " package " + resolvedPackageName);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001937 if (op.startNesting == 0) {
1938 op.startRealtime = SystemClock.elapsedRealtime();
1939 op.time[uidState.state] = System.currentTimeMillis();
1940 op.rejectTime[uidState.state] = 0;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001941 op.duration = -1;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001942 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, true);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001943 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001944 op.startNesting++;
1945 uidState.startNesting++;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001946 if (client.mStartedOps != null) {
1947 client.mStartedOps.add(op);
1948 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001949 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001950
1951 return AppOpsManager.MODE_ALLOWED;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001952 }
1953
1954 @Override
Dianne Hackborne98f5db2013-07-17 17:23:25 -07001955 public void finishOperation(IBinder token, int code, int uid, String packageName) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001956 verifyIncomingUid(uid);
Dianne Hackborn961321f2013-02-05 17:22:41 -08001957 verifyIncomingOp(code);
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00001958 String resolvedPackageName = resolvePackageName(uid, packageName);
1959 if (resolvedPackageName == null) {
1960 return;
1961 }
1962 if (!(token instanceof ClientState)) {
1963 return;
1964 }
1965 ClientState client = (ClientState) token;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001966 synchronized (this) {
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07001967 Op op = getOpLocked(code, uid, resolvedPackageName, true, true, false);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001968 if (op == null) {
1969 return;
1970 }
Svet Ganovf7b47252018-02-26 11:11:27 -08001971 if (!client.mStartedOps.remove(op)) {
Svet Ganovf5d5af12018-03-18 11:51:17 -07001972 // We finish ops when packages get removed to guarantee no dangling
1973 // started ops. However, some part of the system may asynchronously
1974 // finish ops for an already gone package. Hence, finishing an op
1975 // for a non existing package is fine and we don't log as a wtf.
1976 final long identity = Binder.clearCallingIdentity();
1977 try {
1978 if (LocalServices.getService(PackageManagerInternal.class).getPackageUid(
1979 resolvedPackageName, 0, UserHandle.getUserId(uid)) < 0) {
1980 Slog.i(TAG, "Finishing op=" + AppOpsManager.opToName(code)
1981 + " for non-existing package=" + resolvedPackageName
1982 + " in uid=" + uid);
1983 return;
1984 }
1985 } finally {
1986 Binder.restoreCallingIdentity(identity);
1987 }
1988 Slog.wtf(TAG, "Operation not started: uid=" + op.uid + " pkg="
1989 + op.packageName + " op=" + AppOpsManager.opToName(op.op));
Svet Ganov31d83ae2018-03-15 10:45:56 -07001990 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001991 }
Svet Ganova7a0db62018-02-27 20:08:01 -08001992 finishOperationLocked(op, /*finishNested*/ false);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07001993 if (op.startNesting <= 0) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08001994 scheduleOpActiveChangedIfNeededLocked(code, uid, packageName, false);
1995 }
1996 }
1997 }
1998
1999 private void scheduleOpActiveChangedIfNeededLocked(int code, int uid, String packageName,
2000 boolean active) {
2001 ArraySet<ActiveCallback> dispatchedCallbacks = null;
2002 final int callbackListCount = mActiveWatchers.size();
2003 for (int i = 0; i < callbackListCount; i++) {
2004 final SparseArray<ActiveCallback> callbacks = mActiveWatchers.valueAt(i);
2005 ActiveCallback callback = callbacks.get(code);
2006 if (callback != null) {
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07002007 if (callback.mWatchingUid >= 0 && callback.mWatchingUid != uid) {
Svet Ganovf7b47252018-02-26 11:11:27 -08002008 continue;
2009 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08002010 if (dispatchedCallbacks == null) {
2011 dispatchedCallbacks = new ArraySet<>();
2012 }
2013 dispatchedCallbacks.add(callback);
2014 }
2015 }
2016 if (dispatchedCallbacks == null) {
2017 return;
2018 }
2019 mHandler.sendMessage(PooledLambda.obtainMessage(
2020 AppOpsService::notifyOpActiveChanged,
2021 this, dispatchedCallbacks, code, uid, packageName, active));
2022 }
2023
2024 private void notifyOpActiveChanged(ArraySet<ActiveCallback> callbacks,
2025 int code, int uid, String packageName, boolean active) {
2026 // There are components watching for mode changes such as window manager
2027 // and location manager which are in our process. The callbacks in these
2028 // components may require permissions our remote caller does not have.
2029 final long identity = Binder.clearCallingIdentity();
2030 try {
2031 final int callbackCount = callbacks.size();
2032 for (int i = 0; i < callbackCount; i++) {
2033 final ActiveCallback callback = callbacks.valueAt(i);
2034 try {
2035 callback.mCallback.opActiveChanged(code, uid, packageName, active);
2036 } catch (RemoteException e) {
2037 /* do nothing */
2038 }
2039 }
2040 } finally {
2041 Binder.restoreCallingIdentity(identity);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002042 }
2043 }
2044
Svet Ganovb9d71a62015-04-30 10:38:13 -07002045 @Override
2046 public int permissionToOpCode(String permission) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00002047 if (permission == null) {
2048 return AppOpsManager.OP_NONE;
2049 }
Svet Ganovb9d71a62015-04-30 10:38:13 -07002050 return AppOpsManager.permissionToOpCode(permission);
2051 }
2052
Svet Ganova7a0db62018-02-27 20:08:01 -08002053 void finishOperationLocked(Op op, boolean finishNested) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002054 if (op.startNesting <= 1 || finishNested) {
2055 if (op.startNesting == 1 || finishNested) {
2056 op.duration = (int)(SystemClock.elapsedRealtime() - op.startRealtime);
2057 op.time[op.uidState.state] = System.currentTimeMillis();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002058 } else {
2059 Slog.w(TAG, "Finishing op nesting under-run: uid " + op.uid + " pkg "
2060 + op.packageName + " code " + op.op + " time=" + op.time
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002061 + " duration=" + op.duration + " nesting=" + op.startNesting);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002062 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002063 if (op.startNesting >= 1) {
2064 op.uidState.startNesting -= op.startNesting;
2065 }
2066 op.startNesting = 0;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07002067 } else {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002068 op.startNesting--;
2069 op.uidState.startNesting--;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002070 }
2071 }
2072
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002073 private void verifyIncomingUid(int uid) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002074 if (uid == Binder.getCallingUid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002075 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002076 }
2077 if (Binder.getCallingPid() == Process.myPid()) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002078 return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002079 }
2080 mContext.enforcePermission(android.Manifest.permission.UPDATE_APP_OPS_STATS,
2081 Binder.getCallingPid(), Binder.getCallingUid(), null);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002082 }
2083
Dianne Hackborn961321f2013-02-05 17:22:41 -08002084 private void verifyIncomingOp(int op) {
2085 if (op >= 0 && op < AppOpsManager._NUM_OP) {
2086 return;
2087 }
2088 throw new IllegalArgumentException("Bad operation #" + op);
2089 }
2090
Svet Ganov2af57082015-07-30 08:44:20 -07002091 private UidState getUidStateLocked(int uid, boolean edit) {
2092 UidState uidState = mUidStates.get(uid);
2093 if (uidState == null) {
2094 if (!edit) {
2095 return null;
2096 }
2097 uidState = new UidState(uid);
2098 mUidStates.put(uid, uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002099 } else {
2100 if (uidState.pendingStateCommitTime != 0) {
Dianne Hackborn9fb93502018-06-18 12:29:44 -07002101 if (uidState.pendingStateCommitTime < mLastRealtime) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002102 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002103 } else {
Dianne Hackborn9fb93502018-06-18 12:29:44 -07002104 mLastRealtime = SystemClock.elapsedRealtime();
2105 if (uidState.pendingStateCommitTime < mLastRealtime) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002106 commitUidPendingStateLocked(uidState);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002107 }
2108 }
2109 }
Svet Ganov2af57082015-07-30 08:44:20 -07002110 }
2111 return uidState;
2112 }
2113
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002114 private void commitUidPendingStateLocked(UidState uidState) {
Dianne Hackborne93ab412018-05-14 17:52:30 -07002115 final boolean lastForeground = uidState.state <= UID_STATE_LAST_NON_RESTRICTED;
2116 final boolean nowForeground = uidState.pendingState <= UID_STATE_LAST_NON_RESTRICTED;
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002117 uidState.state = uidState.pendingState;
2118 uidState.pendingStateCommitTime = 0;
Dianne Hackborne93ab412018-05-14 17:52:30 -07002119 if (uidState.hasForegroundWatchers && lastForeground != nowForeground) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002120 for (int fgi = uidState.foregroundOps.size() - 1; fgi >= 0; fgi--) {
2121 if (!uidState.foregroundOps.valueAt(fgi)) {
2122 continue;
2123 }
2124 final int code = uidState.foregroundOps.keyAt(fgi);
2125
2126 final ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
2127 if (callbacks != null) {
2128 for (int cbi = callbacks.size() - 1; cbi >= 0; cbi--) {
2129 final ModeCallback callback = callbacks.valueAt(cbi);
2130 if ((callback.mFlags & AppOpsManager.WATCH_FOREGROUND_CHANGES) == 0
2131 || !callback.isWatchingUid(uidState.uid)) {
2132 continue;
2133 }
2134 boolean doAllPackages = uidState.opModes != null
Hai Zhang2b98fb32018-09-21 15:18:46 -07002135 && uidState.opModes.indexOfKey(code) >= 0
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002136 && uidState.opModes.get(code) == AppOpsManager.MODE_FOREGROUND;
2137 if (uidState.pkgOps != null) {
2138 for (int pkgi = uidState.pkgOps.size() - 1; pkgi >= 0; pkgi--) {
2139 final Op op = uidState.pkgOps.valueAt(pkgi).get(code);
2140 if (doAllPackages || (op != null
2141 && op.mode == AppOpsManager.MODE_FOREGROUND)) {
2142 mHandler.sendMessage(PooledLambda.obtainMessage(
2143 AppOpsService::notifyOpChanged,
2144 this, callback, code, uidState.uid,
2145 uidState.pkgOps.keyAt(pkgi)));
2146 }
2147 }
2148 }
2149 }
2150 }
2151 }
2152 }
2153 }
2154
Yohei Yukawaa965d652017-10-12 15:02:26 -07002155 private Ops getOpsRawLocked(int uid, String packageName, boolean edit,
2156 boolean uidMismatchExpected) {
Svet Ganov2af57082015-07-30 08:44:20 -07002157 UidState uidState = getUidStateLocked(uid, edit);
2158 if (uidState == null) {
2159 return null;
2160 }
2161
2162 if (uidState.pkgOps == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002163 if (!edit) {
2164 return null;
2165 }
Svet Ganov2af57082015-07-30 08:44:20 -07002166 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002167 }
Svet Ganov2af57082015-07-30 08:44:20 -07002168
2169 Ops ops = uidState.pkgOps.get(packageName);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002170 if (ops == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002171 if (!edit) {
2172 return null;
2173 }
Jason Monk1c7c3192014-06-26 12:52:18 -04002174 boolean isPrivileged = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002175 // This is the first time we have seen this package name under this uid,
2176 // so let's make sure it is valid.
Dianne Hackborn514074f2013-02-11 10:52:46 -08002177 if (uid != 0) {
2178 final long ident = Binder.clearCallingIdentity();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002179 try {
Dianne Hackborn514074f2013-02-11 10:52:46 -08002180 int pkgUid = -1;
2181 try {
Jason Monk1c7c3192014-06-26 12:52:18 -04002182 ApplicationInfo appInfo = ActivityThread.getPackageManager()
Jeff Sharkeycd654482016-01-08 17:42:11 -07002183 .getApplicationInfo(packageName,
Svet Ganovad0a49b2018-10-29 10:07:08 -07002184 PackageManager.MATCH_DIRECT_BOOT_AWARE
2185 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkeycd654482016-01-08 17:42:11 -07002186 UserHandle.getUserId(uid));
Jason Monk1c7c3192014-06-26 12:52:18 -04002187 if (appInfo != null) {
2188 pkgUid = appInfo.uid;
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002189 isPrivileged = (appInfo.privateFlags
2190 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04002191 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08002192 pkgUid = resolveUid(packageName);
2193 if (pkgUid >= 0) {
Chien-Yu Chen75cade02016-01-11 10:56:21 -08002194 isPrivileged = false;
Jason Monk1c7c3192014-06-26 12:52:18 -04002195 }
Dianne Hackborn713df152013-05-17 11:27:57 -07002196 }
Jason Monk1c7c3192014-06-26 12:52:18 -04002197 } catch (RemoteException e) {
2198 Slog.w(TAG, "Could not contact PackageManager", e);
Dianne Hackborn514074f2013-02-11 10:52:46 -08002199 }
2200 if (pkgUid != uid) {
2201 // Oops! The package name is not valid for the uid they are calling
2202 // under. Abort.
Yohei Yukawaa965d652017-10-12 15:02:26 -07002203 if (!uidMismatchExpected) {
2204 RuntimeException ex = new RuntimeException("here");
2205 ex.fillInStackTrace();
2206 Slog.w(TAG, "Bad call: specified package " + packageName
2207 + " under uid " + uid + " but it is really " + pkgUid, ex);
2208 }
Dianne Hackborn514074f2013-02-11 10:52:46 -08002209 return null;
2210 }
2211 } finally {
2212 Binder.restoreCallingIdentity(ident);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002213 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002214 }
Svet Ganov2af57082015-07-30 08:44:20 -07002215 ops = new Ops(packageName, uidState, isPrivileged);
2216 uidState.pkgOps.put(packageName, ops);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002217 }
Dianne Hackborn72e39832013-01-18 18:36:09 -08002218 return ops;
2219 }
2220
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07002221 /**
2222 * Get the state of all ops for a package, <b>don't verify that package belongs to uid</b>.
2223 *
2224 * <p>Usually callers should use {@link #getOpLocked} and not call this directly.
2225 *
2226 * @param uid The uid the of the package
2227 * @param packageName The package name for which to get the state for
2228 * @param edit Iff {@code true} create the {@link Ops} object if not yet created
2229 * @param isPrivileged Whether the package is privileged or not
2230 *
2231 * @return The {@link Ops state} of all ops for the package
2232 */
2233 private @Nullable Ops getOpsRawNoVerifyLocked(int uid, @NonNull String packageName,
2234 boolean edit, boolean isPrivileged) {
2235 UidState uidState = getUidStateLocked(uid, edit);
2236 if (uidState == null) {
2237 return null;
2238 }
2239
2240 if (uidState.pkgOps == null) {
2241 if (!edit) {
2242 return null;
2243 }
2244 uidState.pkgOps = new ArrayMap<>();
2245 }
2246
2247 Ops ops = uidState.pkgOps.get(packageName);
2248 if (ops == null) {
2249 if (!edit) {
2250 return null;
2251 }
2252 ops = new Ops(packageName, uidState, isPrivileged);
2253 uidState.pkgOps.put(packageName, ops);
2254 }
2255 return ops;
2256 }
2257
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002258 private void scheduleWriteLocked() {
2259 if (!mWriteScheduled) {
2260 mWriteScheduled = true;
2261 mHandler.postDelayed(mWriteRunner, WRITE_DELAY);
2262 }
2263 }
2264
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002265 private void scheduleFastWriteLocked() {
2266 if (!mFastWriteScheduled) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002267 mWriteScheduled = true;
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08002268 mFastWriteScheduled = true;
2269 mHandler.removeCallbacks(mWriteRunner);
2270 mHandler.postDelayed(mWriteRunner, 10*1000);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002271 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002272 }
2273
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07002274 /**
2275 * Get the state of an op for a uid.
2276 *
2277 * @param code The code of the op
2278 * @param uid The uid the of the package
2279 * @param packageName The package name for which to get the state for
2280 * @param edit Iff {@code true} create the {@link Op} object if not yet created
2281 * @param verifyUid Iff {@code true} check that the package belongs to the uid
2282 * @param isPrivileged Whether the package is privileged or not (only used if {@code verifyUid
2283 * == false})
2284 *
2285 * @return The {@link Op state} of the op
2286 */
2287 private @Nullable Op getOpLocked(int code, int uid, @NonNull String packageName, boolean edit,
2288 boolean verifyUid, boolean isPrivileged) {
2289 Ops ops;
2290
2291 if (verifyUid) {
2292 ops = getOpsRawLocked(uid, packageName, edit, false /* uidMismatchExpected */);
2293 } else {
2294 ops = getOpsRawNoVerifyLocked(uid, packageName, edit, isPrivileged);
2295 }
2296
Dianne Hackborn72e39832013-01-18 18:36:09 -08002297 if (ops == null) {
2298 return null;
2299 }
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002300 return getOpLocked(ops, code, edit);
2301 }
2302
2303 private Op getOpLocked(Ops ops, int code, boolean edit) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002304 Op op = ops.get(code);
2305 if (op == null) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002306 if (!edit) {
2307 return null;
2308 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002309 op = new Op(ops.uidState, ops.packageName, code);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002310 ops.put(code, op);
2311 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002312 if (edit) {
2313 scheduleWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002314 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002315 return op;
2316 }
2317
Svet Ganov442ed572016-08-17 17:29:43 -07002318 private boolean isOpRestrictedLocked(int uid, int code, String packageName) {
Jason Monk62062992014-05-06 09:55:28 -04002319 int userHandle = UserHandle.getUserId(uid);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002320 final int restrictionSetCount = mOpUserRestrictions.size();
Ruben Brunk29931bc2016-03-11 00:24:26 -08002321
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002322 for (int i = 0; i < restrictionSetCount; i++) {
Ruben Brunk29931bc2016-03-11 00:24:26 -08002323 // For each client, check that the given op is not restricted, or that the given
2324 // package is exempt from the restriction.
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07002325 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07002326 if (restrictionState.hasRestriction(code, packageName, userHandle)) {
2327 if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
2328 // If we are the system, bypass user restrictions for certain codes
2329 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07002330 Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
2331 false /* uidMismatchExpected */);
Suprabh Shuklaffddadb2016-05-20 16:37:26 -07002332 if ((ops != null) && ops.isPrivileged) {
2333 return false;
2334 }
Ruben Brunk32f0fa42016-03-11 19:07:07 -08002335 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08002336 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08002337 return true;
Jason Monk1c7c3192014-06-26 12:52:18 -04002338 }
Jason Monk62062992014-05-06 09:55:28 -04002339 }
2340 return false;
2341 }
2342
Dianne Hackborn35654b62013-01-14 17:38:02 -08002343 void readState() {
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002344 int oldVersion = NO_VERSION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08002345 synchronized (mFile) {
2346 synchronized (this) {
2347 FileInputStream stream;
2348 try {
2349 stream = mFile.openRead();
2350 } catch (FileNotFoundException e) {
2351 Slog.i(TAG, "No existing app ops " + mFile.getBaseFile() + "; starting empty");
2352 return;
2353 }
2354 boolean success = false;
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002355 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002356 try {
2357 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002358 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08002359 int type;
2360 while ((type = parser.next()) != XmlPullParser.START_TAG
2361 && type != XmlPullParser.END_DOCUMENT) {
2362 ;
2363 }
2364
2365 if (type != XmlPullParser.START_TAG) {
2366 throw new IllegalStateException("no start tag found");
2367 }
2368
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002369 final String versionString = parser.getAttributeValue(null, "v");
2370 if (versionString != null) {
2371 oldVersion = Integer.parseInt(versionString);
2372 }
2373
Dianne Hackborn35654b62013-01-14 17:38:02 -08002374 int outerDepth = parser.getDepth();
2375 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2376 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2377 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2378 continue;
2379 }
2380
2381 String tagName = parser.getName();
2382 if (tagName.equals("pkg")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00002383 readPackage(parser);
Svetoslav215b44a2015-08-04 19:03:40 -07002384 } else if (tagName.equals("uid")) {
Svet Ganov2af57082015-07-30 08:44:20 -07002385 readUidOps(parser);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002386 } else {
2387 Slog.w(TAG, "Unknown element under <app-ops>: "
2388 + parser.getName());
2389 XmlUtils.skipCurrentTag(parser);
2390 }
2391 }
2392 success = true;
2393 } catch (IllegalStateException e) {
2394 Slog.w(TAG, "Failed parsing " + e);
2395 } catch (NullPointerException e) {
2396 Slog.w(TAG, "Failed parsing " + e);
2397 } catch (NumberFormatException e) {
2398 Slog.w(TAG, "Failed parsing " + e);
2399 } catch (XmlPullParserException e) {
2400 Slog.w(TAG, "Failed parsing " + e);
2401 } catch (IOException e) {
2402 Slog.w(TAG, "Failed parsing " + e);
2403 } catch (IndexOutOfBoundsException e) {
2404 Slog.w(TAG, "Failed parsing " + e);
2405 } finally {
2406 if (!success) {
Svet Ganov2af57082015-07-30 08:44:20 -07002407 mUidStates.clear();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002408 }
2409 try {
2410 stream.close();
2411 } catch (IOException e) {
2412 }
2413 }
2414 }
2415 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002416 synchronized (this) {
2417 upgradeLocked(oldVersion);
2418 }
2419 }
2420
2421 private void upgradeRunAnyInBackgroundLocked() {
2422 for (int i = 0; i < mUidStates.size(); i++) {
2423 final UidState uidState = mUidStates.valueAt(i);
2424 if (uidState == null) {
2425 continue;
2426 }
2427 if (uidState.opModes != null) {
2428 final int idx = uidState.opModes.indexOfKey(AppOpsManager.OP_RUN_IN_BACKGROUND);
2429 if (idx >= 0) {
2430 uidState.opModes.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND,
2431 uidState.opModes.valueAt(idx));
2432 }
2433 }
2434 if (uidState.pkgOps == null) {
2435 continue;
2436 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002437 boolean changed = false;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002438 for (int j = 0; j < uidState.pkgOps.size(); j++) {
2439 Ops ops = uidState.pkgOps.valueAt(j);
2440 if (ops != null) {
2441 final Op op = ops.get(AppOpsManager.OP_RUN_IN_BACKGROUND);
2442 if (op != null && op.mode != AppOpsManager.opToDefaultMode(op.op)) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002443 final Op copy = new Op(op.uidState, op.packageName,
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002444 AppOpsManager.OP_RUN_ANY_IN_BACKGROUND);
2445 copy.mode = op.mode;
2446 ops.put(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, copy);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002447 changed = true;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002448 }
2449 }
2450 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002451 if (changed) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002452 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002453 }
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002454 }
2455 }
2456
2457 private void upgradeLocked(int oldVersion) {
2458 if (oldVersion >= CURRENT_VERSION) {
2459 return;
2460 }
2461 Slog.d(TAG, "Upgrading app-ops xml from version " + oldVersion + " to " + CURRENT_VERSION);
2462 switch (oldVersion) {
2463 case NO_VERSION:
2464 upgradeRunAnyInBackgroundLocked();
2465 // fall through
2466 case 1:
2467 // for future upgrades
2468 }
2469 scheduleFastWriteLocked();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002470 }
2471
Svet Ganov2af57082015-07-30 08:44:20 -07002472 void readUidOps(XmlPullParser parser) throws NumberFormatException,
2473 XmlPullParserException, IOException {
2474 final int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
2475 int outerDepth = parser.getDepth();
2476 int type;
2477 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2478 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2479 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2480 continue;
2481 }
2482
2483 String tagName = parser.getName();
2484 if (tagName.equals("op")) {
2485 final int code = Integer.parseInt(parser.getAttributeValue(null, "n"));
2486 final int mode = Integer.parseInt(parser.getAttributeValue(null, "m"));
2487 UidState uidState = getUidStateLocked(uid, true);
2488 if (uidState.opModes == null) {
2489 uidState.opModes = new SparseIntArray();
2490 }
2491 uidState.opModes.put(code, mode);
2492 } else {
2493 Slog.w(TAG, "Unknown element under <uid-ops>: "
2494 + parser.getName());
2495 XmlUtils.skipCurrentTag(parser);
2496 }
2497 }
2498 }
2499
Dave Burke0997c5bd2013-08-02 20:25:02 +00002500 void readPackage(XmlPullParser parser) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08002501 XmlPullParserException, IOException {
2502 String pkgName = parser.getAttributeValue(null, "n");
2503 int outerDepth = parser.getDepth();
2504 int type;
2505 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2506 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2507 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2508 continue;
2509 }
2510
2511 String tagName = parser.getName();
2512 if (tagName.equals("uid")) {
Dave Burke0997c5bd2013-08-02 20:25:02 +00002513 readUid(parser, pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002514 } else {
2515 Slog.w(TAG, "Unknown element under <pkg>: "
2516 + parser.getName());
2517 XmlUtils.skipCurrentTag(parser);
2518 }
2519 }
2520 }
2521
Dave Burke0997c5bd2013-08-02 20:25:02 +00002522 void readUid(XmlPullParser parser, String pkgName) throws NumberFormatException,
Dianne Hackborn35654b62013-01-14 17:38:02 -08002523 XmlPullParserException, IOException {
2524 int uid = Integer.parseInt(parser.getAttributeValue(null, "n"));
Jason Monk1c7c3192014-06-26 12:52:18 -04002525 String isPrivilegedString = parser.getAttributeValue(null, "p");
2526 boolean isPrivileged = false;
2527 if (isPrivilegedString == null) {
2528 try {
2529 IPackageManager packageManager = ActivityThread.getPackageManager();
2530 if (packageManager != null) {
2531 ApplicationInfo appInfo = ActivityThread.getPackageManager()
2532 .getApplicationInfo(pkgName, 0, UserHandle.getUserId(uid));
2533 if (appInfo != null) {
Alex Klyubinb9f8a522015-02-03 11:12:59 -08002534 isPrivileged = (appInfo.privateFlags
2535 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
Jason Monk1c7c3192014-06-26 12:52:18 -04002536 }
2537 } else {
2538 // Could not load data, don't add to cache so it will be loaded later.
2539 return;
2540 }
2541 } catch (RemoteException e) {
2542 Slog.w(TAG, "Could not contact PackageManager", e);
2543 }
2544 } else {
2545 isPrivileged = Boolean.parseBoolean(isPrivilegedString);
2546 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002547 int outerDepth = parser.getDepth();
2548 int type;
2549 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2550 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2551 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2552 continue;
2553 }
2554
2555 String tagName = parser.getName();
2556 if (tagName.equals("op")) {
Svet Ganov2af57082015-07-30 08:44:20 -07002557 UidState uidState = getUidStateLocked(uid, true);
2558 if (uidState.pkgOps == null) {
2559 uidState.pkgOps = new ArrayMap<>();
Dianne Hackborn35654b62013-01-14 17:38:02 -08002560 }
Svet Ganov2af57082015-07-30 08:44:20 -07002561
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002562 Op op = new Op(uidState, pkgName,
2563 Integer.parseInt(parser.getAttributeValue(null, "n")));
2564
2565 for (int i = parser.getAttributeCount()-1; i >= 0; i--) {
2566 final String name = parser.getAttributeName(i);
2567 final String value = parser.getAttributeValue(i);
2568 switch (name) {
2569 case "m":
2570 op.mode = Integer.parseInt(value);
2571 break;
2572 case "d":
2573 op.duration = Integer.parseInt(value);
2574 break;
2575 case "pu":
2576 op.proxyUid = Integer.parseInt(value);
2577 break;
2578 case "pp":
2579 op.proxyPackageName = value;
2580 break;
2581 case "tp":
2582 op.time[AppOpsManager.UID_STATE_PERSISTENT] = Long.parseLong(value);
2583 break;
2584 case "tt":
2585 op.time[AppOpsManager.UID_STATE_TOP] = Long.parseLong(value);
2586 break;
2587 case "tfs":
2588 op.time[AppOpsManager.UID_STATE_FOREGROUND_SERVICE]
2589 = Long.parseLong(value);
2590 break;
2591 case "tf":
2592 op.time[AppOpsManager.UID_STATE_FOREGROUND] = Long.parseLong(value);
2593 break;
2594 case "tb":
2595 op.time[AppOpsManager.UID_STATE_BACKGROUND] = Long.parseLong(value);
2596 break;
2597 case "tc":
2598 op.time[AppOpsManager.UID_STATE_CACHED] = Long.parseLong(value);
2599 break;
2600 case "rp":
2601 op.rejectTime[AppOpsManager.UID_STATE_PERSISTENT]
2602 = Long.parseLong(value);
2603 break;
2604 case "rt":
2605 op.rejectTime[AppOpsManager.UID_STATE_TOP] = Long.parseLong(value);
2606 break;
2607 case "rfs":
2608 op.rejectTime[AppOpsManager.UID_STATE_FOREGROUND_SERVICE]
2609 = Long.parseLong(value);
2610 break;
2611 case "rf":
2612 op.rejectTime[AppOpsManager.UID_STATE_FOREGROUND]
2613 = Long.parseLong(value);
2614 break;
2615 case "rb":
2616 op.rejectTime[AppOpsManager.UID_STATE_BACKGROUND]
2617 = Long.parseLong(value);
2618 break;
2619 case "rc":
2620 op.rejectTime[AppOpsManager.UID_STATE_CACHED]
2621 = Long.parseLong(value);
2622 break;
2623 case "t":
2624 // Backwards compat.
2625 op.time[AppOpsManager.UID_STATE_TOP] = Long.parseLong(value);
2626 break;
2627 case "r":
2628 // Backwards compat.
2629 op.rejectTime[AppOpsManager.UID_STATE_TOP] = Long.parseLong(value);
2630 break;
2631 default:
2632 Slog.w(TAG, "Unknown attribute in 'op' tag: " + name);
2633 break;
2634 }
2635 }
2636
Svet Ganov2af57082015-07-30 08:44:20 -07002637 Ops ops = uidState.pkgOps.get(pkgName);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002638 if (ops == null) {
Svet Ganov2af57082015-07-30 08:44:20 -07002639 ops = new Ops(pkgName, uidState, isPrivileged);
2640 uidState.pkgOps.put(pkgName, ops);
Dianne Hackborn35654b62013-01-14 17:38:02 -08002641 }
2642 ops.put(op.op, op);
2643 } else {
2644 Slog.w(TAG, "Unknown element under <pkg>: "
2645 + parser.getName());
2646 XmlUtils.skipCurrentTag(parser);
2647 }
2648 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002649 UidState uidState = getUidStateLocked(uid, false);
2650 if (uidState != null) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002651 uidState.evalForegroundOps(mOpModeWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002652 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002653 }
2654
2655 void writeState() {
2656 synchronized (mFile) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002657 FileOutputStream stream;
2658 try {
2659 stream = mFile.startWrite();
2660 } catch (IOException e) {
2661 Slog.w(TAG, "Failed to write state: " + e);
2662 return;
2663 }
2664
Dianne Hackborne17b4452018-01-10 13:15:40 -08002665 List<AppOpsManager.PackageOps> allOps = getPackagesForOps(null);
2666
Dianne Hackborn35654b62013-01-14 17:38:02 -08002667 try {
2668 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002669 out.setOutput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn35654b62013-01-14 17:38:02 -08002670 out.startDocument(null, true);
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002671 out.startTag(null, "app-ops");
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07002672 out.attribute(null, "v", String.valueOf(CURRENT_VERSION));
Svet Ganov2af57082015-07-30 08:44:20 -07002673
2674 final int uidStateCount = mUidStates.size();
2675 for (int i = 0; i < uidStateCount; i++) {
2676 UidState uidState = mUidStates.valueAt(i);
2677 if (uidState.opModes != null && uidState.opModes.size() > 0) {
2678 out.startTag(null, "uid");
2679 out.attribute(null, "n", Integer.toString(uidState.uid));
2680 SparseIntArray uidOpModes = uidState.opModes;
2681 final int opCount = uidOpModes.size();
2682 for (int j = 0; j < opCount; j++) {
2683 final int op = uidOpModes.keyAt(j);
2684 final int mode = uidOpModes.valueAt(j);
2685 out.startTag(null, "op");
2686 out.attribute(null, "n", Integer.toString(op));
2687 out.attribute(null, "m", Integer.toString(mode));
2688 out.endTag(null, "op");
2689 }
2690 out.endTag(null, "uid");
2691 }
2692 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002693
2694 if (allOps != null) {
2695 String lastPkg = null;
2696 for (int i=0; i<allOps.size(); i++) {
2697 AppOpsManager.PackageOps pkg = allOps.get(i);
2698 if (!pkg.getPackageName().equals(lastPkg)) {
2699 if (lastPkg != null) {
2700 out.endTag(null, "pkg");
2701 }
2702 lastPkg = pkg.getPackageName();
2703 out.startTag(null, "pkg");
2704 out.attribute(null, "n", lastPkg);
2705 }
2706 out.startTag(null, "uid");
2707 out.attribute(null, "n", Integer.toString(pkg.getUid()));
Jason Monk1c7c3192014-06-26 12:52:18 -04002708 synchronized (this) {
Yohei Yukawaa965d652017-10-12 15:02:26 -07002709 Ops ops = getOpsRawLocked(pkg.getUid(), pkg.getPackageName(),
2710 false /* edit */, false /* uidMismatchExpected */);
Jason Monk1c7c3192014-06-26 12:52:18 -04002711 // Should always be present as the list of PackageOps is generated
2712 // from Ops.
2713 if (ops != null) {
2714 out.attribute(null, "p", Boolean.toString(ops.isPrivileged));
2715 } else {
2716 out.attribute(null, "p", Boolean.toString(false));
2717 }
2718 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002719 List<AppOpsManager.OpEntry> ops = pkg.getOps();
2720 for (int j=0; j<ops.size(); j++) {
2721 AppOpsManager.OpEntry op = ops.get(j);
2722 out.startTag(null, "op");
2723 out.attribute(null, "n", Integer.toString(op.getOp()));
David Braunf5d83192013-09-16 13:43:51 -07002724 if (op.getMode() != AppOpsManager.opToDefaultMode(op.getOp())) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002725 out.attribute(null, "m", Integer.toString(op.getMode()));
2726 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002727 for (int k = 0; k < _NUM_UID_STATE; k++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002728 final long time = op.getLastTimeFor(k);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002729 if (time != 0) {
2730 out.attribute(null, UID_STATE_TIME_ATTRS[k],
2731 Long.toString(time));
2732 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002733 final long rejectTime = op.getLastRejectTimeFor(k);
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002734 if (rejectTime != 0) {
2735 out.attribute(null, UID_STATE_REJECT_ATTRS[k],
2736 Long.toString(rejectTime));
2737 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002738 }
2739 int dur = op.getDuration();
2740 if (dur != 0) {
2741 out.attribute(null, "d", Integer.toString(dur));
2742 }
Svet Ganov99b60432015-06-27 13:15:22 -07002743 int proxyUid = op.getProxyUid();
2744 if (proxyUid != -1) {
2745 out.attribute(null, "pu", Integer.toString(proxyUid));
2746 }
2747 String proxyPackageName = op.getProxyPackageName();
2748 if (proxyPackageName != null) {
2749 out.attribute(null, "pp", proxyPackageName);
2750 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08002751 out.endTag(null, "op");
2752 }
2753 out.endTag(null, "uid");
2754 }
2755 if (lastPkg != null) {
2756 out.endTag(null, "pkg");
2757 }
2758 }
2759
2760 out.endTag(null, "app-ops");
2761 out.endDocument();
2762 mFile.finishWrite(stream);
2763 } catch (IOException e) {
2764 Slog.w(TAG, "Failed to write state, restoring backup.", e);
2765 mFile.failWrite(stream);
2766 }
2767 }
2768 }
2769
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002770 static class Shell extends ShellCommand {
2771 final IAppOpsService mInterface;
2772 final AppOpsService mInternal;
2773
2774 int userId = UserHandle.USER_SYSTEM;
2775 String packageName;
2776 String opStr;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002777 String modeStr;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002778 int op;
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002779 int mode;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002780 int packageUid;
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002781 int nonpackageUid;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05002782 final static Binder sBinder = new Binder();
2783 IBinder mToken;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002784
2785 Shell(IAppOpsService iface, AppOpsService internal) {
2786 mInterface = iface;
2787 mInternal = internal;
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05002788 try {
2789 mToken = mInterface.getToken(sBinder);
2790 } catch (RemoteException e) {
2791 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002792 }
2793
2794 @Override
2795 public int onCommand(String cmd) {
2796 return onShellCommand(this, cmd);
2797 }
2798
2799 @Override
2800 public void onHelp() {
2801 PrintWriter pw = getOutPrintWriter();
2802 dumpCommandHelp(pw);
2803 }
2804
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002805 static private int strOpToOp(String op, PrintWriter err) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002806 try {
2807 return AppOpsManager.strOpToOp(op);
2808 } catch (IllegalArgumentException e) {
2809 }
2810 try {
2811 return Integer.parseInt(op);
2812 } catch (NumberFormatException e) {
2813 }
2814 try {
2815 return AppOpsManager.strDebugOpToOp(op);
2816 } catch (IllegalArgumentException e) {
2817 err.println("Error: " + e.getMessage());
2818 return -1;
2819 }
2820 }
2821
Dianne Hackborn65a4f252018-05-08 17:30:48 -07002822 static int strModeToMode(String modeStr, PrintWriter err) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07002823 for (int i = AppOpsManager.MODE_NAMES.length - 1; i >= 0; i--) {
2824 if (AppOpsManager.MODE_NAMES[i].equals(modeStr)) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07002825 return i;
2826 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002827 }
2828 try {
2829 return Integer.parseInt(modeStr);
2830 } catch (NumberFormatException e) {
2831 }
2832 err.println("Error: Mode " + modeStr + " is not valid");
2833 return -1;
2834 }
2835
2836 int parseUserOpMode(int defMode, PrintWriter err) throws RemoteException {
2837 userId = UserHandle.USER_CURRENT;
2838 opStr = null;
2839 modeStr = null;
2840 for (String argument; (argument = getNextArg()) != null;) {
2841 if ("--user".equals(argument)) {
2842 userId = UserHandle.parseUserArg(getNextArgRequired());
2843 } else {
2844 if (opStr == null) {
2845 opStr = argument;
2846 } else if (modeStr == null) {
2847 modeStr = argument;
2848 break;
2849 }
2850 }
2851 }
2852 if (opStr == null) {
2853 err.println("Error: Operation not specified.");
2854 return -1;
2855 }
2856 op = strOpToOp(opStr, err);
2857 if (op < 0) {
2858 return -1;
2859 }
2860 if (modeStr != null) {
2861 if ((mode=strModeToMode(modeStr, err)) < 0) {
2862 return -1;
2863 }
2864 } else {
2865 mode = defMode;
2866 }
2867 return 0;
2868 }
2869
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002870 int parseUserPackageOp(boolean reqOp, PrintWriter err) throws RemoteException {
2871 userId = UserHandle.USER_CURRENT;
2872 packageName = null;
2873 opStr = null;
2874 for (String argument; (argument = getNextArg()) != null;) {
2875 if ("--user".equals(argument)) {
2876 userId = UserHandle.parseUserArg(getNextArgRequired());
2877 } else {
2878 if (packageName == null) {
2879 packageName = argument;
2880 } else if (opStr == null) {
2881 opStr = argument;
2882 break;
2883 }
2884 }
2885 }
2886 if (packageName == null) {
2887 err.println("Error: Package name not specified.");
2888 return -1;
2889 } else if (opStr == null && reqOp) {
2890 err.println("Error: Operation not specified.");
2891 return -1;
2892 }
2893 if (opStr != null) {
2894 op = strOpToOp(opStr, err);
2895 if (op < 0) {
2896 return -1;
2897 }
2898 } else {
2899 op = AppOpsManager.OP_NONE;
2900 }
2901 if (userId == UserHandle.USER_CURRENT) {
2902 userId = ActivityManager.getCurrentUser();
2903 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002904 nonpackageUid = -1;
2905 try {
2906 nonpackageUid = Integer.parseInt(packageName);
2907 } catch (NumberFormatException e) {
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002908 }
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002909 if (nonpackageUid == -1 && packageName.length() > 1 && packageName.charAt(0) == 'u'
2910 && packageName.indexOf('.') < 0) {
2911 int i = 1;
2912 while (i < packageName.length() && packageName.charAt(i) >= '0'
2913 && packageName.charAt(i) <= '9') {
2914 i++;
2915 }
2916 if (i > 1 && i < packageName.length()) {
2917 String userStr = packageName.substring(1, i);
2918 try {
2919 int user = Integer.parseInt(userStr);
2920 char type = packageName.charAt(i);
2921 i++;
2922 int startTypeVal = i;
2923 while (i < packageName.length() && packageName.charAt(i) >= '0'
2924 && packageName.charAt(i) <= '9') {
2925 i++;
2926 }
2927 if (i > startTypeVal) {
2928 String typeValStr = packageName.substring(startTypeVal, i);
2929 try {
2930 int typeVal = Integer.parseInt(typeValStr);
2931 if (type == 'a') {
2932 nonpackageUid = UserHandle.getUid(user,
2933 typeVal + Process.FIRST_APPLICATION_UID);
2934 } else if (type == 's') {
2935 nonpackageUid = UserHandle.getUid(user, typeVal);
2936 }
2937 } catch (NumberFormatException e) {
2938 }
2939 }
2940 } catch (NumberFormatException e) {
2941 }
2942 }
2943 }
2944 if (nonpackageUid != -1) {
2945 packageName = null;
2946 } else {
Svet Ganov82f09bc2018-01-12 22:08:40 -08002947 packageUid = resolveUid(packageName);
2948 if (packageUid < 0) {
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002949 packageUid = AppGlobals.getPackageManager().getPackageUid(packageName,
2950 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
2951 }
2952 if (packageUid < 0) {
2953 err.println("Error: No UID for " + packageName + " in user " + userId);
2954 return -1;
2955 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002956 }
2957 return 0;
2958 }
2959 }
2960
2961 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002962 FileDescriptor err, String[] args, ShellCallback callback,
2963 ResultReceiver resultReceiver) {
2964 (new Shell(this, this)).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002965 }
2966
2967 static void dumpCommandHelp(PrintWriter pw) {
2968 pw.println("AppOps service (appops) commands:");
2969 pw.println(" help");
2970 pw.println(" Print this help text.");
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05002971 pw.println(" start [--user <USER_ID>] <PACKAGE | UID> <OP> ");
2972 pw.println(" Starts a given operation for a particular application.");
2973 pw.println(" stop [--user <USER_ID>] <PACKAGE | UID> <OP> ");
2974 pw.println(" Stops a given operation for a particular application.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002975 pw.println(" set [--user <USER_ID>] <PACKAGE | UID> <OP> <MODE>");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002976 pw.println(" Set the mode for a particular application and operation.");
Dianne Hackbornc7214a32017-04-11 13:32:47 -07002977 pw.println(" get [--user <USER_ID>] <PACKAGE | UID> [<OP>]");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002978 pw.println(" Return the mode for a particular application and optional operation.");
Dianne Hackborne91f3e72016-03-25 18:48:15 -07002979 pw.println(" query-op [--user <USER_ID>] <OP> [<MODE>]");
2980 pw.println(" Print all packages that currently have the given op in the given mode.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002981 pw.println(" reset [--user <USER_ID>] [<PACKAGE>]");
2982 pw.println(" Reset the given application or all applications to default modes.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07002983 pw.println(" write-settings");
2984 pw.println(" Immediately write pending changes to storage.");
2985 pw.println(" read-settings");
2986 pw.println(" Read the last written settings, replacing current state in RAM.");
Dianne Hackborn268e4e32015-11-18 16:29:56 -08002987 pw.println(" options:");
2988 pw.println(" <PACKAGE> an Android package name.");
2989 pw.println(" <OP> an AppOps operation.");
2990 pw.println(" <MODE> one of allow, ignore, deny, or default");
2991 pw.println(" <USER_ID> the user id under which the package is installed. If --user is not");
2992 pw.println(" specified, the current user is assumed.");
2993 }
2994
2995 static int onShellCommand(Shell shell, String cmd) {
2996 if (cmd == null) {
2997 return shell.handleDefaultCommands(cmd);
2998 }
2999 PrintWriter pw = shell.getOutPrintWriter();
3000 PrintWriter err = shell.getErrPrintWriter();
3001 try {
3002 switch (cmd) {
3003 case "set": {
3004 int res = shell.parseUserPackageOp(true, err);
3005 if (res < 0) {
3006 return res;
3007 }
3008 String modeStr = shell.getNextArg();
3009 if (modeStr == null) {
3010 err.println("Error: Mode not specified.");
3011 return -1;
3012 }
3013
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003014 final int mode = shell.strModeToMode(modeStr, err);
3015 if (mode < 0) {
3016 return -1;
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003017 }
3018
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003019 if (shell.packageName != null) {
3020 shell.mInterface.setMode(shell.op, shell.packageUid, shell.packageName,
3021 mode);
3022 } else {
3023 shell.mInterface.setUidMode(shell.op, shell.nonpackageUid, mode);
3024 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003025 return 0;
3026 }
3027 case "get": {
3028 int res = shell.parseUserPackageOp(false, err);
3029 if (res < 0) {
3030 return res;
3031 }
3032
Dianne Hackbornc7214a32017-04-11 13:32:47 -07003033 List<AppOpsManager.PackageOps> ops;
3034 if (shell.packageName != null) {
3035 ops = shell.mInterface.getOpsForPackage(
3036 shell.packageUid, shell.packageName,
3037 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
3038 } else {
3039 ops = shell.mInterface.getUidOps(
3040 shell.nonpackageUid,
3041 shell.op != AppOpsManager.OP_NONE ? new int[]{shell.op} : null);
3042 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003043 if (ops == null || ops.size() <= 0) {
3044 pw.println("No operations.");
Svet Ganov82f09bc2018-01-12 22:08:40 -08003045 if (shell.op > AppOpsManager.OP_NONE && shell.op < AppOpsManager._NUM_OP) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003046 pw.println("Default mode: " + AppOpsManager.modeToName(
Svet Ganov82f09bc2018-01-12 22:08:40 -08003047 AppOpsManager.opToDefaultMode(shell.op)));
3048 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003049 return 0;
3050 }
3051 final long now = System.currentTimeMillis();
3052 for (int i=0; i<ops.size(); i++) {
3053 List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
3054 for (int j=0; j<entries.size(); j++) {
3055 AppOpsManager.OpEntry ent = entries.get(j);
3056 pw.print(AppOpsManager.opToName(ent.getOp()));
3057 pw.print(": ");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003058 pw.print(AppOpsManager.modeToName(ent.getMode()));
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003059 if (ent.getTime() != 0) {
3060 pw.print("; time=");
3061 TimeUtils.formatDuration(now - ent.getTime(), pw);
3062 pw.print(" ago");
3063 }
3064 if (ent.getRejectTime() != 0) {
3065 pw.print("; rejectTime=");
3066 TimeUtils.formatDuration(now - ent.getRejectTime(), pw);
3067 pw.print(" ago");
3068 }
3069 if (ent.getDuration() == -1) {
3070 pw.print(" (running)");
3071 } else if (ent.getDuration() != 0) {
3072 pw.print("; duration=");
3073 TimeUtils.formatDuration(ent.getDuration(), pw);
3074 }
3075 pw.println();
3076 }
3077 }
3078 return 0;
3079 }
Dianne Hackborne91f3e72016-03-25 18:48:15 -07003080 case "query-op": {
3081 int res = shell.parseUserOpMode(AppOpsManager.MODE_IGNORED, err);
3082 if (res < 0) {
3083 return res;
3084 }
3085 List<AppOpsManager.PackageOps> ops = shell.mInterface.getPackagesForOps(
3086 new int[] {shell.op});
3087 if (ops == null || ops.size() <= 0) {
3088 pw.println("No operations.");
3089 return 0;
3090 }
3091 for (int i=0; i<ops.size(); i++) {
3092 final AppOpsManager.PackageOps pkg = ops.get(i);
3093 boolean hasMatch = false;
3094 final List<AppOpsManager.OpEntry> entries = ops.get(i).getOps();
3095 for (int j=0; j<entries.size(); j++) {
3096 AppOpsManager.OpEntry ent = entries.get(j);
3097 if (ent.getOp() == shell.op && ent.getMode() == shell.mode) {
3098 hasMatch = true;
3099 break;
3100 }
3101 }
3102 if (hasMatch) {
3103 pw.println(pkg.getPackageName());
3104 }
3105 }
3106 return 0;
3107 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003108 case "reset": {
3109 String packageName = null;
3110 int userId = UserHandle.USER_CURRENT;
3111 for (String argument; (argument = shell.getNextArg()) != null;) {
3112 if ("--user".equals(argument)) {
3113 String userStr = shell.getNextArgRequired();
3114 userId = UserHandle.parseUserArg(userStr);
3115 } else {
3116 if (packageName == null) {
3117 packageName = argument;
3118 } else {
3119 err.println("Error: Unsupported argument: " + argument);
3120 return -1;
3121 }
3122 }
3123 }
3124
3125 if (userId == UserHandle.USER_CURRENT) {
3126 userId = ActivityManager.getCurrentUser();
3127 }
3128
3129 shell.mInterface.resetAllModes(userId, packageName);
3130 pw.print("Reset all modes for: ");
3131 if (userId == UserHandle.USER_ALL) {
3132 pw.print("all users");
3133 } else {
3134 pw.print("user "); pw.print(userId);
3135 }
3136 pw.print(", ");
3137 if (packageName == null) {
3138 pw.println("all packages");
3139 } else {
3140 pw.print("package "); pw.println(packageName);
3141 }
3142 return 0;
3143 }
3144 case "write-settings": {
Dianne Hackbornd5254412018-05-11 18:02:58 -07003145 shell.mInternal.enforceManageAppOpsModes(Binder.getCallingPid(),
3146 Binder.getCallingUid(), -1);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003147 long token = Binder.clearCallingIdentity();
3148 try {
3149 synchronized (shell.mInternal) {
3150 shell.mInternal.mHandler.removeCallbacks(shell.mInternal.mWriteRunner);
3151 }
3152 shell.mInternal.writeState();
3153 pw.println("Current settings written.");
3154 } finally {
3155 Binder.restoreCallingIdentity(token);
3156 }
3157 return 0;
3158 }
3159 case "read-settings": {
Dianne Hackbornd5254412018-05-11 18:02:58 -07003160 shell.mInternal.enforceManageAppOpsModes(Binder.getCallingPid(),
3161 Binder.getCallingUid(), -1);
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003162 long token = Binder.clearCallingIdentity();
3163 try {
3164 shell.mInternal.readState();
3165 pw.println("Last settings read.");
3166 } finally {
3167 Binder.restoreCallingIdentity(token);
3168 }
3169 return 0;
3170 }
Julia Reynolds6cb5fcc2018-02-27 17:33:52 -05003171 case "start": {
3172 int res = shell.parseUserPackageOp(true, err);
3173 if (res < 0) {
3174 return res;
3175 }
3176
3177 if (shell.packageName != null) {
3178 shell.mInterface.startOperation(shell.mToken,
3179 shell.op, shell.packageUid, shell.packageName, true);
3180 } else {
3181 return -1;
3182 }
3183 return 0;
3184 }
3185 case "stop": {
3186 int res = shell.parseUserPackageOp(true, err);
3187 if (res < 0) {
3188 return res;
3189 }
3190
3191 if (shell.packageName != null) {
3192 shell.mInterface.finishOperation(shell.mToken,
3193 shell.op, shell.packageUid, shell.packageName);
3194 } else {
3195 return -1;
3196 }
3197 return 0;
3198 }
Dianne Hackborn268e4e32015-11-18 16:29:56 -08003199 default:
3200 return shell.handleDefaultCommands(cmd);
3201 }
3202 } catch (RemoteException e) {
3203 pw.println("Remote exception: " + e);
3204 }
3205 return -1;
3206 }
3207
3208 private void dumpHelp(PrintWriter pw) {
3209 pw.println("AppOps service (appops) dump options:");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003210 pw.println(" -h");
3211 pw.println(" Print this help text.");
3212 pw.println(" --op [OP]");
3213 pw.println(" Limit output to data associated with the given app op code.");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003214 pw.println(" --mode [MODE]");
3215 pw.println(" Limit output to data associated with the given app op mode.");
3216 pw.println(" --package [PACKAGE]");
3217 pw.println(" Limit output to data associated with the given package name.");
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003218 }
3219
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003220 private void dumpTimesLocked(PrintWriter pw, String firstPrefix, String prefix, long[] times,
3221 long now, SimpleDateFormat sdf, Date date) {
3222 boolean hasTime = false;
3223 for (int i = 0; i < _NUM_UID_STATE; i++) {
3224 if (times[i] != 0) {
3225 hasTime = true;
3226 break;
3227 }
3228 }
3229 if (!hasTime) {
3230 return;
3231 }
3232 boolean first = true;
3233 for (int i = 0; i < _NUM_UID_STATE; i++) {
3234 if (times[i] != 0) {
3235 pw.print(first ? firstPrefix : prefix);
3236 first = false;
3237 pw.print(UID_STATE_NAMES[i]);
3238 pw.print(" = ");
3239 date.setTime(times[i]);
3240 pw.print(sdf.format(date));
3241 pw.print(" (");
3242 TimeUtils.formatDuration(times[i]-now, pw);
3243 pw.println(")");
3244 }
3245 }
3246 }
3247
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003248 @Override
3249 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06003250 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003251
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003252 int dumpOp = -1;
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003253 String dumpPackage = null;
3254 int dumpUid = -1;
3255 int dumpMode = -1;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003256
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003257 if (args != null) {
3258 for (int i=0; i<args.length; i++) {
3259 String arg = args[i];
3260 if ("-h".equals(arg)) {
3261 dumpHelp(pw);
3262 return;
Tim Kilbourn8f1ea832015-08-26 15:07:37 -07003263 } else if ("-a".equals(arg)) {
3264 // dump all data
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003265 } else if ("--op".equals(arg)) {
3266 i++;
3267 if (i >= args.length) {
3268 pw.println("No argument for --op option");
3269 return;
3270 }
3271 dumpOp = Shell.strOpToOp(args[i], pw);
3272 if (dumpOp < 0) {
3273 return;
3274 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003275 } else if ("--package".equals(arg)) {
3276 i++;
3277 if (i >= args.length) {
3278 pw.println("No argument for --package option");
3279 return;
3280 }
3281 dumpPackage = args[i];
3282 try {
3283 dumpUid = AppGlobals.getPackageManager().getPackageUid(dumpPackage,
3284 PackageManager.MATCH_KNOWN_PACKAGES | PackageManager.MATCH_INSTANT,
3285 0);
3286 } catch (RemoteException e) {
3287 }
3288 if (dumpUid < 0) {
3289 pw.println("Unknown package: " + dumpPackage);
3290 return;
3291 }
3292 dumpUid = UserHandle.getAppId(dumpUid);
3293 } else if ("--mode".equals(arg)) {
3294 i++;
3295 if (i >= args.length) {
3296 pw.println("No argument for --mode option");
3297 return;
3298 }
3299 dumpMode = Shell.strModeToMode(args[i], pw);
3300 if (dumpMode < 0) {
3301 return;
3302 }
Dianne Hackborn4d34bb82015-08-07 18:26:38 -07003303 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
3304 pw.println("Unknown option: " + arg);
3305 return;
3306 } else {
3307 pw.println("Unknown command: " + arg);
3308 return;
3309 }
3310 }
3311 }
3312
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003313 synchronized (this) {
3314 pw.println("Current AppOps Service state:");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003315 mConstants.dump(pw);
3316 pw.println();
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003317 final long now = System.currentTimeMillis();
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003318 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003319 final long nowUptime = SystemClock.uptimeMillis();
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003320 final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
3321 final Date date = new Date();
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003322 boolean needSep = false;
Dianne Hackbornd5254412018-05-11 18:02:58 -07003323 if (dumpOp < 0 && dumpMode < 0 && dumpPackage == null && mProfileOwners != null) {
3324 pw.println(" Profile owners:");
3325 for (int poi = 0; poi < mProfileOwners.size(); poi++) {
3326 pw.print(" User #");
3327 pw.print(mProfileOwners.keyAt(poi));
3328 pw.print(": ");
3329 UserHandle.formatUid(pw, mProfileOwners.valueAt(poi));
3330 pw.println();
3331 }
3332 pw.println();
3333 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003334 if (mOpModeWatchers.size() > 0) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003335 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003336 for (int i=0; i<mOpModeWatchers.size(); i++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003337 if (dumpOp >= 0 && dumpOp != mOpModeWatchers.keyAt(i)) {
3338 continue;
3339 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003340 boolean printedOpHeader = false;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003341 ArraySet<ModeCallback> callbacks = mOpModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003342 for (int j=0; j<callbacks.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003343 final ModeCallback cb = callbacks.valueAt(j);
3344 if (dumpPackage != null && cb.mWatchingUid >= 0
3345 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3346 continue;
3347 }
3348 needSep = true;
3349 if (!printedHeader) {
3350 pw.println(" Op mode watchers:");
3351 printedHeader = true;
3352 }
3353 if (!printedOpHeader) {
3354 pw.print(" Op ");
3355 pw.print(AppOpsManager.opToName(mOpModeWatchers.keyAt(i)));
3356 pw.println(":");
3357 printedOpHeader = true;
3358 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003359 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003360 pw.println(cb);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003361 }
3362 }
3363 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003364 if (mPackageModeWatchers.size() > 0 && dumpOp < 0) {
3365 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003366 for (int i=0; i<mPackageModeWatchers.size(); i++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003367 if (dumpPackage != null && !dumpPackage.equals(mPackageModeWatchers.keyAt(i))) {
3368 continue;
3369 }
3370 needSep = true;
3371 if (!printedHeader) {
3372 pw.println(" Package mode watchers:");
3373 printedHeader = true;
3374 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003375 pw.print(" Pkg "); pw.print(mPackageModeWatchers.keyAt(i));
3376 pw.println(":");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003377 ArraySet<ModeCallback> callbacks = mPackageModeWatchers.valueAt(i);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003378 for (int j=0; j<callbacks.size(); j++) {
3379 pw.print(" #"); pw.print(j); pw.print(": ");
Dianne Hackborn68d76552017-02-27 15:32:03 -08003380 pw.println(callbacks.valueAt(j));
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003381 }
3382 }
3383 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003384 if (mModeWatchers.size() > 0 && dumpOp < 0) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003385 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003386 for (int i=0; i<mModeWatchers.size(); i++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003387 final ModeCallback cb = mModeWatchers.valueAt(i);
3388 if (dumpPackage != null && cb.mWatchingUid >= 0
3389 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3390 continue;
3391 }
3392 needSep = true;
3393 if (!printedHeader) {
3394 pw.println(" All op mode watchers:");
3395 printedHeader = true;
3396 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003397 pw.print(" ");
3398 pw.print(Integer.toHexString(System.identityHashCode(mModeWatchers.keyAt(i))));
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003399 pw.print(": "); pw.println(cb);
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003400 }
3401 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003402 if (mActiveWatchers.size() > 0 && dumpMode < 0) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003403 needSep = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003404 boolean printedHeader = false;
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003405 for (int i = 0; i < mActiveWatchers.size(); i++) {
3406 final SparseArray<ActiveCallback> activeWatchers = mActiveWatchers.valueAt(i);
3407 if (activeWatchers.size() <= 0) {
3408 continue;
3409 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003410 final ActiveCallback cb = activeWatchers.valueAt(0);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003411 if (dumpOp >= 0 && activeWatchers.indexOfKey(dumpOp) < 0) {
3412 continue;
3413 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003414 if (dumpPackage != null && cb.mWatchingUid >= 0
3415 && dumpUid != UserHandle.getAppId(cb.mWatchingUid)) {
3416 continue;
3417 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003418 if (!printedHeader) {
3419 pw.println(" All op active watchers:");
3420 printedHeader = true;
3421 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003422 pw.print(" ");
3423 pw.print(Integer.toHexString(System.identityHashCode(
3424 mActiveWatchers.keyAt(i))));
3425 pw.println(" ->");
3426 pw.print(" [");
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003427 final int opCount = activeWatchers.size();
3428 for (i = 0; i < opCount; i++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003429 if (i > 0) {
3430 pw.print(' ');
3431 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003432 pw.print(AppOpsManager.opToName(activeWatchers.keyAt(i)));
3433 if (i < opCount - 1) {
3434 pw.print(',');
3435 }
3436 }
Dianne Hackborn3b563fc2018-04-16 17:17:14 -07003437 pw.println("]");
3438 pw.print(" ");
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003439 pw.println(cb);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003440 }
3441 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003442 if (mClients.size() > 0 && dumpMode < 0) {
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003443 needSep = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003444 boolean printedHeader = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003445 for (int i=0; i<mClients.size(); i++) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003446 boolean printedClient = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003447 ClientState cs = mClients.valueAt(i);
Svet Ganovf7b47252018-02-26 11:11:27 -08003448 if (cs.mStartedOps.size() > 0) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003449 boolean printedStarted = false;
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003450 for (int j=0; j<cs.mStartedOps.size(); j++) {
3451 Op op = cs.mStartedOps.get(j);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003452 if (dumpOp >= 0 && op.op != dumpOp) {
3453 continue;
3454 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003455 if (dumpPackage != null && !dumpPackage.equals(op.packageName)) {
3456 continue;
3457 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003458 if (!printedHeader) {
3459 pw.println(" Clients:");
3460 printedHeader = true;
3461 }
3462 if (!printedClient) {
3463 pw.print(" "); pw.print(mClients.keyAt(i)); pw.println(":");
3464 pw.print(" "); pw.println(cs);
3465 printedClient = true;
3466 }
3467 if (!printedStarted) {
3468 pw.println(" Started ops:");
3469 printedStarted = true;
3470 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003471 pw.print(" "); pw.print("uid="); pw.print(op.uid);
3472 pw.print(" pkg="); pw.print(op.packageName);
3473 pw.print(" op="); pw.println(AppOpsManager.opToName(op.op));
3474 }
3475 }
3476 }
3477 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003478 if (mAudioRestrictions.size() > 0 && dumpOp < 0 && dumpPackage != null
3479 && dumpMode < 0) {
John Spurlock1af30c72014-03-10 08:33:35 -04003480 boolean printedHeader = false;
3481 for (int o=0; o<mAudioRestrictions.size(); o++) {
3482 final String op = AppOpsManager.opToName(mAudioRestrictions.keyAt(o));
3483 final SparseArray<Restriction> restrictions = mAudioRestrictions.valueAt(o);
3484 for (int i=0; i<restrictions.size(); i++) {
3485 if (!printedHeader){
3486 pw.println(" Audio Restrictions:");
3487 printedHeader = true;
3488 needSep = true;
3489 }
John Spurlock7b414672014-07-18 13:02:39 -04003490 final int usage = restrictions.keyAt(i);
John Spurlock1af30c72014-03-10 08:33:35 -04003491 pw.print(" "); pw.print(op);
John Spurlock7b414672014-07-18 13:02:39 -04003492 pw.print(" usage="); pw.print(AudioAttributes.usageToString(usage));
John Spurlock1af30c72014-03-10 08:33:35 -04003493 Restriction r = restrictions.valueAt(i);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003494 pw.print(": mode="); pw.println(AppOpsManager.modeToName(r.mode));
John Spurlock1af30c72014-03-10 08:33:35 -04003495 if (!r.exceptionPackages.isEmpty()) {
3496 pw.println(" Exceptions:");
3497 for (int j=0; j<r.exceptionPackages.size(); j++) {
3498 pw.print(" "); pw.println(r.exceptionPackages.valueAt(j));
3499 }
3500 }
3501 }
3502 }
3503 }
Dianne Hackborne98f5db2013-07-17 17:23:25 -07003504 if (needSep) {
3505 pw.println();
3506 }
Svet Ganov2af57082015-07-30 08:44:20 -07003507 for (int i=0; i<mUidStates.size(); i++) {
3508 UidState uidState = mUidStates.valueAt(i);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003509 final SparseIntArray opModes = uidState.opModes;
3510 final ArrayMap<String, Ops> pkgOps = uidState.pkgOps;
3511
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003512 if (dumpOp >= 0 || dumpPackage != null || dumpMode >= 0) {
3513 boolean hasOp = dumpOp < 0 || (uidState.opModes != null
3514 && uidState.opModes.indexOfKey(dumpOp) >= 0);
3515 boolean hasPackage = dumpPackage == null;
3516 boolean hasMode = dumpMode < 0;
3517 if (!hasMode && opModes != null) {
3518 for (int opi = 0; !hasMode && opi < opModes.size(); opi++) {
3519 if (opModes.valueAt(opi) == dumpMode) {
3520 hasMode = true;
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003521 }
3522 }
3523 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003524 if (pkgOps != null) {
3525 for (int pkgi = 0;
3526 (!hasOp || !hasPackage || !hasMode) && pkgi < pkgOps.size();
3527 pkgi++) {
3528 Ops ops = pkgOps.valueAt(pkgi);
3529 if (!hasOp && ops != null && ops.indexOfKey(dumpOp) >= 0) {
3530 hasOp = true;
3531 }
3532 if (!hasMode) {
3533 for (int opi = 0; !hasMode && opi < ops.size(); opi++) {
3534 if (ops.valueAt(opi).mode == dumpMode) {
3535 hasMode = true;
3536 }
3537 }
3538 }
3539 if (!hasPackage && dumpPackage.equals(ops.packageName)) {
3540 hasPackage = true;
3541 }
3542 }
3543 }
3544 if (uidState.foregroundOps != null && !hasOp) {
3545 if (uidState.foregroundOps.indexOfKey(dumpOp) > 0) {
3546 hasOp = true;
3547 }
3548 }
3549 if (!hasOp || !hasPackage || !hasMode) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003550 continue;
3551 }
3552 }
Svet Ganov2af57082015-07-30 08:44:20 -07003553
3554 pw.print(" Uid "); UserHandle.formatUid(pw, uidState.uid); pw.println(":");
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003555 pw.print(" state=");
3556 pw.println(UID_STATE_NAMES[uidState.state]);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003557 if (uidState.state != uidState.pendingState) {
3558 pw.print(" pendingState=");
3559 pw.println(UID_STATE_NAMES[uidState.pendingState]);
3560 }
3561 if (uidState.pendingStateCommitTime != 0) {
3562 pw.print(" pendingStateCommitTime=");
Dianne Hackborn9fb93502018-06-18 12:29:44 -07003563 TimeUtils.formatDuration(uidState.pendingStateCommitTime, nowElapsed, pw);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003564 pw.println();
3565 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003566 if (uidState.startNesting != 0) {
3567 pw.print(" startNesting=");
3568 pw.println(uidState.startNesting);
3569 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003570 if (uidState.foregroundOps != null && (dumpMode < 0
3571 || dumpMode == AppOpsManager.MODE_FOREGROUND)) {
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003572 pw.println(" foregroundOps:");
3573 for (int j = 0; j < uidState.foregroundOps.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003574 if (dumpOp >= 0 && dumpOp != uidState.foregroundOps.keyAt(j)) {
3575 continue;
3576 }
3577 pw.print(" ");
3578 pw.print(AppOpsManager.opToName(uidState.foregroundOps.keyAt(j)));
3579 pw.print(": ");
3580 pw.println(uidState.foregroundOps.valueAt(j) ? "WATCHER" : "SILENT");
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003581 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003582 pw.print(" hasForegroundWatchers=");
3583 pw.println(uidState.hasForegroundWatchers);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003584 }
Svet Ganovee438d42017-01-19 18:04:38 -08003585 needSep = true;
Svet Ganov2af57082015-07-30 08:44:20 -07003586
Svet Ganov2af57082015-07-30 08:44:20 -07003587 if (opModes != null) {
3588 final int opModeCount = opModes.size();
3589 for (int j = 0; j < opModeCount; j++) {
3590 final int code = opModes.keyAt(j);
3591 final int mode = opModes.valueAt(j);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003592 if (dumpOp >= 0 && dumpOp != code) {
3593 continue;
3594 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003595 if (dumpMode >= 0 && dumpMode != mode) {
3596 continue;
3597 }
Svet Ganov2af57082015-07-30 08:44:20 -07003598 pw.print(" "); pw.print(AppOpsManager.opToName(code));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003599 pw.print(": mode="); pw.println(AppOpsManager.modeToName(mode));
Svet Ganov2af57082015-07-30 08:44:20 -07003600 }
3601 }
3602
Svet Ganov2af57082015-07-30 08:44:20 -07003603 if (pkgOps == null) {
3604 continue;
3605 }
3606
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003607 for (int pkgi = 0; pkgi < pkgOps.size(); pkgi++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003608 final Ops ops = pkgOps.valueAt(pkgi);
3609 if (dumpPackage != null && !dumpPackage.equals(ops.packageName)) {
3610 continue;
3611 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003612 boolean printedPackage = false;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003613 for (int j=0; j<ops.size(); j++) {
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003614 final Op op = ops.valueAt(j);
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003615 if (dumpOp >= 0 && dumpOp != op.op) {
3616 continue;
3617 }
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003618 if (dumpMode >= 0 && dumpMode != op.mode) {
3619 continue;
3620 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003621 if (!printedPackage) {
3622 pw.print(" Package "); pw.print(ops.packageName); pw.println(":");
3623 printedPackage = true;
3624 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003625 pw.print(" "); pw.print(AppOpsManager.opToName(op.op));
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003626 pw.print(" ("); pw.print(AppOpsManager.modeToName(op.mode));
Dianne Hackborn65a4f252018-05-08 17:30:48 -07003627 final int switchOp = AppOpsManager.opToSwitch(op.op);
3628 if (switchOp != op.op) {
3629 pw.print(" / switch ");
3630 pw.print(AppOpsManager.opToName(switchOp));
3631 final Op switchObj = ops.get(switchOp);
3632 int mode = switchObj != null
3633 ? switchObj.mode : AppOpsManager.opToDefaultMode(switchOp);
3634 pw.print("="); pw.print(AppOpsManager.modeToName(mode));
3635 }
Dianne Hackborn2378a4a2018-04-26 13:46:22 -07003636 pw.println("): ");
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003637 dumpTimesLocked(pw,
3638 " Access: ",
3639 " ", op.time, now, sdf, date);
3640 dumpTimesLocked(pw,
3641 " Reject: ",
3642 " ", op.rejectTime, now, sdf, date);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003643 if (op.duration == -1) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003644 pw.print(" Running start at: ");
3645 TimeUtils.formatDuration(nowElapsed-op.startRealtime, pw);
3646 pw.println();
Dianne Hackborn7b7c58b2014-12-02 18:32:20 -08003647 } else if (op.duration != 0) {
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003648 pw.print(" duration=");
3649 TimeUtils.formatDuration(op.duration, pw);
3650 pw.println();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003651 }
Dianne Hackborncd1f30b2018-04-23 17:38:09 -07003652 if (op.startNesting != 0) {
3653 pw.print(" startNesting=");
3654 pw.println(op.startNesting);
3655 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003656 }
3657 }
3658 }
Svet Ganovee438d42017-01-19 18:04:38 -08003659 if (needSep) {
3660 pw.println();
3661 }
3662
3663 final int userRestrictionCount = mOpUserRestrictions.size();
3664 for (int i = 0; i < userRestrictionCount; i++) {
3665 IBinder token = mOpUserRestrictions.keyAt(i);
3666 ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
3667 pw.println(" User restrictions for token " + token + ":");
3668
3669 final int restrictionCount = restrictionState.perUserRestrictions != null
3670 ? restrictionState.perUserRestrictions.size() : 0;
3671 if (restrictionCount > 0) {
3672 pw.println(" Restricted ops:");
3673 for (int j = 0; j < restrictionCount; j++) {
3674 int userId = restrictionState.perUserRestrictions.keyAt(j);
3675 boolean[] restrictedOps = restrictionState.perUserRestrictions.valueAt(j);
3676 if (restrictedOps == null) {
3677 continue;
3678 }
3679 StringBuilder restrictedOpsValue = new StringBuilder();
3680 restrictedOpsValue.append("[");
3681 final int restrictedOpCount = restrictedOps.length;
3682 for (int k = 0; k < restrictedOpCount; k++) {
3683 if (restrictedOps[k]) {
3684 if (restrictedOpsValue.length() > 1) {
3685 restrictedOpsValue.append(", ");
3686 }
3687 restrictedOpsValue.append(AppOpsManager.opToName(k));
3688 }
3689 }
3690 restrictedOpsValue.append("]");
3691 pw.print(" "); pw.print("user: "); pw.print(userId);
3692 pw.print(" restricted ops: "); pw.println(restrictedOpsValue);
3693 }
3694 }
3695
3696 final int excludedPackageCount = restrictionState.perUserExcludedPackages != null
3697 ? restrictionState.perUserExcludedPackages.size() : 0;
3698 if (excludedPackageCount > 0) {
3699 pw.println(" Excluded packages:");
3700 for (int j = 0; j < excludedPackageCount; j++) {
3701 int userId = restrictionState.perUserExcludedPackages.keyAt(j);
3702 String[] packageNames = restrictionState.perUserExcludedPackages.valueAt(j);
3703 pw.print(" "); pw.print("user: "); pw.print(userId);
3704 pw.print(" packages: "); pw.println(Arrays.toString(packageNames));
3705 }
3706 }
3707 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08003708 }
3709 }
John Spurlock1af30c72014-03-10 08:33:35 -04003710
3711 private static final class Restriction {
3712 private static final ArraySet<String> NO_EXCEPTIONS = new ArraySet<String>();
3713 int mode;
3714 ArraySet<String> exceptionPackages = NO_EXCEPTIONS;
3715 }
Jason Monk62062992014-05-06 09:55:28 -04003716
3717 @Override
Svet Ganov9cea80cd2016-02-16 11:47:00 -08003718 public void setUserRestrictions(Bundle restrictions, IBinder token, int userHandle) {
Jason Monk62062992014-05-06 09:55:28 -04003719 checkSystemUid("setUserRestrictions");
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00003720 Preconditions.checkNotNull(restrictions);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08003721 Preconditions.checkNotNull(token);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07003722 for (int i = 0; i < AppOpsManager._NUM_OP; i++) {
Jason Monk62062992014-05-06 09:55:28 -04003723 String restriction = AppOpsManager.opToRestriction(i);
Suprabh Shukla64e0dcb2016-05-24 16:23:11 -07003724 if (restriction != null) {
3725 setUserRestrictionNoCheck(i, restrictions.getBoolean(restriction, false), token,
3726 userHandle, null);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07003727 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08003728 }
3729 }
3730
3731 @Override
Ruben Brunk29931bc2016-03-11 00:24:26 -08003732 public void setUserRestriction(int code, boolean restricted, IBinder token, int userHandle,
3733 String[] exceptionPackages) {
Svet Ganov9cea80cd2016-02-16 11:47:00 -08003734 if (Binder.getCallingPid() != Process.myPid()) {
3735 mContext.enforcePermission(Manifest.permission.MANAGE_APP_OPS_RESTRICTIONS,
3736 Binder.getCallingPid(), Binder.getCallingUid(), null);
3737 }
3738 if (userHandle != UserHandle.getCallingUserId()) {
3739 if (mContext.checkCallingOrSelfPermission(Manifest.permission
3740 .INTERACT_ACROSS_USERS_FULL) != PackageManager.PERMISSION_GRANTED
3741 && mContext.checkCallingOrSelfPermission(Manifest.permission
3742 .INTERACT_ACROSS_USERS) != PackageManager.PERMISSION_GRANTED) {
3743 throw new SecurityException("Need INTERACT_ACROSS_USERS_FULL or"
3744 + " INTERACT_ACROSS_USERS to interact cross user ");
Jason Monk62062992014-05-06 09:55:28 -04003745 }
3746 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08003747 verifyIncomingOp(code);
3748 Preconditions.checkNotNull(token);
Ruben Brunk29931bc2016-03-11 00:24:26 -08003749 setUserRestrictionNoCheck(code, restricted, token, userHandle, exceptionPackages);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08003750 }
3751
3752 private void setUserRestrictionNoCheck(int code, boolean restricted, IBinder token,
Ruben Brunk29931bc2016-03-11 00:24:26 -08003753 int userHandle, String[] exceptionPackages) {
Svet Ganov442ed572016-08-17 17:29:43 -07003754 synchronized (AppOpsService.this) {
3755 ClientRestrictionState restrictionState = mOpUserRestrictions.get(token);
3756
3757 if (restrictionState == null) {
3758 try {
3759 restrictionState = new ClientRestrictionState(token);
3760 } catch (RemoteException e) {
3761 return;
3762 }
3763 mOpUserRestrictions.put(token, restrictionState);
Ruben Brunk29931bc2016-03-11 00:24:26 -08003764 }
Svet Ganov442ed572016-08-17 17:29:43 -07003765
3766 if (restrictionState.setRestriction(code, restricted, exceptionPackages, userHandle)) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003767 mHandler.sendMessage(PooledLambda.obtainMessage(
Svet Ganov3a95f832018-03-23 17:44:30 -07003768 AppOpsService::notifyWatchersOfChange, this, code, UID_ANY));
Svet Ganov442ed572016-08-17 17:29:43 -07003769 }
3770
3771 if (restrictionState.isDefault()) {
3772 mOpUserRestrictions.remove(token);
3773 restrictionState.destroy();
3774 }
Ruben Brunk29931bc2016-03-11 00:24:26 -08003775 }
Julia Reynoldsbb21c252016-04-05 16:01:49 -04003776 }
3777
Svet Ganov3a95f832018-03-23 17:44:30 -07003778 private void notifyWatchersOfChange(int code, int uid) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003779 final ArraySet<ModeCallback> clonedCallbacks;
Svet Ganov9cea80cd2016-02-16 11:47:00 -08003780 synchronized (this) {
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003781 ArraySet<ModeCallback> callbacks = mOpModeWatchers.get(code);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08003782 if (callbacks == null) {
3783 return;
3784 }
Dianne Hackborn68d76552017-02-27 15:32:03 -08003785 clonedCallbacks = new ArraySet<>(callbacks);
Svet Ganov9cea80cd2016-02-16 11:47:00 -08003786 }
3787
Svet Ganov3a95f832018-03-23 17:44:30 -07003788 notifyOpChanged(clonedCallbacks, code, uid, null);
Jason Monk62062992014-05-06 09:55:28 -04003789 }
3790
3791 @Override
3792 public void removeUser(int userHandle) throws RemoteException {
3793 checkSystemUid("removeUser");
Svet Ganov442ed572016-08-17 17:29:43 -07003794 synchronized (AppOpsService.this) {
3795 final int tokenCount = mOpUserRestrictions.size();
3796 for (int i = tokenCount - 1; i >= 0; i--) {
3797 ClientRestrictionState opRestrictions = mOpUserRestrictions.valueAt(i);
3798 opRestrictions.removeUser(userHandle);
3799 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07003800 removeUidsForUserLocked(userHandle);
3801 }
3802 }
3803
Jeff Sharkey35e46d22017-06-09 10:01:20 -06003804 @Override
3805 public boolean isOperationActive(int code, int uid, String packageName) {
Svet Ganovf7b47252018-02-26 11:11:27 -08003806 if (Binder.getCallingUid() != uid) {
3807 if (mContext.checkCallingOrSelfPermission(Manifest.permission.WATCH_APPOPS)
3808 != PackageManager.PERMISSION_GRANTED) {
3809 return false;
3810 }
3811 }
Jeff Sharkey35e46d22017-06-09 10:01:20 -06003812 verifyIncomingOp(code);
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003813 final String resolvedPackageName = resolvePackageName(uid, packageName);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06003814 if (resolvedPackageName == null) {
3815 return false;
3816 }
Svetoslav Ganov2d20fb42018-02-08 15:52:10 -08003817 synchronized (AppOpsService.this) {
Jeff Sharkey35e46d22017-06-09 10:01:20 -06003818 for (int i = mClients.size() - 1; i >= 0; i--) {
3819 final ClientState client = mClients.valueAt(i);
Jeff Sharkey35e46d22017-06-09 10:01:20 -06003820 for (int j = client.mStartedOps.size() - 1; j >= 0; j--) {
3821 final Op op = client.mStartedOps.get(j);
3822 if (op.op == code && op.uid == uid) return true;
3823 }
3824 }
3825 }
3826 return false;
3827 }
3828
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07003829 private void removeUidsForUserLocked(int userHandle) {
3830 for (int i = mUidStates.size() - 1; i >= 0; --i) {
3831 final int uid = mUidStates.keyAt(i);
3832 if (UserHandle.getUserId(uid) == userHandle) {
3833 mUidStates.removeAt(i);
3834 }
Svet Ganov9cea80cd2016-02-16 11:47:00 -08003835 }
3836 }
3837
Jason Monk62062992014-05-06 09:55:28 -04003838 private void checkSystemUid(String function) {
3839 int uid = Binder.getCallingUid();
3840 if (uid != Process.SYSTEM_UID) {
3841 throw new SecurityException(function + " must by called by the system");
3842 }
3843 }
3844
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00003845 private static String resolvePackageName(int uid, String packageName) {
Svet Ganov82f09bc2018-01-12 22:08:40 -08003846 if (uid == Process.ROOT_UID) {
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00003847 return "root";
3848 } else if (uid == Process.SHELL_UID) {
3849 return "com.android.shell";
Svet Ganov82f09bc2018-01-12 22:08:40 -08003850 } else if (uid == Process.MEDIA_UID) {
3851 return "media";
3852 } else if (uid == Process.AUDIOSERVER_UID) {
3853 return "audioserver";
3854 } else if (uid == Process.CAMERASERVER_UID) {
3855 return "cameraserver";
Svetoslav Ganovf73adb62016-03-29 01:07:06 +00003856 } else if (uid == Process.SYSTEM_UID && packageName == null) {
3857 return "android";
3858 }
3859 return packageName;
3860 }
3861
Svet Ganov82f09bc2018-01-12 22:08:40 -08003862 private static int resolveUid(String packageName) {
3863 if (packageName == null) {
3864 return -1;
3865 }
3866 switch (packageName) {
3867 case "root":
3868 return Process.ROOT_UID;
3869 case "shell":
3870 return Process.SHELL_UID;
3871 case "media":
3872 return Process.MEDIA_UID;
3873 case "audioserver":
3874 return Process.AUDIOSERVER_UID;
3875 case "cameraserver":
3876 return Process.CAMERASERVER_UID;
3877 }
3878 return -1;
3879 }
3880
Svet Ganov2af57082015-07-30 08:44:20 -07003881 private static String[] getPackagesForUid(int uid) {
Svet Ganovf3807aa2015-08-02 10:09:56 -07003882 String[] packageNames = null;
Svet Ganov2af57082015-07-30 08:44:20 -07003883 try {
riddle_hsu40b300f2015-11-23 13:22:03 +08003884 packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
Svet Ganov2af57082015-07-30 08:44:20 -07003885 } catch (RemoteException e) {
3886 /* ignore - local call */
3887 }
Svet Ganovf3807aa2015-08-02 10:09:56 -07003888 if (packageNames == null) {
3889 return EmptyArray.STRING;
3890 }
3891 return packageNames;
Svet Ganov2af57082015-07-30 08:44:20 -07003892 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07003893
3894 private final class ClientRestrictionState implements DeathRecipient {
3895 private final IBinder token;
3896 SparseArray<boolean[]> perUserRestrictions;
3897 SparseArray<String[]> perUserExcludedPackages;
3898
3899 public ClientRestrictionState(IBinder token)
3900 throws RemoteException {
3901 token.linkToDeath(this, 0);
3902 this.token = token;
3903 }
3904
3905 public boolean setRestriction(int code, boolean restricted,
3906 String[] excludedPackages, int userId) {
3907 boolean changed = false;
3908
3909 if (perUserRestrictions == null && restricted) {
3910 perUserRestrictions = new SparseArray<>();
3911 }
3912
Philip P. Moltmanne683f192017-06-23 14:05:04 -07003913 int[] users;
3914 if (userId == UserHandle.USER_ALL) {
3915 List<UserInfo> liveUsers = UserManager.get(mContext).getUsers(false);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07003916
Philip P. Moltmanne683f192017-06-23 14:05:04 -07003917 users = new int[liveUsers.size()];
3918 for (int i = 0; i < liveUsers.size(); i++) {
3919 users[i] = liveUsers.get(i).id;
3920 }
3921 } else {
3922 users = new int[]{userId};
3923 }
3924
3925 if (perUserRestrictions != null) {
3926 int numUsers = users.length;
3927
3928 for (int i = 0; i < numUsers; i++) {
3929 int thisUserId = users[i];
3930
3931 boolean[] userRestrictions = perUserRestrictions.get(thisUserId);
3932 if (userRestrictions == null && restricted) {
3933 userRestrictions = new boolean[AppOpsManager._NUM_OP];
3934 perUserRestrictions.put(thisUserId, userRestrictions);
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07003935 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07003936 if (userRestrictions != null && userRestrictions[code] != restricted) {
3937 userRestrictions[code] = restricted;
3938 if (!restricted && isDefault(userRestrictions)) {
3939 perUserRestrictions.remove(thisUserId);
3940 userRestrictions = null;
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07003941 }
3942 changed = true;
3943 }
Philip P. Moltmanne683f192017-06-23 14:05:04 -07003944
3945 if (userRestrictions != null) {
3946 final boolean noExcludedPackages = ArrayUtils.isEmpty(excludedPackages);
3947 if (perUserExcludedPackages == null && !noExcludedPackages) {
3948 perUserExcludedPackages = new SparseArray<>();
3949 }
3950 if (perUserExcludedPackages != null && !Arrays.equals(excludedPackages,
3951 perUserExcludedPackages.get(thisUserId))) {
3952 if (noExcludedPackages) {
3953 perUserExcludedPackages.remove(thisUserId);
3954 if (perUserExcludedPackages.size() <= 0) {
3955 perUserExcludedPackages = null;
3956 }
3957 } else {
3958 perUserExcludedPackages.put(thisUserId, excludedPackages);
3959 }
3960 changed = true;
3961 }
3962 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07003963 }
3964 }
3965
3966 return changed;
3967 }
3968
3969 public boolean hasRestriction(int restriction, String packageName, int userId) {
3970 if (perUserRestrictions == null) {
3971 return false;
3972 }
3973 boolean[] restrictions = perUserRestrictions.get(userId);
3974 if (restrictions == null) {
3975 return false;
3976 }
3977 if (!restrictions[restriction]) {
3978 return false;
3979 }
3980 if (perUserExcludedPackages == null) {
3981 return true;
3982 }
3983 String[] perUserExclusions = perUserExcludedPackages.get(userId);
3984 if (perUserExclusions == null) {
3985 return true;
3986 }
3987 return !ArrayUtils.contains(perUserExclusions, packageName);
3988 }
3989
3990 public void removeUser(int userId) {
3991 if (perUserExcludedPackages != null) {
3992 perUserExcludedPackages.remove(userId);
3993 if (perUserExcludedPackages.size() <= 0) {
3994 perUserExcludedPackages = null;
3995 }
3996 }
Sudheer Shankabc2fadd2016-09-27 17:36:39 -07003997 if (perUserRestrictions != null) {
3998 perUserRestrictions.remove(userId);
3999 if (perUserRestrictions.size() <= 0) {
4000 perUserRestrictions = null;
4001 }
4002 }
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004003 }
4004
4005 public boolean isDefault() {
4006 return perUserRestrictions == null || perUserRestrictions.size() <= 0;
4007 }
4008
4009 @Override
4010 public void binderDied() {
4011 synchronized (AppOpsService.this) {
4012 mOpUserRestrictions.remove(token);
4013 if (perUserRestrictions == null) {
4014 return;
4015 }
4016 final int userCount = perUserRestrictions.size();
4017 for (int i = 0; i < userCount; i++) {
4018 final boolean[] restrictions = perUserRestrictions.valueAt(i);
4019 final int restrictionCount = restrictions.length;
4020 for (int j = 0; j < restrictionCount; j++) {
4021 if (restrictions[j]) {
4022 final int changedCode = j;
Svet Ganov3a95f832018-03-23 17:44:30 -07004023 mHandler.post(() -> notifyWatchersOfChange(changedCode, UID_ANY));
Svetoslav Ganova8bbd762016-05-13 17:08:16 -07004024 }
4025 }
4026 }
4027 destroy();
4028 }
4029 }
4030
4031 public void destroy() {
4032 token.unlinkToDeath(this, 0);
4033 }
4034
4035 private boolean isDefault(boolean[] array) {
4036 if (ArrayUtils.isEmpty(array)) {
4037 return true;
4038 }
4039 for (boolean value : array) {
4040 if (value) {
4041 return false;
4042 }
4043 }
4044 return true;
4045 }
4046 }
Dianne Hackbornd5254412018-05-11 18:02:58 -07004047
4048 private final class AppOpsManagerInternalImpl extends AppOpsManagerInternal {
4049 @Override public void setDeviceAndProfileOwners(SparseIntArray owners) {
4050 synchronized (AppOpsService.this) {
4051 mProfileOwners = owners;
4052 }
4053 }
Philip P. Moltmann17f65af2018-10-18 15:32:29 -07004054
4055 @Override
4056 public void setMode(int code, int uid, @NonNull String packageName, int mode,
4057 boolean isPrivileged) {
4058 AppOpsService.this.setMode(code, uid, packageName, mode, false, isPrivileged);
4059 }
Dianne Hackbornd5254412018-05-11 18:02:58 -07004060 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004061}