AppOpsManager.java revision 6b590c3934c6663e647909fbdcabc1d42a125547
1/*
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 android.app;
18
19import android.Manifest;
20import android.annotation.NonNull;
21import android.annotation.RequiresPermission;
22import android.annotation.SystemApi;
23import android.annotation.SystemService;
24import android.annotation.TestApi;
25import android.app.usage.UsageStatsManager;
26import android.content.Context;
27import android.media.AudioAttributes.AttributeUsage;
28import android.os.Binder;
29import android.os.IBinder;
30import android.os.Parcel;
31import android.os.Parcelable;
32import android.os.Process;
33import android.os.RemoteException;
34import android.os.UserManager;
35import android.util.ArrayMap;
36
37import com.android.internal.app.IAppOpsActiveCallback;
38import com.android.internal.app.IAppOpsCallback;
39import com.android.internal.app.IAppOpsService;
40import com.android.internal.util.Preconditions;
41
42import java.util.ArrayList;
43import java.util.Arrays;
44import java.util.HashMap;
45import java.util.List;
46
47/**
48 * API for interacting with "application operation" tracking.
49 *
50 * <p>This API is not generally intended for third party application developers; most
51 * features are only available to system applications.
52 */
53@SystemService(Context.APP_OPS_SERVICE)
54public class AppOpsManager {
55    /**
56     * <p>App ops allows callers to:</p>
57     *
58     * <ul>
59     * <li> Note when operations are happening, and find out if they are allowed for the current
60     * caller.</li>
61     * <li> Disallow specific apps from doing specific operations.</li>
62     * <li> Collect all of the current information about operations that have been executed or
63     * are not being allowed.</li>
64     * <li> Monitor for changes in whether an operation is allowed.</li>
65     * </ul>
66     *
67     * <p>Each operation is identified by a single integer; these integers are a fixed set of
68     * operations, enumerated by the OP_* constants.
69     *
70     * <p></p>When checking operations, the result is a "mode" integer indicating the current
71     * setting for the operation under that caller: MODE_ALLOWED, MODE_IGNORED (don't execute
72     * the operation but fake its behavior enough so that the caller doesn't crash),
73     * MODE_ERRORED (throw a SecurityException back to the caller; the normal operation calls
74     * will do this for you).
75     */
76
77    final Context mContext;
78    final IAppOpsService mService;
79    final ArrayMap<OnOpChangedListener, IAppOpsCallback> mModeWatchers = new ArrayMap<>();
80    final ArrayMap<OnOpActiveChangedListener, IAppOpsActiveCallback> mActiveWatchers =
81            new ArrayMap<>();
82
83    static IBinder sToken;
84
85    /**
86     * Result from {@link #checkOp}, {@link #noteOp}, {@link #startOp}: the given caller is
87     * allowed to perform the given operation.
88     */
89    public static final int MODE_ALLOWED = 0;
90
91    /**
92     * Result from {@link #checkOp}, {@link #noteOp}, {@link #startOp}: the given caller is
93     * not allowed to perform the given operation, and this attempt should
94     * <em>silently fail</em> (it should not cause the app to crash).
95     */
96    public static final int MODE_IGNORED = 1;
97
98    /**
99     * Result from {@link #checkOpNoThrow}, {@link #noteOpNoThrow}, {@link #startOpNoThrow}: the
100     * given caller is not allowed to perform the given operation, and this attempt should
101     * cause it to have a fatal error, typically a {@link SecurityException}.
102     */
103    public static final int MODE_ERRORED = 2;
104
105    /**
106     * Result from {@link #checkOp}, {@link #noteOp}, {@link #startOp}: the given caller should
107     * use its default security check.  This mode is not normally used; it should only be used
108     * with appop permissions, and callers must explicitly check for it and deal with it.
109     */
110    public static final int MODE_DEFAULT = 3;
111
112    /**
113     * Special mode that means "allow only when app is in foreground."  This is <b>not</b>
114     * returned from {@link #checkOp}, {@link #noteOp}, {@link #startOp}; rather, when this
115     * mode is set, these functions will return {@link #MODE_ALLOWED} when the app being
116     * checked is currently in the foreground, otherwise {@link #MODE_IGNORED}.
117     * @hide
118     */
119    public static final int MODE_FOREGROUND = 4;
120
121
122    /**
123     * @hide
124     */
125    public static final String[] MODE_NAMES = new String[] {
126            "allow",        // MODE_ALLOWED
127            "ignore",       // MODE_IGNORED
128            "deny",         // MODE_ERRORED
129            "default",      // MODE_DEFAULT
130            "foreground",   // MODE_FOREGROUND
131    };
132
133    /**
134     * Metrics about an op when its uid is persistent.
135     * @hide
136     */
137    public static final int UID_STATE_PERSISTENT = 0;
138
139    /**
140     * Metrics about an op when its uid is at the top.
141     * @hide
142     */
143    public static final int UID_STATE_TOP = 1;
144
145    /**
146     * Metrics about an op when its uid is running a foreground service.
147     * @hide
148     */
149    public static final int UID_STATE_FOREGROUND_SERVICE = 2;
150
151    /**
152     * Metrics about an op when its uid is in the foreground for any other reasons.
153     * @hide
154     */
155    public static final int UID_STATE_FOREGROUND = 3;
156
157    /**
158     * Metrics about an op when its uid is in the background for any reason.
159     * @hide
160     */
161    public static final int UID_STATE_BACKGROUND = 4;
162
163    /**
164     * Metrics about an op when its uid is cached.
165     * @hide
166     */
167    public static final int UID_STATE_CACHED = 5;
168
169    /**
170     * Number of uid states we track.
171     * @hide
172     */
173    public static final int _NUM_UID_STATE = 6;
174
175    // when adding one of these:
176    //  - increment _NUM_OP
177    //  - define an OPSTR_* constant (marked as @SystemApi)
178    //  - add rows to sOpToSwitch, sOpToString, sOpNames, sOpToPerms, sOpDefault
179    //  - add descriptive strings to Settings/res/values/arrays.xml
180    //  - add the op to the appropriate template in AppOpsState.OpsTemplate (settings app)
181
182    /** @hide No operation specified. */
183    public static final int OP_NONE = -1;
184    /** @hide Access to coarse location information. */
185    public static final int OP_COARSE_LOCATION = 0;
186    /** @hide Access to fine location information. */
187    public static final int OP_FINE_LOCATION = 1;
188    /** @hide Causing GPS to run. */
189    public static final int OP_GPS = 2;
190    /** @hide */
191    public static final int OP_VIBRATE = 3;
192    /** @hide */
193    public static final int OP_READ_CONTACTS = 4;
194    /** @hide */
195    public static final int OP_WRITE_CONTACTS = 5;
196    /** @hide */
197    public static final int OP_READ_CALL_LOG = 6;
198    /** @hide */
199    public static final int OP_WRITE_CALL_LOG = 7;
200    /** @hide */
201    public static final int OP_READ_CALENDAR = 8;
202    /** @hide */
203    public static final int OP_WRITE_CALENDAR = 9;
204    /** @hide */
205    public static final int OP_WIFI_SCAN = 10;
206    /** @hide */
207    public static final int OP_POST_NOTIFICATION = 11;
208    /** @hide */
209    public static final int OP_NEIGHBORING_CELLS = 12;
210    /** @hide */
211    public static final int OP_CALL_PHONE = 13;
212    /** @hide */
213    public static final int OP_READ_SMS = 14;
214    /** @hide */
215    public static final int OP_WRITE_SMS = 15;
216    /** @hide */
217    public static final int OP_RECEIVE_SMS = 16;
218    /** @hide */
219    public static final int OP_RECEIVE_EMERGECY_SMS = 17;
220    /** @hide */
221    public static final int OP_RECEIVE_MMS = 18;
222    /** @hide */
223    public static final int OP_RECEIVE_WAP_PUSH = 19;
224    /** @hide */
225    public static final int OP_SEND_SMS = 20;
226    /** @hide */
227    public static final int OP_READ_ICC_SMS = 21;
228    /** @hide */
229    public static final int OP_WRITE_ICC_SMS = 22;
230    /** @hide */
231    public static final int OP_WRITE_SETTINGS = 23;
232    /** @hide Required to draw on top of other apps. */
233    @TestApi
234    public static final int OP_SYSTEM_ALERT_WINDOW = 24;
235    /** @hide */
236    public static final int OP_ACCESS_NOTIFICATIONS = 25;
237    /** @hide */
238    public static final int OP_CAMERA = 26;
239    /** @hide */
240    @TestApi
241    public static final int OP_RECORD_AUDIO = 27;
242    /** @hide */
243    public static final int OP_PLAY_AUDIO = 28;
244    /** @hide */
245    public static final int OP_READ_CLIPBOARD = 29;
246    /** @hide */
247    public static final int OP_WRITE_CLIPBOARD = 30;
248    /** @hide */
249    public static final int OP_TAKE_MEDIA_BUTTONS = 31;
250    /** @hide */
251    public static final int OP_TAKE_AUDIO_FOCUS = 32;
252    /** @hide */
253    public static final int OP_AUDIO_MASTER_VOLUME = 33;
254    /** @hide */
255    public static final int OP_AUDIO_VOICE_VOLUME = 34;
256    /** @hide */
257    public static final int OP_AUDIO_RING_VOLUME = 35;
258    /** @hide */
259    public static final int OP_AUDIO_MEDIA_VOLUME = 36;
260    /** @hide */
261    public static final int OP_AUDIO_ALARM_VOLUME = 37;
262    /** @hide */
263    public static final int OP_AUDIO_NOTIFICATION_VOLUME = 38;
264    /** @hide */
265    public static final int OP_AUDIO_BLUETOOTH_VOLUME = 39;
266    /** @hide */
267    public static final int OP_WAKE_LOCK = 40;
268    /** @hide Continually monitoring location data. */
269    public static final int OP_MONITOR_LOCATION = 41;
270    /** @hide Continually monitoring location data with a relatively high power request. */
271    public static final int OP_MONITOR_HIGH_POWER_LOCATION = 42;
272    /** @hide Retrieve current usage stats via {@link UsageStatsManager}. */
273    public static final int OP_GET_USAGE_STATS = 43;
274    /** @hide */
275    public static final int OP_MUTE_MICROPHONE = 44;
276    /** @hide */
277    public static final int OP_TOAST_WINDOW = 45;
278    /** @hide Capture the device's display contents and/or audio */
279    public static final int OP_PROJECT_MEDIA = 46;
280    /** @hide Activate a VPN connection without user intervention. */
281    public static final int OP_ACTIVATE_VPN = 47;
282    /** @hide Access the WallpaperManagerAPI to write wallpapers. */
283    public static final int OP_WRITE_WALLPAPER = 48;
284    /** @hide Received the assist structure from an app. */
285    public static final int OP_ASSIST_STRUCTURE = 49;
286    /** @hide Received a screenshot from assist. */
287    public static final int OP_ASSIST_SCREENSHOT = 50;
288    /** @hide Read the phone state. */
289    public static final int OP_READ_PHONE_STATE = 51;
290    /** @hide Add voicemail messages to the voicemail content provider. */
291    public static final int OP_ADD_VOICEMAIL = 52;
292    /** @hide Access APIs for SIP calling over VOIP or WiFi. */
293    public static final int OP_USE_SIP = 53;
294    /** @hide Intercept outgoing calls. */
295    public static final int OP_PROCESS_OUTGOING_CALLS = 54;
296    /** @hide User the fingerprint API. */
297    public static final int OP_USE_FINGERPRINT = 55;
298    /** @hide Access to body sensors such as heart rate, etc. */
299    public static final int OP_BODY_SENSORS = 56;
300    /** @hide Read previously received cell broadcast messages. */
301    public static final int OP_READ_CELL_BROADCASTS = 57;
302    /** @hide Inject mock location into the system. */
303    public static final int OP_MOCK_LOCATION = 58;
304    /** @hide Read external storage. */
305    public static final int OP_READ_EXTERNAL_STORAGE = 59;
306    /** @hide Write external storage. */
307    public static final int OP_WRITE_EXTERNAL_STORAGE = 60;
308    /** @hide Turned on the screen. */
309    public static final int OP_TURN_SCREEN_ON = 61;
310    /** @hide Get device accounts. */
311    public static final int OP_GET_ACCOUNTS = 62;
312    /** @hide Control whether an application is allowed to run in the background. */
313    public static final int OP_RUN_IN_BACKGROUND = 63;
314    /** @hide */
315    public static final int OP_AUDIO_ACCESSIBILITY_VOLUME = 64;
316    /** @hide Read the phone number. */
317    public static final int OP_READ_PHONE_NUMBERS = 65;
318    /** @hide Request package installs through package installer */
319    public static final int OP_REQUEST_INSTALL_PACKAGES = 66;
320    /** @hide Enter picture-in-picture. */
321    public static final int OP_PICTURE_IN_PICTURE = 67;
322    /** @hide Instant app start foreground service. */
323    public static final int OP_INSTANT_APP_START_FOREGROUND = 68;
324    /** @hide Answer incoming phone calls */
325    public static final int OP_ANSWER_PHONE_CALLS = 69;
326    /** @hide Run jobs when in background */
327    public static final int OP_RUN_ANY_IN_BACKGROUND = 70;
328    /** @hide Change Wi-Fi connectivity state */
329    public static final int OP_CHANGE_WIFI_STATE = 71;
330    /** @hide Request package deletion through package installer */
331    public static final int OP_REQUEST_DELETE_PACKAGES = 72;
332    /** @hide Bind an accessibility service. */
333    public static final int OP_BIND_ACCESSIBILITY_SERVICE = 73;
334    /** @hide Continue handover of a call from another app */
335    public static final int OP_ACCEPT_HANDOVER = 74;
336    /** @hide Create and Manage IPsec Tunnels */
337    public static final int OP_MANAGE_IPSEC_TUNNELS = 75;
338    /** @hide Any app start foreground service. */
339    public static final int OP_START_FOREGROUND = 76;
340    /** @hide */
341    public static final int OP_BLUETOOTH_SCAN = 77;
342    /** @hide */
343    public static final int _NUM_OP = 78;
344
345    /** Access to coarse location information. */
346    public static final String OPSTR_COARSE_LOCATION = "android:coarse_location";
347    /** Access to fine location information. */
348    public static final String OPSTR_FINE_LOCATION =
349            "android:fine_location";
350    /** Continually monitoring location data. */
351    public static final String OPSTR_MONITOR_LOCATION
352            = "android:monitor_location";
353    /** Continually monitoring location data with a relatively high power request. */
354    public static final String OPSTR_MONITOR_HIGH_POWER_LOCATION
355            = "android:monitor_location_high_power";
356    /** Access to {@link android.app.usage.UsageStatsManager}. */
357    public static final String OPSTR_GET_USAGE_STATS
358            = "android:get_usage_stats";
359    /** Activate a VPN connection without user intervention. @hide */
360    @SystemApi @TestApi
361    public static final String OPSTR_ACTIVATE_VPN
362            = "android:activate_vpn";
363    /** Allows an application to read the user's contacts data. */
364    public static final String OPSTR_READ_CONTACTS
365            = "android:read_contacts";
366    /** Allows an application to write to the user's contacts data. */
367    public static final String OPSTR_WRITE_CONTACTS
368            = "android:write_contacts";
369    /** Allows an application to read the user's call log. */
370    public static final String OPSTR_READ_CALL_LOG
371            = "android:read_call_log";
372    /** Allows an application to write to the user's call log. */
373    public static final String OPSTR_WRITE_CALL_LOG
374            = "android:write_call_log";
375    /** Allows an application to read the user's calendar data. */
376    public static final String OPSTR_READ_CALENDAR
377            = "android:read_calendar";
378    /** Allows an application to write to the user's calendar data. */
379    public static final String OPSTR_WRITE_CALENDAR
380            = "android:write_calendar";
381    /** Allows an application to initiate a phone call. */
382    public static final String OPSTR_CALL_PHONE
383            = "android:call_phone";
384    /** Allows an application to read SMS messages. */
385    public static final String OPSTR_READ_SMS
386            = "android:read_sms";
387    /** Allows an application to receive SMS messages. */
388    public static final String OPSTR_RECEIVE_SMS
389            = "android:receive_sms";
390    /** Allows an application to receive MMS messages. */
391    public static final String OPSTR_RECEIVE_MMS
392            = "android:receive_mms";
393    /** Allows an application to receive WAP push messages. */
394    public static final String OPSTR_RECEIVE_WAP_PUSH
395            = "android:receive_wap_push";
396    /** Allows an application to send SMS messages. */
397    public static final String OPSTR_SEND_SMS
398            = "android:send_sms";
399    /** Required to be able to access the camera device. */
400    public static final String OPSTR_CAMERA
401            = "android:camera";
402    /** Required to be able to access the microphone device. */
403    public static final String OPSTR_RECORD_AUDIO
404            = "android:record_audio";
405    /** Required to access phone state related information. */
406    public static final String OPSTR_READ_PHONE_STATE
407            = "android:read_phone_state";
408    /** Required to access phone state related information. */
409    public static final String OPSTR_ADD_VOICEMAIL
410            = "android:add_voicemail";
411    /** Access APIs for SIP calling over VOIP or WiFi */
412    public static final String OPSTR_USE_SIP
413            = "android:use_sip";
414    /** Access APIs for diverting outgoing calls */
415    public static final String OPSTR_PROCESS_OUTGOING_CALLS
416            = "android:process_outgoing_calls";
417    /** Use the fingerprint API. */
418    public static final String OPSTR_USE_FINGERPRINT
419            = "android:use_fingerprint";
420    /** Access to body sensors such as heart rate, etc. */
421    public static final String OPSTR_BODY_SENSORS
422            = "android:body_sensors";
423    /** Read previously received cell broadcast messages. */
424    public static final String OPSTR_READ_CELL_BROADCASTS
425            = "android:read_cell_broadcasts";
426    /** Inject mock location into the system. */
427    public static final String OPSTR_MOCK_LOCATION
428            = "android:mock_location";
429    /** Read external storage. */
430    public static final String OPSTR_READ_EXTERNAL_STORAGE
431            = "android:read_external_storage";
432    /** Write external storage. */
433    public static final String OPSTR_WRITE_EXTERNAL_STORAGE
434            = "android:write_external_storage";
435    /** Required to draw on top of other apps. */
436    public static final String OPSTR_SYSTEM_ALERT_WINDOW
437            = "android:system_alert_window";
438    /** Required to write/modify/update system settingss. */
439    public static final String OPSTR_WRITE_SETTINGS
440            = "android:write_settings";
441    /** @hide Get device accounts. */
442    @SystemApi @TestApi
443    public static final String OPSTR_GET_ACCOUNTS
444            = "android:get_accounts";
445    public static final String OPSTR_READ_PHONE_NUMBERS
446            = "android:read_phone_numbers";
447    /** Access to picture-in-picture. */
448    public static final String OPSTR_PICTURE_IN_PICTURE
449            = "android:picture_in_picture";
450    /** @hide */
451    @SystemApi @TestApi
452    public static final String OPSTR_INSTANT_APP_START_FOREGROUND
453            = "android:instant_app_start_foreground";
454    /** Answer incoming phone calls */
455    public static final String OPSTR_ANSWER_PHONE_CALLS
456            = "android:answer_phone_calls";
457    /**
458     * Accept call handover
459     * @hide
460     */
461    @SystemApi @TestApi
462    public static final String OPSTR_ACCEPT_HANDOVER
463            = "android:accept_handover";
464    /** @hide */
465    @SystemApi @TestApi
466    public static final String OPSTR_GPS = "android:gps";
467    /** @hide */
468    @SystemApi @TestApi
469    public static final String OPSTR_VIBRATE = "android:vibrate";
470    /** @hide */
471    @SystemApi @TestApi
472    public static final String OPSTR_WIFI_SCAN = "android:wifi_scan";
473    /** @hide */
474    @SystemApi @TestApi
475    public static final String OPSTR_POST_NOTIFICATION = "android:post_notification";
476    /** @hide */
477    @SystemApi @TestApi
478    public static final String OPSTR_NEIGHBORING_CELLS = "android:neighboring_cells";
479    /** @hide */
480    @SystemApi @TestApi
481    public static final String OPSTR_WRITE_SMS = "android:write_sms";
482    /** @hide */
483    @SystemApi @TestApi
484    public static final String OPSTR_RECEIVE_EMERGENCY_BROADCAST =
485            "android:receive_emergency_broadcast";
486    /** @hide */
487    @SystemApi @TestApi
488    public static final String OPSTR_READ_ICC_SMS = "android:read_icc_sms";
489    /** @hide */
490    @SystemApi @TestApi
491    public static final String OPSTR_WRITE_ICC_SMS = "android:write_icc_sms";
492    /** @hide */
493    @SystemApi @TestApi
494    public static final String OPSTR_ACCESS_NOTIFICATIONS = "android:access_notifications";
495    /** @hide */
496    @SystemApi @TestApi
497    public static final String OPSTR_PLAY_AUDIO = "android:play_audio";
498    /** @hide */
499    @SystemApi @TestApi
500    public static final String OPSTR_READ_CLIPBOARD = "android:read_clipboard";
501    /** @hide */
502    @SystemApi @TestApi
503    public static final String OPSTR_WRITE_CLIPBOARD = "android:write_clipboard";
504    /** @hide */
505    @SystemApi @TestApi
506    public static final String OPSTR_TAKE_MEDIA_BUTTONS = "android:take_media_buttons";
507    /** @hide */
508    @SystemApi @TestApi
509    public static final String OPSTR_TAKE_AUDIO_FOCUS = "android:take_audio_focus";
510    /** @hide */
511    @SystemApi @TestApi
512    public static final String OPSTR_AUDIO_MASTER_VOLUME = "android:audio_master_volume";
513    /** @hide */
514    @SystemApi @TestApi
515    public static final String OPSTR_AUDIO_VOICE_VOLUME = "android:audio_voice_volume";
516    /** @hide */
517    @SystemApi @TestApi
518    public static final String OPSTR_AUDIO_RING_VOLUME = "android:audio_ring_volume";
519    /** @hide */
520    @SystemApi @TestApi
521    public static final String OPSTR_AUDIO_MEDIA_VOLUME = "android:audio_media_volume";
522    /** @hide */
523    @SystemApi @TestApi
524    public static final String OPSTR_AUDIO_ALARM_VOLUME = "android:audio_alarm_volume";
525    /** @hide */
526    @SystemApi @TestApi
527    public static final String OPSTR_AUDIO_NOTIFICATION_VOLUME =
528            "android:audio_notification_volume";
529    /** @hide */
530    @SystemApi @TestApi
531    public static final String OPSTR_AUDIO_BLUETOOTH_VOLUME = "android:audio_bluetooth_volume";
532    /** @hide */
533    @SystemApi @TestApi
534    public static final String OPSTR_WAKE_LOCK = "android:wake_lock";
535    /** @hide */
536    @SystemApi @TestApi
537    public static final String OPSTR_MUTE_MICROPHONE = "android:mute_microphone";
538    /** @hide */
539    @SystemApi @TestApi
540    public static final String OPSTR_TOAST_WINDOW = "android:toast_window";
541    /** @hide */
542    @SystemApi @TestApi
543    public static final String OPSTR_PROJECT_MEDIA = "android:project_media";
544    /** @hide */
545    @SystemApi @TestApi
546    public static final String OPSTR_WRITE_WALLPAPER = "android:write_wallpaper";
547    /** @hide */
548    @SystemApi @TestApi
549    public static final String OPSTR_ASSIST_STRUCTURE = "android:assist_structure";
550    /** @hide */
551    @SystemApi @TestApi
552    public static final String OPSTR_ASSIST_SCREENSHOT = "android:assist_screenshot";
553    /** @hide */
554    @SystemApi @TestApi
555    public static final String OPSTR_TURN_SCREEN_ON = "android:turn_screen_on";
556    /** @hide */
557    @SystemApi @TestApi
558    public static final String OPSTR_RUN_IN_BACKGROUND = "android:run_in_background";
559    /** @hide */
560    @SystemApi @TestApi
561    public static final String OPSTR_AUDIO_ACCESSIBILITY_VOLUME =
562            "android:audio_accessibility_volume";
563    /** @hide */
564    @SystemApi @TestApi
565    public static final String OPSTR_REQUEST_INSTALL_PACKAGES = "android:request_install_packages";
566    /** @hide */
567    @SystemApi @TestApi
568    public static final String OPSTR_RUN_ANY_IN_BACKGROUND = "android:run_any_in_background";
569    /** @hide */
570    @SystemApi @TestApi
571    public static final String OPSTR_CHANGE_WIFI_STATE = "android:change_wifi_state";
572    /** @hide */
573    @SystemApi @TestApi
574    public static final String OPSTR_REQUEST_DELETE_PACKAGES = "android:request_delete_packages";
575    /** @hide */
576    @SystemApi @TestApi
577    public static final String OPSTR_BIND_ACCESSIBILITY_SERVICE =
578            "android:bind_accessibility_service";
579    /** @hide */
580    @SystemApi @TestApi
581    public static final String OPSTR_MANAGE_IPSEC_TUNNELS = "android:manage_ipsec_tunnels";
582    /** @hide */
583    @SystemApi @TestApi
584    public static final String OPSTR_START_FOREGROUND = "android:start_foreground";
585    /** @hide */
586    public static final String OPSTR_BLUETOOTH_SCAN = "android:bluetooth_scan";
587
588    // Warning: If an permission is added here it also has to be added to
589    // com.android.packageinstaller.permission.utils.EventLogger
590    private static final int[] RUNTIME_AND_APPOP_PERMISSIONS_OPS = {
591            // RUNTIME PERMISSIONS
592            // Contacts
593            OP_READ_CONTACTS,
594            OP_WRITE_CONTACTS,
595            OP_GET_ACCOUNTS,
596            // Calendar
597            OP_READ_CALENDAR,
598            OP_WRITE_CALENDAR,
599            // SMS
600            OP_SEND_SMS,
601            OP_RECEIVE_SMS,
602            OP_READ_SMS,
603            OP_RECEIVE_WAP_PUSH,
604            OP_RECEIVE_MMS,
605            OP_READ_CELL_BROADCASTS,
606            // Storage
607            OP_READ_EXTERNAL_STORAGE,
608            OP_WRITE_EXTERNAL_STORAGE,
609            // Location
610            OP_COARSE_LOCATION,
611            OP_FINE_LOCATION,
612            // Phone
613            OP_READ_PHONE_STATE,
614            OP_READ_PHONE_NUMBERS,
615            OP_CALL_PHONE,
616            OP_READ_CALL_LOG,
617            OP_WRITE_CALL_LOG,
618            OP_ADD_VOICEMAIL,
619            OP_USE_SIP,
620            OP_PROCESS_OUTGOING_CALLS,
621            OP_ANSWER_PHONE_CALLS,
622            OP_ACCEPT_HANDOVER,
623            // Microphone
624            OP_RECORD_AUDIO,
625            // Camera
626            OP_CAMERA,
627            // Body sensors
628            OP_BODY_SENSORS,
629
630            // APPOP PERMISSIONS
631            OP_ACCESS_NOTIFICATIONS,
632            OP_SYSTEM_ALERT_WINDOW,
633            OP_WRITE_SETTINGS,
634            OP_REQUEST_INSTALL_PACKAGES,
635            OP_START_FOREGROUND,
636    };
637
638    /**
639     * This maps each operation to the operation that serves as the
640     * switch to determine whether it is allowed.  Generally this is
641     * a 1:1 mapping, but for some things (like location) that have
642     * multiple low-level operations being tracked that should be
643     * presented to the user as one switch then this can be used to
644     * make them all controlled by the same single operation.
645     */
646    private static int[] sOpToSwitch = new int[] {
647            OP_COARSE_LOCATION,                 // COARSE_LOCATION
648            OP_COARSE_LOCATION,                 // FINE_LOCATION
649            OP_COARSE_LOCATION,                 // GPS
650            OP_VIBRATE,                         // VIBRATE
651            OP_READ_CONTACTS,                   // READ_CONTACTS
652            OP_WRITE_CONTACTS,                  // WRITE_CONTACTS
653            OP_READ_CALL_LOG,                   // READ_CALL_LOG
654            OP_WRITE_CALL_LOG,                  // WRITE_CALL_LOG
655            OP_READ_CALENDAR,                   // READ_CALENDAR
656            OP_WRITE_CALENDAR,                  // WRITE_CALENDAR
657            OP_COARSE_LOCATION,                 // WIFI_SCAN
658            OP_POST_NOTIFICATION,               // POST_NOTIFICATION
659            OP_COARSE_LOCATION,                 // NEIGHBORING_CELLS
660            OP_CALL_PHONE,                      // CALL_PHONE
661            OP_READ_SMS,                        // READ_SMS
662            OP_WRITE_SMS,                       // WRITE_SMS
663            OP_RECEIVE_SMS,                     // RECEIVE_SMS
664            OP_RECEIVE_SMS,                     // RECEIVE_EMERGECY_SMS
665            OP_RECEIVE_MMS,                     // RECEIVE_MMS
666            OP_RECEIVE_WAP_PUSH,                // RECEIVE_WAP_PUSH
667            OP_SEND_SMS,                        // SEND_SMS
668            OP_READ_SMS,                        // READ_ICC_SMS
669            OP_WRITE_SMS,                       // WRITE_ICC_SMS
670            OP_WRITE_SETTINGS,                  // WRITE_SETTINGS
671            OP_SYSTEM_ALERT_WINDOW,             // SYSTEM_ALERT_WINDOW
672            OP_ACCESS_NOTIFICATIONS,            // ACCESS_NOTIFICATIONS
673            OP_CAMERA,                          // CAMERA
674            OP_RECORD_AUDIO,                    // RECORD_AUDIO
675            OP_PLAY_AUDIO,                      // PLAY_AUDIO
676            OP_READ_CLIPBOARD,                  // READ_CLIPBOARD
677            OP_WRITE_CLIPBOARD,                 // WRITE_CLIPBOARD
678            OP_TAKE_MEDIA_BUTTONS,              // TAKE_MEDIA_BUTTONS
679            OP_TAKE_AUDIO_FOCUS,                // TAKE_AUDIO_FOCUS
680            OP_AUDIO_MASTER_VOLUME,             // AUDIO_MASTER_VOLUME
681            OP_AUDIO_VOICE_VOLUME,              // AUDIO_VOICE_VOLUME
682            OP_AUDIO_RING_VOLUME,               // AUDIO_RING_VOLUME
683            OP_AUDIO_MEDIA_VOLUME,              // AUDIO_MEDIA_VOLUME
684            OP_AUDIO_ALARM_VOLUME,              // AUDIO_ALARM_VOLUME
685            OP_AUDIO_NOTIFICATION_VOLUME,       // AUDIO_NOTIFICATION_VOLUME
686            OP_AUDIO_BLUETOOTH_VOLUME,          // AUDIO_BLUETOOTH_VOLUME
687            OP_WAKE_LOCK,                       // WAKE_LOCK
688            OP_COARSE_LOCATION,                 // MONITOR_LOCATION
689            OP_COARSE_LOCATION,                 // MONITOR_HIGH_POWER_LOCATION
690            OP_GET_USAGE_STATS,                 // GET_USAGE_STATS
691            OP_MUTE_MICROPHONE,                 // MUTE_MICROPHONE
692            OP_TOAST_WINDOW,                    // TOAST_WINDOW
693            OP_PROJECT_MEDIA,                   // PROJECT_MEDIA
694            OP_ACTIVATE_VPN,                    // ACTIVATE_VPN
695            OP_WRITE_WALLPAPER,                 // WRITE_WALLPAPER
696            OP_ASSIST_STRUCTURE,                // ASSIST_STRUCTURE
697            OP_ASSIST_SCREENSHOT,               // ASSIST_SCREENSHOT
698            OP_READ_PHONE_STATE,                // READ_PHONE_STATE
699            OP_ADD_VOICEMAIL,                   // ADD_VOICEMAIL
700            OP_USE_SIP,                         // USE_SIP
701            OP_PROCESS_OUTGOING_CALLS,          // PROCESS_OUTGOING_CALLS
702            OP_USE_FINGERPRINT,                 // USE_FINGERPRINT
703            OP_BODY_SENSORS,                    // BODY_SENSORS
704            OP_READ_CELL_BROADCASTS,            // READ_CELL_BROADCASTS
705            OP_MOCK_LOCATION,                   // MOCK_LOCATION
706            OP_READ_EXTERNAL_STORAGE,           // READ_EXTERNAL_STORAGE
707            OP_WRITE_EXTERNAL_STORAGE,          // WRITE_EXTERNAL_STORAGE
708            OP_TURN_SCREEN_ON,                  // TURN_SCREEN_ON
709            OP_GET_ACCOUNTS,                    // GET_ACCOUNTS
710            OP_RUN_IN_BACKGROUND,               // RUN_IN_BACKGROUND
711            OP_AUDIO_ACCESSIBILITY_VOLUME,      // AUDIO_ACCESSIBILITY_VOLUME
712            OP_READ_PHONE_NUMBERS,              // READ_PHONE_NUMBERS
713            OP_REQUEST_INSTALL_PACKAGES,        // REQUEST_INSTALL_PACKAGES
714            OP_PICTURE_IN_PICTURE,              // ENTER_PICTURE_IN_PICTURE_ON_HIDE
715            OP_INSTANT_APP_START_FOREGROUND,    // INSTANT_APP_START_FOREGROUND
716            OP_ANSWER_PHONE_CALLS,              // ANSWER_PHONE_CALLS
717            OP_RUN_ANY_IN_BACKGROUND,           // OP_RUN_ANY_IN_BACKGROUND
718            OP_CHANGE_WIFI_STATE,               // OP_CHANGE_WIFI_STATE
719            OP_REQUEST_DELETE_PACKAGES,         // OP_REQUEST_DELETE_PACKAGES
720            OP_BIND_ACCESSIBILITY_SERVICE,      // OP_BIND_ACCESSIBILITY_SERVICE
721            OP_ACCEPT_HANDOVER,                 // ACCEPT_HANDOVER
722            OP_MANAGE_IPSEC_TUNNELS,            // MANAGE_IPSEC_HANDOVERS
723            OP_START_FOREGROUND,                // START_FOREGROUND
724            OP_COARSE_LOCATION,                 // BLUETOOTH_SCAN
725    };
726
727    /**
728     * This maps each operation to the public string constant for it.
729     */
730    private static String[] sOpToString = new String[]{
731            OPSTR_COARSE_LOCATION,
732            OPSTR_FINE_LOCATION,
733            OPSTR_GPS,
734            OPSTR_VIBRATE,
735            OPSTR_READ_CONTACTS,
736            OPSTR_WRITE_CONTACTS,
737            OPSTR_READ_CALL_LOG,
738            OPSTR_WRITE_CALL_LOG,
739            OPSTR_READ_CALENDAR,
740            OPSTR_WRITE_CALENDAR,
741            OPSTR_WIFI_SCAN,
742            OPSTR_POST_NOTIFICATION,
743            OPSTR_NEIGHBORING_CELLS,
744            OPSTR_CALL_PHONE,
745            OPSTR_READ_SMS,
746            OPSTR_WRITE_SMS,
747            OPSTR_RECEIVE_SMS,
748            OPSTR_RECEIVE_EMERGENCY_BROADCAST,
749            OPSTR_RECEIVE_MMS,
750            OPSTR_RECEIVE_WAP_PUSH,
751            OPSTR_SEND_SMS,
752            OPSTR_READ_ICC_SMS,
753            OPSTR_WRITE_ICC_SMS,
754            OPSTR_WRITE_SETTINGS,
755            OPSTR_SYSTEM_ALERT_WINDOW,
756            OPSTR_ACCESS_NOTIFICATIONS,
757            OPSTR_CAMERA,
758            OPSTR_RECORD_AUDIO,
759            OPSTR_PLAY_AUDIO,
760            OPSTR_READ_CLIPBOARD,
761            OPSTR_WRITE_CLIPBOARD,
762            OPSTR_TAKE_MEDIA_BUTTONS,
763            OPSTR_TAKE_AUDIO_FOCUS,
764            OPSTR_AUDIO_MASTER_VOLUME,
765            OPSTR_AUDIO_VOICE_VOLUME,
766            OPSTR_AUDIO_RING_VOLUME,
767            OPSTR_AUDIO_MEDIA_VOLUME,
768            OPSTR_AUDIO_ALARM_VOLUME,
769            OPSTR_AUDIO_NOTIFICATION_VOLUME,
770            OPSTR_AUDIO_BLUETOOTH_VOLUME,
771            OPSTR_WAKE_LOCK,
772            OPSTR_MONITOR_LOCATION,
773            OPSTR_MONITOR_HIGH_POWER_LOCATION,
774            OPSTR_GET_USAGE_STATS,
775            OPSTR_MUTE_MICROPHONE,
776            OPSTR_TOAST_WINDOW,
777            OPSTR_PROJECT_MEDIA,
778            OPSTR_ACTIVATE_VPN,
779            OPSTR_WRITE_WALLPAPER,
780            OPSTR_ASSIST_STRUCTURE,
781            OPSTR_ASSIST_SCREENSHOT,
782            OPSTR_READ_PHONE_STATE,
783            OPSTR_ADD_VOICEMAIL,
784            OPSTR_USE_SIP,
785            OPSTR_PROCESS_OUTGOING_CALLS,
786            OPSTR_USE_FINGERPRINT,
787            OPSTR_BODY_SENSORS,
788            OPSTR_READ_CELL_BROADCASTS,
789            OPSTR_MOCK_LOCATION,
790            OPSTR_READ_EXTERNAL_STORAGE,
791            OPSTR_WRITE_EXTERNAL_STORAGE,
792            OPSTR_TURN_SCREEN_ON,
793            OPSTR_GET_ACCOUNTS,
794            OPSTR_RUN_IN_BACKGROUND,
795            OPSTR_AUDIO_ACCESSIBILITY_VOLUME,
796            OPSTR_READ_PHONE_NUMBERS,
797            OPSTR_REQUEST_INSTALL_PACKAGES,
798            OPSTR_PICTURE_IN_PICTURE,
799            OPSTR_INSTANT_APP_START_FOREGROUND,
800            OPSTR_ANSWER_PHONE_CALLS,
801            OPSTR_RUN_ANY_IN_BACKGROUND,
802            OPSTR_CHANGE_WIFI_STATE,
803            OPSTR_REQUEST_DELETE_PACKAGES,
804            OPSTR_BIND_ACCESSIBILITY_SERVICE,
805            OPSTR_ACCEPT_HANDOVER,
806            OPSTR_MANAGE_IPSEC_TUNNELS,
807            OPSTR_START_FOREGROUND,
808            OPSTR_BLUETOOTH_SCAN,
809    };
810
811    /**
812     * This provides a simple name for each operation to be used
813     * in debug output.
814     */
815    private static String[] sOpNames = new String[] {
816            "COARSE_LOCATION",
817            "FINE_LOCATION",
818            "GPS",
819            "VIBRATE",
820            "READ_CONTACTS",
821            "WRITE_CONTACTS",
822            "READ_CALL_LOG",
823            "WRITE_CALL_LOG",
824            "READ_CALENDAR",
825            "WRITE_CALENDAR",
826            "WIFI_SCAN",
827            "POST_NOTIFICATION",
828            "NEIGHBORING_CELLS",
829            "CALL_PHONE",
830            "READ_SMS",
831            "WRITE_SMS",
832            "RECEIVE_SMS",
833            "RECEIVE_EMERGECY_SMS",
834            "RECEIVE_MMS",
835            "RECEIVE_WAP_PUSH",
836            "SEND_SMS",
837            "READ_ICC_SMS",
838            "WRITE_ICC_SMS",
839            "WRITE_SETTINGS",
840            "SYSTEM_ALERT_WINDOW",
841            "ACCESS_NOTIFICATIONS",
842            "CAMERA",
843            "RECORD_AUDIO",
844            "PLAY_AUDIO",
845            "READ_CLIPBOARD",
846            "WRITE_CLIPBOARD",
847            "TAKE_MEDIA_BUTTONS",
848            "TAKE_AUDIO_FOCUS",
849            "AUDIO_MASTER_VOLUME",
850            "AUDIO_VOICE_VOLUME",
851            "AUDIO_RING_VOLUME",
852            "AUDIO_MEDIA_VOLUME",
853            "AUDIO_ALARM_VOLUME",
854            "AUDIO_NOTIFICATION_VOLUME",
855            "AUDIO_BLUETOOTH_VOLUME",
856            "WAKE_LOCK",
857            "MONITOR_LOCATION",
858            "MONITOR_HIGH_POWER_LOCATION",
859            "GET_USAGE_STATS",
860            "MUTE_MICROPHONE",
861            "TOAST_WINDOW",
862            "PROJECT_MEDIA",
863            "ACTIVATE_VPN",
864            "WRITE_WALLPAPER",
865            "ASSIST_STRUCTURE",
866            "ASSIST_SCREENSHOT",
867            "OP_READ_PHONE_STATE",
868            "ADD_VOICEMAIL",
869            "USE_SIP",
870            "PROCESS_OUTGOING_CALLS",
871            "USE_FINGERPRINT",
872            "BODY_SENSORS",
873            "READ_CELL_BROADCASTS",
874            "MOCK_LOCATION",
875            "READ_EXTERNAL_STORAGE",
876            "WRITE_EXTERNAL_STORAGE",
877            "TURN_ON_SCREEN",
878            "GET_ACCOUNTS",
879            "RUN_IN_BACKGROUND",
880            "AUDIO_ACCESSIBILITY_VOLUME",
881            "READ_PHONE_NUMBERS",
882            "REQUEST_INSTALL_PACKAGES",
883            "PICTURE_IN_PICTURE",
884            "INSTANT_APP_START_FOREGROUND",
885            "ANSWER_PHONE_CALLS",
886            "RUN_ANY_IN_BACKGROUND",
887            "CHANGE_WIFI_STATE",
888            "REQUEST_DELETE_PACKAGES",
889            "BIND_ACCESSIBILITY_SERVICE",
890            "ACCEPT_HANDOVER",
891            "MANAGE_IPSEC_TUNNELS",
892            "START_FOREGROUND",
893            "BLUETOOTH_SCAN",
894    };
895
896    /**
897     * This optionally maps a permission to an operation.  If there
898     * is no permission associated with an operation, it is null.
899     */
900    private static String[] sOpPerms = new String[] {
901            android.Manifest.permission.ACCESS_COARSE_LOCATION,
902            android.Manifest.permission.ACCESS_FINE_LOCATION,
903            null,
904            android.Manifest.permission.VIBRATE,
905            android.Manifest.permission.READ_CONTACTS,
906            android.Manifest.permission.WRITE_CONTACTS,
907            android.Manifest.permission.READ_CALL_LOG,
908            android.Manifest.permission.WRITE_CALL_LOG,
909            android.Manifest.permission.READ_CALENDAR,
910            android.Manifest.permission.WRITE_CALENDAR,
911            android.Manifest.permission.ACCESS_WIFI_STATE,
912            null, // no permission required for notifications
913            null, // neighboring cells shares the coarse location perm
914            android.Manifest.permission.CALL_PHONE,
915            android.Manifest.permission.READ_SMS,
916            null, // no permission required for writing sms
917            android.Manifest.permission.RECEIVE_SMS,
918            android.Manifest.permission.RECEIVE_EMERGENCY_BROADCAST,
919            android.Manifest.permission.RECEIVE_MMS,
920            android.Manifest.permission.RECEIVE_WAP_PUSH,
921            android.Manifest.permission.SEND_SMS,
922            android.Manifest.permission.READ_SMS,
923            null, // no permission required for writing icc sms
924            android.Manifest.permission.WRITE_SETTINGS,
925            android.Manifest.permission.SYSTEM_ALERT_WINDOW,
926            android.Manifest.permission.ACCESS_NOTIFICATIONS,
927            android.Manifest.permission.CAMERA,
928            android.Manifest.permission.RECORD_AUDIO,
929            null, // no permission for playing audio
930            null, // no permission for reading clipboard
931            null, // no permission for writing clipboard
932            null, // no permission for taking media buttons
933            null, // no permission for taking audio focus
934            null, // no permission for changing master volume
935            null, // no permission for changing voice volume
936            null, // no permission for changing ring volume
937            null, // no permission for changing media volume
938            null, // no permission for changing alarm volume
939            null, // no permission for changing notification volume
940            null, // no permission for changing bluetooth volume
941            android.Manifest.permission.WAKE_LOCK,
942            null, // no permission for generic location monitoring
943            null, // no permission for high power location monitoring
944            android.Manifest.permission.PACKAGE_USAGE_STATS,
945            null, // no permission for muting/unmuting microphone
946            null, // no permission for displaying toasts
947            null, // no permission for projecting media
948            null, // no permission for activating vpn
949            null, // no permission for supporting wallpaper
950            null, // no permission for receiving assist structure
951            null, // no permission for receiving assist screenshot
952            Manifest.permission.READ_PHONE_STATE,
953            Manifest.permission.ADD_VOICEMAIL,
954            Manifest.permission.USE_SIP,
955            Manifest.permission.PROCESS_OUTGOING_CALLS,
956            Manifest.permission.USE_FINGERPRINT,
957            Manifest.permission.BODY_SENSORS,
958            Manifest.permission.READ_CELL_BROADCASTS,
959            null,
960            Manifest.permission.READ_EXTERNAL_STORAGE,
961            Manifest.permission.WRITE_EXTERNAL_STORAGE,
962            null, // no permission for turning the screen on
963            Manifest.permission.GET_ACCOUNTS,
964            null, // no permission for running in background
965            null, // no permission for changing accessibility volume
966            Manifest.permission.READ_PHONE_NUMBERS,
967            Manifest.permission.REQUEST_INSTALL_PACKAGES,
968            null, // no permission for entering picture-in-picture on hide
969            Manifest.permission.INSTANT_APP_FOREGROUND_SERVICE,
970            Manifest.permission.ANSWER_PHONE_CALLS,
971            null, // no permission for OP_RUN_ANY_IN_BACKGROUND
972            Manifest.permission.CHANGE_WIFI_STATE,
973            Manifest.permission.REQUEST_DELETE_PACKAGES,
974            Manifest.permission.BIND_ACCESSIBILITY_SERVICE,
975            Manifest.permission.ACCEPT_HANDOVER,
976            null, // no permission for OP_MANAGE_IPSEC_TUNNELS
977            Manifest.permission.FOREGROUND_SERVICE,
978            null, // no permission for OP_BLUETOOTH_SCAN
979    };
980
981    /**
982     * Specifies whether an Op should be restricted by a user restriction.
983     * Each Op should be filled with a restriction string from UserManager or
984     * null to specify it is not affected by any user restriction.
985     */
986    private static String[] sOpRestrictions = new String[] {
987            UserManager.DISALLOW_SHARE_LOCATION, //COARSE_LOCATION
988            UserManager.DISALLOW_SHARE_LOCATION, //FINE_LOCATION
989            UserManager.DISALLOW_SHARE_LOCATION, //GPS
990            null, //VIBRATE
991            null, //READ_CONTACTS
992            null, //WRITE_CONTACTS
993            UserManager.DISALLOW_OUTGOING_CALLS, //READ_CALL_LOG
994            UserManager.DISALLOW_OUTGOING_CALLS, //WRITE_CALL_LOG
995            null, //READ_CALENDAR
996            null, //WRITE_CALENDAR
997            UserManager.DISALLOW_SHARE_LOCATION, //WIFI_SCAN
998            null, //POST_NOTIFICATION
999            null, //NEIGHBORING_CELLS
1000            null, //CALL_PHONE
1001            UserManager.DISALLOW_SMS, //READ_SMS
1002            UserManager.DISALLOW_SMS, //WRITE_SMS
1003            UserManager.DISALLOW_SMS, //RECEIVE_SMS
1004            null, //RECEIVE_EMERGENCY_SMS
1005            UserManager.DISALLOW_SMS, //RECEIVE_MMS
1006            null, //RECEIVE_WAP_PUSH
1007            UserManager.DISALLOW_SMS, //SEND_SMS
1008            UserManager.DISALLOW_SMS, //READ_ICC_SMS
1009            UserManager.DISALLOW_SMS, //WRITE_ICC_SMS
1010            null, //WRITE_SETTINGS
1011            UserManager.DISALLOW_CREATE_WINDOWS, //SYSTEM_ALERT_WINDOW
1012            null, //ACCESS_NOTIFICATIONS
1013            UserManager.DISALLOW_CAMERA, //CAMERA
1014            UserManager.DISALLOW_RECORD_AUDIO, //RECORD_AUDIO
1015            null, //PLAY_AUDIO
1016            null, //READ_CLIPBOARD
1017            null, //WRITE_CLIPBOARD
1018            null, //TAKE_MEDIA_BUTTONS
1019            null, //TAKE_AUDIO_FOCUS
1020            UserManager.DISALLOW_ADJUST_VOLUME, //AUDIO_MASTER_VOLUME
1021            UserManager.DISALLOW_ADJUST_VOLUME, //AUDIO_VOICE_VOLUME
1022            UserManager.DISALLOW_ADJUST_VOLUME, //AUDIO_RING_VOLUME
1023            UserManager.DISALLOW_ADJUST_VOLUME, //AUDIO_MEDIA_VOLUME
1024            UserManager.DISALLOW_ADJUST_VOLUME, //AUDIO_ALARM_VOLUME
1025            UserManager.DISALLOW_ADJUST_VOLUME, //AUDIO_NOTIFICATION_VOLUME
1026            UserManager.DISALLOW_ADJUST_VOLUME, //AUDIO_BLUETOOTH_VOLUME
1027            null, //WAKE_LOCK
1028            UserManager.DISALLOW_SHARE_LOCATION, //MONITOR_LOCATION
1029            UserManager.DISALLOW_SHARE_LOCATION, //MONITOR_HIGH_POWER_LOCATION
1030            null, //GET_USAGE_STATS
1031            UserManager.DISALLOW_UNMUTE_MICROPHONE, // MUTE_MICROPHONE
1032            UserManager.DISALLOW_CREATE_WINDOWS, // TOAST_WINDOW
1033            null, //PROJECT_MEDIA
1034            null, // ACTIVATE_VPN
1035            UserManager.DISALLOW_WALLPAPER, // WRITE_WALLPAPER
1036            null, // ASSIST_STRUCTURE
1037            null, // ASSIST_SCREENSHOT
1038            null, // READ_PHONE_STATE
1039            null, // ADD_VOICEMAIL
1040            null, // USE_SIP
1041            null, // PROCESS_OUTGOING_CALLS
1042            null, // USE_FINGERPRINT
1043            null, // BODY_SENSORS
1044            null, // READ_CELL_BROADCASTS
1045            null, // MOCK_LOCATION
1046            null, // READ_EXTERNAL_STORAGE
1047            null, // WRITE_EXTERNAL_STORAGE
1048            null, // TURN_ON_SCREEN
1049            null, // GET_ACCOUNTS
1050            null, // RUN_IN_BACKGROUND
1051            UserManager.DISALLOW_ADJUST_VOLUME, //AUDIO_ACCESSIBILITY_VOLUME
1052            null, // READ_PHONE_NUMBERS
1053            null, // REQUEST_INSTALL_PACKAGES
1054            null, // ENTER_PICTURE_IN_PICTURE_ON_HIDE
1055            null, // INSTANT_APP_START_FOREGROUND
1056            null, // ANSWER_PHONE_CALLS
1057            null, // OP_RUN_ANY_IN_BACKGROUND
1058            null, // OP_CHANGE_WIFI_STATE
1059            null, // REQUEST_DELETE_PACKAGES
1060            null, // OP_BIND_ACCESSIBILITY_SERVICE
1061            null, // ACCEPT_HANDOVER
1062            null, // MANAGE_IPSEC_TUNNELS
1063            null, // START_FOREGROUND
1064            null, // maybe should be UserManager.DISALLOW_SHARE_LOCATION, //BLUETOOTH_SCAN
1065    };
1066
1067    /**
1068     * This specifies whether each option should allow the system
1069     * (and system ui) to bypass the user restriction when active.
1070     */
1071    private static boolean[] sOpAllowSystemRestrictionBypass = new boolean[] {
1072            true, //COARSE_LOCATION
1073            true, //FINE_LOCATION
1074            false, //GPS
1075            false, //VIBRATE
1076            false, //READ_CONTACTS
1077            false, //WRITE_CONTACTS
1078            false, //READ_CALL_LOG
1079            false, //WRITE_CALL_LOG
1080            false, //READ_CALENDAR
1081            false, //WRITE_CALENDAR
1082            true, //WIFI_SCAN
1083            false, //POST_NOTIFICATION
1084            false, //NEIGHBORING_CELLS
1085            false, //CALL_PHONE
1086            false, //READ_SMS
1087            false, //WRITE_SMS
1088            false, //RECEIVE_SMS
1089            false, //RECEIVE_EMERGECY_SMS
1090            false, //RECEIVE_MMS
1091            false, //RECEIVE_WAP_PUSH
1092            false, //SEND_SMS
1093            false, //READ_ICC_SMS
1094            false, //WRITE_ICC_SMS
1095            false, //WRITE_SETTINGS
1096            true, //SYSTEM_ALERT_WINDOW
1097            false, //ACCESS_NOTIFICATIONS
1098            false, //CAMERA
1099            false, //RECORD_AUDIO
1100            false, //PLAY_AUDIO
1101            false, //READ_CLIPBOARD
1102            false, //WRITE_CLIPBOARD
1103            false, //TAKE_MEDIA_BUTTONS
1104            false, //TAKE_AUDIO_FOCUS
1105            false, //AUDIO_MASTER_VOLUME
1106            false, //AUDIO_VOICE_VOLUME
1107            false, //AUDIO_RING_VOLUME
1108            false, //AUDIO_MEDIA_VOLUME
1109            false, //AUDIO_ALARM_VOLUME
1110            false, //AUDIO_NOTIFICATION_VOLUME
1111            false, //AUDIO_BLUETOOTH_VOLUME
1112            false, //WAKE_LOCK
1113            false, //MONITOR_LOCATION
1114            false, //MONITOR_HIGH_POWER_LOCATION
1115            false, //GET_USAGE_STATS
1116            false, //MUTE_MICROPHONE
1117            true, //TOAST_WINDOW
1118            false, //PROJECT_MEDIA
1119            false, //ACTIVATE_VPN
1120            false, //WALLPAPER
1121            false, //ASSIST_STRUCTURE
1122            false, //ASSIST_SCREENSHOT
1123            false, //READ_PHONE_STATE
1124            false, //ADD_VOICEMAIL
1125            false, // USE_SIP
1126            false, // PROCESS_OUTGOING_CALLS
1127            false, // USE_FINGERPRINT
1128            false, // BODY_SENSORS
1129            false, // READ_CELL_BROADCASTS
1130            false, // MOCK_LOCATION
1131            false, // READ_EXTERNAL_STORAGE
1132            false, // WRITE_EXTERNAL_STORAGE
1133            false, // TURN_ON_SCREEN
1134            false, // GET_ACCOUNTS
1135            false, // RUN_IN_BACKGROUND
1136            false, // AUDIO_ACCESSIBILITY_VOLUME
1137            false, // READ_PHONE_NUMBERS
1138            false, // REQUEST_INSTALL_PACKAGES
1139            false, // ENTER_PICTURE_IN_PICTURE_ON_HIDE
1140            false, // INSTANT_APP_START_FOREGROUND
1141            false, // ANSWER_PHONE_CALLS
1142            false, // OP_RUN_ANY_IN_BACKGROUND
1143            false, // OP_CHANGE_WIFI_STATE
1144            false, // OP_REQUEST_DELETE_PACKAGES
1145            false, // OP_BIND_ACCESSIBILITY_SERVICE
1146            false, // ACCEPT_HANDOVER
1147            false, // MANAGE_IPSEC_HANDOVERS
1148            false, // START_FOREGROUND
1149            true, // BLUETOOTH_SCAN
1150    };
1151
1152    /**
1153     * This specifies the default mode for each operation.
1154     */
1155    private static int[] sOpDefaultMode = new int[] {
1156            AppOpsManager.MODE_ALLOWED,
1157            AppOpsManager.MODE_ALLOWED,
1158            AppOpsManager.MODE_ALLOWED,
1159            AppOpsManager.MODE_ALLOWED,
1160            AppOpsManager.MODE_ALLOWED,
1161            AppOpsManager.MODE_ALLOWED,
1162            AppOpsManager.MODE_ALLOWED,
1163            AppOpsManager.MODE_ALLOWED,
1164            AppOpsManager.MODE_ALLOWED,
1165            AppOpsManager.MODE_ALLOWED,
1166            AppOpsManager.MODE_ALLOWED,
1167            AppOpsManager.MODE_ALLOWED,
1168            AppOpsManager.MODE_ALLOWED,
1169            AppOpsManager.MODE_ALLOWED,
1170            AppOpsManager.MODE_ALLOWED,
1171            AppOpsManager.MODE_IGNORED, // OP_WRITE_SMS
1172            AppOpsManager.MODE_ALLOWED,
1173            AppOpsManager.MODE_ALLOWED,
1174            AppOpsManager.MODE_ALLOWED,
1175            AppOpsManager.MODE_ALLOWED,
1176            AppOpsManager.MODE_ALLOWED,
1177            AppOpsManager.MODE_ALLOWED,
1178            AppOpsManager.MODE_ALLOWED,
1179            AppOpsManager.MODE_DEFAULT, // OP_WRITE_SETTINGS
1180            AppOpsManager.MODE_DEFAULT, // OP_SYSTEM_ALERT_WINDOW
1181            AppOpsManager.MODE_ALLOWED,
1182            AppOpsManager.MODE_ALLOWED,
1183            AppOpsManager.MODE_ALLOWED,
1184            AppOpsManager.MODE_ALLOWED,
1185            AppOpsManager.MODE_ALLOWED,
1186            AppOpsManager.MODE_ALLOWED,
1187            AppOpsManager.MODE_ALLOWED,
1188            AppOpsManager.MODE_ALLOWED,
1189            AppOpsManager.MODE_ALLOWED,
1190            AppOpsManager.MODE_ALLOWED,
1191            AppOpsManager.MODE_ALLOWED,
1192            AppOpsManager.MODE_ALLOWED,
1193            AppOpsManager.MODE_ALLOWED,
1194            AppOpsManager.MODE_ALLOWED,
1195            AppOpsManager.MODE_ALLOWED,
1196            AppOpsManager.MODE_ALLOWED,
1197            AppOpsManager.MODE_ALLOWED,
1198            AppOpsManager.MODE_ALLOWED,
1199            AppOpsManager.MODE_DEFAULT, // OP_GET_USAGE_STATS
1200            AppOpsManager.MODE_ALLOWED,
1201            AppOpsManager.MODE_ALLOWED,
1202            AppOpsManager.MODE_IGNORED, // OP_PROJECT_MEDIA
1203            AppOpsManager.MODE_IGNORED, // OP_ACTIVATE_VPN
1204            AppOpsManager.MODE_ALLOWED,
1205            AppOpsManager.MODE_ALLOWED,
1206            AppOpsManager.MODE_ALLOWED,
1207            AppOpsManager.MODE_ALLOWED,
1208            AppOpsManager.MODE_ALLOWED,
1209            AppOpsManager.MODE_ALLOWED,
1210            AppOpsManager.MODE_ALLOWED,
1211            AppOpsManager.MODE_ALLOWED,
1212            AppOpsManager.MODE_ALLOWED,
1213            AppOpsManager.MODE_ALLOWED,
1214            AppOpsManager.MODE_ERRORED,  // OP_MOCK_LOCATION
1215            AppOpsManager.MODE_ALLOWED,
1216            AppOpsManager.MODE_ALLOWED,
1217            AppOpsManager.MODE_ALLOWED,  // OP_TURN_ON_SCREEN
1218            AppOpsManager.MODE_ALLOWED,
1219            AppOpsManager.MODE_ALLOWED,  // OP_RUN_IN_BACKGROUND
1220            AppOpsManager.MODE_ALLOWED,  // OP_AUDIO_ACCESSIBILITY_VOLUME
1221            AppOpsManager.MODE_ALLOWED,
1222            AppOpsManager.MODE_DEFAULT,  // OP_REQUEST_INSTALL_PACKAGES
1223            AppOpsManager.MODE_ALLOWED,  // OP_PICTURE_IN_PICTURE
1224            AppOpsManager.MODE_DEFAULT,  // OP_INSTANT_APP_START_FOREGROUND
1225            AppOpsManager.MODE_ALLOWED,  // ANSWER_PHONE_CALLS
1226            AppOpsManager.MODE_ALLOWED,  // OP_RUN_ANY_IN_BACKGROUND
1227            AppOpsManager.MODE_ALLOWED,  // OP_CHANGE_WIFI_STATE
1228            AppOpsManager.MODE_ALLOWED,  // REQUEST_DELETE_PACKAGES
1229            AppOpsManager.MODE_ALLOWED,  // OP_BIND_ACCESSIBILITY_SERVICE
1230            AppOpsManager.MODE_ALLOWED,  // ACCEPT_HANDOVER
1231            AppOpsManager.MODE_ERRORED,  // MANAGE_IPSEC_TUNNELS
1232            AppOpsManager.MODE_ALLOWED,  // OP_START_FOREGROUND
1233            AppOpsManager.MODE_ALLOWED,  // OP_BLUETOOTH_SCAN
1234    };
1235
1236    /**
1237     * This specifies whether each option is allowed to be reset
1238     * when resetting all app preferences.  Disable reset for
1239     * app ops that are under strong control of some part of the
1240     * system (such as OP_WRITE_SMS, which should be allowed only
1241     * for whichever app is selected as the current SMS app).
1242     */
1243    private static boolean[] sOpDisableReset = new boolean[] {
1244            false,
1245            false,
1246            false,
1247            false,
1248            false,
1249            false,
1250            false,
1251            false,
1252            false,
1253            false,
1254            false,
1255            false,
1256            false,
1257            false,
1258            false,
1259            true,      // OP_WRITE_SMS
1260            false,
1261            false,
1262            false,
1263            false,
1264            false,
1265            false,
1266            false,
1267            false,
1268            false,
1269            false,
1270            false,
1271            false,
1272            false,
1273            false,
1274            false,
1275            false,
1276            false,
1277            false,
1278            false,
1279            false,
1280            false,
1281            false,
1282            false,
1283            false,
1284            false,
1285            false,
1286            false,
1287            false,
1288            false,
1289            false,
1290            false,
1291            false,
1292            false,
1293            false,
1294            false,
1295            false,
1296            false,
1297            false,
1298            false,
1299            false,
1300            false,
1301            false,
1302            false,
1303            false,
1304            false,
1305            false,
1306            false,
1307            false,
1308            false, // OP_AUDIO_ACCESSIBILITY_VOLUME
1309            false,
1310            false, // OP_REQUEST_INSTALL_PACKAGES
1311            false, // OP_PICTURE_IN_PICTURE
1312            false,
1313            false, // ANSWER_PHONE_CALLS
1314            false, // OP_RUN_ANY_IN_BACKGROUND
1315            false, // OP_CHANGE_WIFI_STATE
1316            false, // OP_REQUEST_DELETE_PACKAGES
1317            false, // OP_BIND_ACCESSIBILITY_SERVICE
1318            false, // ACCEPT_HANDOVER
1319            false, // MANAGE_IPSEC_TUNNELS
1320            false, // START_FOREGROUND
1321            false, // BLUETOOTH_SCAN
1322    };
1323
1324    /**
1325     * Mapping from an app op name to the app op code.
1326     */
1327    private static HashMap<String, Integer> sOpStrToOp = new HashMap<>();
1328
1329    /**
1330     * Mapping from a permission to the corresponding app op.
1331     */
1332    private static HashMap<String, Integer> sPermToOp = new HashMap<>();
1333
1334    static {
1335        if (sOpToSwitch.length != _NUM_OP) {
1336            throw new IllegalStateException("sOpToSwitch length " + sOpToSwitch.length
1337                    + " should be " + _NUM_OP);
1338        }
1339        if (sOpToString.length != _NUM_OP) {
1340            throw new IllegalStateException("sOpToString length " + sOpToString.length
1341                    + " should be " + _NUM_OP);
1342        }
1343        if (sOpNames.length != _NUM_OP) {
1344            throw new IllegalStateException("sOpNames length " + sOpNames.length
1345                    + " should be " + _NUM_OP);
1346        }
1347        if (sOpPerms.length != _NUM_OP) {
1348            throw new IllegalStateException("sOpPerms length " + sOpPerms.length
1349                    + " should be " + _NUM_OP);
1350        }
1351        if (sOpDefaultMode.length != _NUM_OP) {
1352            throw new IllegalStateException("sOpDefaultMode length " + sOpDefaultMode.length
1353                    + " should be " + _NUM_OP);
1354        }
1355        if (sOpDisableReset.length != _NUM_OP) {
1356            throw new IllegalStateException("sOpDisableReset length " + sOpDisableReset.length
1357                    + " should be " + _NUM_OP);
1358        }
1359        if (sOpRestrictions.length != _NUM_OP) {
1360            throw new IllegalStateException("sOpRestrictions length " + sOpRestrictions.length
1361                    + " should be " + _NUM_OP);
1362        }
1363        if (sOpAllowSystemRestrictionBypass.length != _NUM_OP) {
1364            throw new IllegalStateException("sOpAllowSYstemRestrictionsBypass length "
1365                    + sOpRestrictions.length + " should be " + _NUM_OP);
1366        }
1367        for (int i=0; i<_NUM_OP; i++) {
1368            if (sOpToString[i] != null) {
1369                sOpStrToOp.put(sOpToString[i], i);
1370            }
1371        }
1372        for (int op : RUNTIME_AND_APPOP_PERMISSIONS_OPS) {
1373            if (sOpPerms[op] != null) {
1374                sPermToOp.put(sOpPerms[op], op);
1375            }
1376        }
1377    }
1378
1379    /**
1380     * Retrieve the op switch that controls the given operation.
1381     * @hide
1382     */
1383    public static int opToSwitch(int op) {
1384        return sOpToSwitch[op];
1385    }
1386
1387    /**
1388     * Retrieve a non-localized name for the operation, for debugging output.
1389     * @hide
1390     */
1391    public static String opToName(int op) {
1392        if (op == OP_NONE) return "NONE";
1393        return op < sOpNames.length ? sOpNames[op] : ("Unknown(" + op + ")");
1394    }
1395
1396    /**
1397     * @hide
1398     */
1399    public static int strDebugOpToOp(String op) {
1400        for (int i=0; i<sOpNames.length; i++) {
1401            if (sOpNames[i].equals(op)) {
1402                return i;
1403            }
1404        }
1405        throw new IllegalArgumentException("Unknown operation string: " + op);
1406    }
1407
1408    /**
1409     * Retrieve the permission associated with an operation, or null if there is not one.
1410     * @hide
1411     */
1412    public static String opToPermission(int op) {
1413        return sOpPerms[op];
1414    }
1415
1416    /**
1417     * Retrieve the user restriction associated with an operation, or null if there is not one.
1418     * @hide
1419     */
1420    public static String opToRestriction(int op) {
1421        return sOpRestrictions[op];
1422    }
1423
1424    /**
1425     * Retrieve the app op code for a permission, or null if there is not one.
1426     * This API is intended to be used for mapping runtime or appop permissions
1427     * to the corresponding app op.
1428     * @hide
1429     */
1430    public static int permissionToOpCode(String permission) {
1431        Integer boxedOpCode = sPermToOp.get(permission);
1432        return boxedOpCode != null ? boxedOpCode : OP_NONE;
1433    }
1434
1435    /**
1436     * Retrieve whether the op allows the system (and system ui) to
1437     * bypass the user restriction.
1438     * @hide
1439     */
1440    public static boolean opAllowSystemBypassRestriction(int op) {
1441        return sOpAllowSystemRestrictionBypass[op];
1442    }
1443
1444    /**
1445     * Retrieve the default mode for the operation.
1446     * @hide
1447     */
1448    public static int opToDefaultMode(int op) {
1449        return sOpDefaultMode[op];
1450    }
1451
1452    /**
1453     * Retrieve the human readable mode.
1454     * @hide
1455     */
1456    public static String modeToName(int mode) {
1457        if (mode >= 0 && mode < MODE_NAMES.length) {
1458            return MODE_NAMES[mode];
1459        }
1460        return "mode=" + mode;
1461    }
1462
1463    /**
1464     * Retrieve whether the op allows itself to be reset.
1465     * @hide
1466     */
1467    public static boolean opAllowsReset(int op) {
1468        return !sOpDisableReset[op];
1469    }
1470
1471    /**
1472     * Class holding all of the operation information associated with an app.
1473     * @hide
1474     */
1475    public static class PackageOps implements Parcelable {
1476        private final String mPackageName;
1477        private final int mUid;
1478        private final List<OpEntry> mEntries;
1479
1480        public PackageOps(String packageName, int uid, List<OpEntry> entries) {
1481            mPackageName = packageName;
1482            mUid = uid;
1483            mEntries = entries;
1484        }
1485
1486        public String getPackageName() {
1487            return mPackageName;
1488        }
1489
1490        public int getUid() {
1491            return mUid;
1492        }
1493
1494        public List<OpEntry> getOps() {
1495            return mEntries;
1496        }
1497
1498        @Override
1499        public int describeContents() {
1500            return 0;
1501        }
1502
1503        @Override
1504        public void writeToParcel(Parcel dest, int flags) {
1505            dest.writeString(mPackageName);
1506            dest.writeInt(mUid);
1507            dest.writeInt(mEntries.size());
1508            for (int i=0; i<mEntries.size(); i++) {
1509                mEntries.get(i).writeToParcel(dest, flags);
1510            }
1511        }
1512
1513        PackageOps(Parcel source) {
1514            mPackageName = source.readString();
1515            mUid = source.readInt();
1516            mEntries = new ArrayList<OpEntry>();
1517            final int N = source.readInt();
1518            for (int i=0; i<N; i++) {
1519                mEntries.add(OpEntry.CREATOR.createFromParcel(source));
1520            }
1521        }
1522
1523        public static final Creator<PackageOps> CREATOR = new Creator<PackageOps>() {
1524            @Override public PackageOps createFromParcel(Parcel source) {
1525                return new PackageOps(source);
1526            }
1527
1528            @Override public PackageOps[] newArray(int size) {
1529                return new PackageOps[size];
1530            }
1531        };
1532    }
1533
1534    /**
1535     * Class holding the information about one unique operation of an application.
1536     * @hide
1537     */
1538    public static class OpEntry implements Parcelable {
1539        private final int mOp;
1540        private final int mMode;
1541        private final long[] mTimes;
1542        private final long[] mRejectTimes;
1543        private final int mDuration;
1544        private final int mProxyUid;
1545        private final String mProxyPackageName;
1546
1547        public OpEntry(int op, int mode, long time, long rejectTime, int duration,
1548                int proxyUid, String proxyPackage) {
1549            mOp = op;
1550            mMode = mode;
1551            mTimes = new long[_NUM_UID_STATE];
1552            mRejectTimes = new long[_NUM_UID_STATE];
1553            mTimes[0] = time;
1554            mRejectTimes[0] = rejectTime;
1555            mDuration = duration;
1556            mProxyUid = proxyUid;
1557            mProxyPackageName = proxyPackage;
1558        }
1559
1560        public OpEntry(int op, int mode, long[] times, long[] rejectTimes, int duration,
1561                int proxyUid, String proxyPackage) {
1562            mOp = op;
1563            mMode = mode;
1564            mTimes = new long[_NUM_UID_STATE];
1565            mRejectTimes = new long[_NUM_UID_STATE];
1566            System.arraycopy(times, 0, mTimes, 0, _NUM_UID_STATE);
1567            System.arraycopy(rejectTimes, 0, mRejectTimes, 0, _NUM_UID_STATE);
1568            mDuration = duration;
1569            mProxyUid = proxyUid;
1570            mProxyPackageName = proxyPackage;
1571        }
1572
1573        public int getOp() {
1574            return mOp;
1575        }
1576
1577        public int getMode() {
1578            return mMode;
1579        }
1580
1581        public long getTime() {
1582            return maxTime(mTimes, 0, _NUM_UID_STATE);
1583        }
1584
1585        public long getLastAccessTime() {
1586            return maxTime(mTimes, 0, _NUM_UID_STATE);
1587        }
1588
1589        public long getLastAccessForegroundTime() {
1590            return maxTime(mTimes, UID_STATE_PERSISTENT, UID_STATE_FOREGROUND_SERVICE + 1);
1591        }
1592
1593        public long getLastAccessBackgroundTime() {
1594            return maxTime(mTimes, UID_STATE_FOREGROUND_SERVICE + 1, _NUM_UID_STATE);
1595        }
1596
1597        public long getLastTimeFor(int uidState) {
1598            return mTimes[uidState];
1599        }
1600
1601        public long getRejectTime() {
1602            return maxTime(mRejectTimes, 0, _NUM_UID_STATE);
1603        }
1604
1605        public long getLastRejectTime() {
1606            return maxTime(mRejectTimes, 0, _NUM_UID_STATE);
1607        }
1608
1609        public long getLastRejectForegroundTime() {
1610            return maxTime(mRejectTimes, UID_STATE_PERSISTENT, UID_STATE_FOREGROUND_SERVICE + 1);
1611        }
1612
1613        public long getLastRejectBackgroundTime() {
1614            return maxTime(mRejectTimes, UID_STATE_FOREGROUND_SERVICE + 1, _NUM_UID_STATE);
1615        }
1616
1617        public long getLastRejectTimeFor(int uidState) {
1618            return mRejectTimes[uidState];
1619        }
1620
1621        public boolean isRunning() {
1622            return mDuration == -1;
1623        }
1624
1625        public int getDuration() {
1626            return mDuration;
1627        }
1628
1629        public int getProxyUid() {
1630            return  mProxyUid;
1631        }
1632
1633        public String getProxyPackageName() {
1634            return mProxyPackageName;
1635        }
1636
1637        @Override
1638        public int describeContents() {
1639            return 0;
1640        }
1641
1642        @Override
1643        public void writeToParcel(Parcel dest, int flags) {
1644            dest.writeInt(mOp);
1645            dest.writeInt(mMode);
1646            dest.writeLongArray(mTimes);
1647            dest.writeLongArray(mRejectTimes);
1648            dest.writeInt(mDuration);
1649            dest.writeInt(mProxyUid);
1650            dest.writeString(mProxyPackageName);
1651        }
1652
1653        OpEntry(Parcel source) {
1654            mOp = source.readInt();
1655            mMode = source.readInt();
1656            mTimes = source.createLongArray();
1657            mRejectTimes = source.createLongArray();
1658            mDuration = source.readInt();
1659            mProxyUid = source.readInt();
1660            mProxyPackageName = source.readString();
1661        }
1662
1663        public static final Creator<OpEntry> CREATOR = new Creator<OpEntry>() {
1664            @Override public OpEntry createFromParcel(Parcel source) {
1665                return new OpEntry(source);
1666            }
1667
1668            @Override public OpEntry[] newArray(int size) {
1669                return new OpEntry[size];
1670            }
1671        };
1672    }
1673
1674    /**
1675     * Callback for notification of changes to operation state.
1676     */
1677    public interface OnOpChangedListener {
1678        public void onOpChanged(String op, String packageName);
1679    }
1680
1681    /**
1682     * Callback for notification of changes to operation active state.
1683     *
1684     * @hide
1685     */
1686    @TestApi
1687    public interface OnOpActiveChangedListener {
1688        /**
1689         * Called when the active state of an app op changes.
1690         *
1691         * @param code The op code.
1692         * @param uid The UID performing the operation.
1693         * @param packageName The package performing the operation.
1694         * @param active Whether the operation became active or inactive.
1695         */
1696        void onOpActiveChanged(int code, int uid, String packageName, boolean active);
1697    }
1698
1699    /**
1700     * Callback for notification of changes to operation state.
1701     * This allows you to see the raw op codes instead of strings.
1702     * @hide
1703     */
1704    public static class OnOpChangedInternalListener implements OnOpChangedListener {
1705        public void onOpChanged(String op, String packageName) { }
1706        public void onOpChanged(int op, String packageName) { }
1707    }
1708
1709    AppOpsManager(Context context, IAppOpsService service) {
1710        mContext = context;
1711        mService = service;
1712    }
1713
1714    /**
1715     * Retrieve current operation state for all applications.
1716     *
1717     * @param ops The set of operations you are interested in, or null if you want all of them.
1718     * @hide
1719     */
1720    @RequiresPermission(android.Manifest.permission.GET_APP_OPS_STATS)
1721    public List<AppOpsManager.PackageOps> getPackagesForOps(int[] ops) {
1722        try {
1723            return mService.getPackagesForOps(ops);
1724        } catch (RemoteException e) {
1725            throw e.rethrowFromSystemServer();
1726        }
1727    }
1728
1729    /**
1730     * Retrieve current operation state for one application.
1731     *
1732     * @param uid The uid of the application of interest.
1733     * @param packageName The name of the application of interest.
1734     * @param ops The set of operations you are interested in, or null if you want all of them.
1735     * @hide
1736     */
1737    @RequiresPermission(android.Manifest.permission.GET_APP_OPS_STATS)
1738    public List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName, int[] ops) {
1739        try {
1740            return mService.getOpsForPackage(uid, packageName, ops);
1741        } catch (RemoteException e) {
1742            throw e.rethrowFromSystemServer();
1743        }
1744    }
1745
1746    /**
1747     * Sets given app op in the specified mode for app ops in the UID.
1748     * This applies to all apps currently in the UID or installed in
1749     * this UID in the future.
1750     *
1751     * @param code The app op.
1752     * @param uid The UID for which to set the app.
1753     * @param mode The app op mode to set.
1754     * @hide
1755     */
1756    @RequiresPermission(android.Manifest.permission.MANAGE_APP_OPS_MODES)
1757    public void setUidMode(int code, int uid, int mode) {
1758        try {
1759            mService.setUidMode(code, uid, mode);
1760        } catch (RemoteException e) {
1761            throw e.rethrowFromSystemServer();
1762        }
1763    }
1764
1765    /**
1766     * Sets given app op in the specified mode for app ops in the UID.
1767     * This applies to all apps currently in the UID or installed in
1768     * this UID in the future.
1769     *
1770     * @param appOp The app op.
1771     * @param uid The UID for which to set the app.
1772     * @param mode The app op mode to set.
1773     * @hide
1774     */
1775    @SystemApi
1776    @RequiresPermission(android.Manifest.permission.MANAGE_APP_OPS_MODES)
1777    public void setUidMode(String appOp, int uid, int mode) {
1778        try {
1779            mService.setUidMode(AppOpsManager.strOpToOp(appOp), uid, mode);
1780        } catch (RemoteException e) {
1781            throw e.rethrowFromSystemServer();
1782        }
1783    }
1784
1785    /** @hide */
1786    public void setUserRestriction(int code, boolean restricted, IBinder token) {
1787        setUserRestriction(code, restricted, token, /*exceptionPackages*/null);
1788    }
1789
1790    /** @hide */
1791    public void setUserRestriction(int code, boolean restricted, IBinder token,
1792            String[] exceptionPackages) {
1793        setUserRestrictionForUser(code, restricted, token, exceptionPackages, mContext.getUserId());
1794    }
1795
1796    /** @hide */
1797    public void setUserRestrictionForUser(int code, boolean restricted, IBinder token,
1798            String[] exceptionPackages, int userId) {
1799        try {
1800            mService.setUserRestriction(code, restricted, token, userId, exceptionPackages);
1801        } catch (RemoteException e) {
1802            throw e.rethrowFromSystemServer();
1803        }
1804    }
1805
1806    /** @hide */
1807    @TestApi
1808    @RequiresPermission(android.Manifest.permission.MANAGE_APP_OPS_MODES)
1809    public void setMode(int code, int uid, String packageName, int mode) {
1810        try {
1811            mService.setMode(code, uid, packageName, mode);
1812        } catch (RemoteException e) {
1813            throw e.rethrowFromSystemServer();
1814        }
1815    }
1816
1817    /**
1818     * Change the operating mode for the given op in the given app package.  You must pass
1819     * in both the uid and name of the application whose mode is being modified; if these
1820     * do not match, the modification will not be applied.
1821     *
1822     * @param op The operation to modify.  One of the OPSTR_* constants.
1823     * @param uid The user id of the application whose mode will be changed.
1824     * @param packageName The name of the application package name whose mode will
1825     * be changed.
1826     * @hide
1827     */
1828    @SystemApi
1829    @RequiresPermission(android.Manifest.permission.MANAGE_APP_OPS_MODES)
1830    public void setMode(String op, int uid, String packageName, int mode) {
1831        try {
1832            mService.setMode(strOpToOp(op), uid, packageName, mode);
1833        } catch (RemoteException e) {
1834            throw e.rethrowFromSystemServer();
1835        }
1836    }
1837
1838    /**
1839     * Set a non-persisted restriction on an audio operation at a stream-level.
1840     * Restrictions are temporary additional constraints imposed on top of the persisted rules
1841     * defined by {@link #setMode}.
1842     *
1843     * @param code The operation to restrict.
1844     * @param usage The {@link android.media.AudioAttributes} usage value.
1845     * @param mode The restriction mode (MODE_IGNORED,MODE_ERRORED) or MODE_ALLOWED to unrestrict.
1846     * @param exceptionPackages Optional list of packages to exclude from the restriction.
1847     * @hide
1848     */
1849    @RequiresPermission(android.Manifest.permission.MANAGE_APP_OPS_MODES)
1850    public void setRestriction(int code, @AttributeUsage int usage, int mode,
1851            String[] exceptionPackages) {
1852        try {
1853            final int uid = Binder.getCallingUid();
1854            mService.setAudioRestriction(code, usage, uid, mode, exceptionPackages);
1855        } catch (RemoteException e) {
1856            throw e.rethrowFromSystemServer();
1857        }
1858    }
1859
1860    /** @hide */
1861    @RequiresPermission(android.Manifest.permission.MANAGE_APP_OPS_MODES)
1862    public void resetAllModes() {
1863        try {
1864            mService.resetAllModes(mContext.getUserId(), null);
1865        } catch (RemoteException e) {
1866            throw e.rethrowFromSystemServer();
1867        }
1868    }
1869
1870    /**
1871     * Gets the app op name associated with a given permission.
1872     * The app op name is one of the public constants defined
1873     * in this class such as {@link #OPSTR_COARSE_LOCATION}.
1874     * This API is intended to be used for mapping runtime
1875     * permissions to the corresponding app op.
1876     *
1877     * @param permission The permission.
1878     * @return The app op associated with the permission or null.
1879     */
1880    public static String permissionToOp(String permission) {
1881        final Integer opCode = sPermToOp.get(permission);
1882        if (opCode == null) {
1883            return null;
1884        }
1885        return sOpToString[opCode];
1886    }
1887
1888    /**
1889     * Monitor for changes to the operating mode for the given op in the given app package.
1890     * You can watch op changes only for your UID.
1891     *
1892     * @param op The operation to monitor, one of OPSTR_*.
1893     * @param packageName The name of the application to monitor.
1894     * @param callback Where to report changes.
1895     */
1896    public void startWatchingMode(String op, String packageName,
1897            final OnOpChangedListener callback) {
1898        startWatchingMode(strOpToOp(op), packageName, callback);
1899    }
1900
1901    /**
1902     * Monitor for changes to the operating mode for the given op in the given app package.
1903     *
1904     * <p> If you don't hold the {@link android.Manifest.permission#WATCH_APPOPS} permission
1905     * you can watch changes only for your UID.
1906     *
1907     * @param op The operation to monitor, one of OP_*.
1908     * @param packageName The name of the application to monitor.
1909     * @param callback Where to report changes.
1910     * @hide
1911     */
1912    @RequiresPermission(value=android.Manifest.permission.WATCH_APPOPS, conditional=true)
1913    public void startWatchingMode(int op, String packageName, final OnOpChangedListener callback) {
1914        synchronized (mModeWatchers) {
1915            IAppOpsCallback cb = mModeWatchers.get(callback);
1916            if (cb == null) {
1917                cb = new IAppOpsCallback.Stub() {
1918                    public void opChanged(int op, int uid, String packageName) {
1919                        if (callback instanceof OnOpChangedInternalListener) {
1920                            ((OnOpChangedInternalListener)callback).onOpChanged(op, packageName);
1921                        }
1922                        if (sOpToString[op] != null) {
1923                            callback.onOpChanged(sOpToString[op], packageName);
1924                        }
1925                    }
1926                };
1927                mModeWatchers.put(callback, cb);
1928            }
1929            try {
1930                mService.startWatchingMode(op, packageName, cb);
1931            } catch (RemoteException e) {
1932                throw e.rethrowFromSystemServer();
1933            }
1934        }
1935    }
1936
1937    /**
1938     * Stop monitoring that was previously started with {@link #startWatchingMode}.  All
1939     * monitoring associated with this callback will be removed.
1940     */
1941    public void stopWatchingMode(OnOpChangedListener callback) {
1942        synchronized (mModeWatchers) {
1943            IAppOpsCallback cb = mModeWatchers.get(callback);
1944            if (cb != null) {
1945                try {
1946                    mService.stopWatchingMode(cb);
1947                } catch (RemoteException e) {
1948                    throw e.rethrowFromSystemServer();
1949                }
1950            }
1951        }
1952    }
1953
1954    /**
1955     * Start watching for changes to the active state of app ops. An app op may be
1956     * long running and it has a clear start and stop delimiters. If an op is being
1957     * started or stopped by any package you will get a callback. To change the
1958     * watched ops for a registered callback you need to unregister and register it
1959     * again.
1960     *
1961     * <p> If you don't hold the {@link android.Manifest.permission#WATCH_APPOPS} permission
1962     * you can watch changes only for your UID.
1963     *
1964     * @param ops The ops to watch.
1965     * @param callback Where to report changes.
1966     *
1967     * @see #isOperationActive(int, int, String)
1968     * @see #stopWatchingActive(OnOpActiveChangedListener)
1969     * @see #startOp(int, int, String)
1970     * @see #finishOp(int, int, String)
1971     *
1972     * @hide
1973     */
1974    @TestApi
1975    // TODO: Uncomment below annotation once b/73559440 is fixed
1976    // @RequiresPermission(value=Manifest.permission.WATCH_APPOPS, conditional=true)
1977    public void startWatchingActive(@NonNull int[] ops,
1978            @NonNull OnOpActiveChangedListener callback) {
1979        Preconditions.checkNotNull(ops, "ops cannot be null");
1980        Preconditions.checkNotNull(callback, "callback cannot be null");
1981        IAppOpsActiveCallback cb;
1982        synchronized (mActiveWatchers) {
1983            cb = mActiveWatchers.get(callback);
1984            if (cb != null) {
1985                return;
1986            }
1987            cb = new IAppOpsActiveCallback.Stub() {
1988                @Override
1989                public void opActiveChanged(int op, int uid, String packageName, boolean active) {
1990                    callback.onOpActiveChanged(op, uid, packageName, active);
1991                }
1992            };
1993            mActiveWatchers.put(callback, cb);
1994        }
1995        try {
1996            mService.startWatchingActive(ops, cb);
1997        } catch (RemoteException e) {
1998            throw e.rethrowFromSystemServer();
1999        }
2000    }
2001
2002    /**
2003     * Stop watching for changes to the active state of an app op. An app op may be
2004     * long running and it has a clear start and stop delimiters. Unregistering a
2005     * non-registered callback has no effect.
2006     *
2007     * @see #isOperationActive#(int, int, String)
2008     * @see #startWatchingActive(int[], OnOpActiveChangedListener)
2009     * @see #startOp(int, int, String)
2010     * @see #finishOp(int, int, String)
2011     *
2012     * @hide
2013     */
2014    @TestApi
2015    public void stopWatchingActive(@NonNull OnOpActiveChangedListener callback) {
2016        synchronized (mActiveWatchers) {
2017            final IAppOpsActiveCallback cb = mActiveWatchers.get(callback);
2018            if (cb != null) {
2019                try {
2020                    mService.stopWatchingActive(cb);
2021                } catch (RemoteException e) {
2022                    throw e.rethrowFromSystemServer();
2023                }
2024            }
2025        }
2026    }
2027
2028    private String buildSecurityExceptionMsg(int op, int uid, String packageName) {
2029        return packageName + " from uid " + uid + " not allowed to perform " + sOpNames[op];
2030    }
2031
2032    /**
2033     * {@hide}
2034     */
2035    public static int strOpToOp(String op) {
2036        Integer val = sOpStrToOp.get(op);
2037        if (val == null) {
2038            throw new IllegalArgumentException("Unknown operation string: " + op);
2039        }
2040        return val;
2041    }
2042
2043    /**
2044     * Do a quick check for whether an application might be able to perform an operation.
2045     * This is <em>not</em> a security check; you must use {@link #noteOp(String, int, String)}
2046     * or {@link #startOp(String, int, String)} for your actual security checks, which also
2047     * ensure that the given uid and package name are consistent.  This function can just be
2048     * used for a quick check to see if an operation has been disabled for the application,
2049     * as an early reject of some work.  This does not modify the time stamp or other data
2050     * about the operation.
2051     *
2052     * <p>Important things this will not do (which you need to ultimate use
2053     * {@link #noteOp(String, int, String)} or {@link #startOp(String, int, String)} to cover):</p>
2054     * <ul>
2055     *     <li>Verifying the uid and package are consistent, so callers can't spoof
2056     *     their identity.</li>
2057     *     <li>Taking into account the current foreground/background state of the
2058     *     app; apps whose mode varies by this state will always be reported
2059     *     as {@link #MODE_ALLOWED}.</li>
2060     * </ul>
2061     *
2062     * @param op The operation to check.  One of the OPSTR_* constants.
2063     * @param uid The user id of the application attempting to perform the operation.
2064     * @param packageName The name of the application attempting to perform the operation.
2065     * @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or
2066     * {@link #MODE_IGNORED} if it is not allowed and should be silently ignored (without
2067     * causing the app to crash).
2068     * @throws SecurityException If the app has been configured to crash on this op.
2069     */
2070    public int checkOp(String op, int uid, String packageName) {
2071        return checkOp(strOpToOp(op), uid, packageName);
2072    }
2073
2074    /**
2075     * Like {@link #checkOp} but instead of throwing a {@link SecurityException} it
2076     * returns {@link #MODE_ERRORED}.
2077     */
2078    public int checkOpNoThrow(String op, int uid, String packageName) {
2079        return checkOpNoThrow(strOpToOp(op), uid, packageName);
2080    }
2081
2082    /**
2083     * Make note of an application performing an operation.  Note that you must pass
2084     * in both the uid and name of the application to be checked; this function will verify
2085     * that these two match, and if not, return {@link #MODE_IGNORED}.  If this call
2086     * succeeds, the last execution time of the operation for this app will be updated to
2087     * the current time.
2088     * @param op The operation to note.  One of the OPSTR_* constants.
2089     * @param uid The user id of the application attempting to perform the operation.
2090     * @param packageName The name of the application attempting to perform the operation.
2091     * @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or
2092     * {@link #MODE_IGNORED} if it is not allowed and should be silently ignored (without
2093     * causing the app to crash).
2094     * @throws SecurityException If the app has been configured to crash on this op.
2095     */
2096    public int noteOp(String op, int uid, String packageName) {
2097        return noteOp(strOpToOp(op), uid, packageName);
2098    }
2099
2100    /**
2101     * Like {@link #noteOp} but instead of throwing a {@link SecurityException} it
2102     * returns {@link #MODE_ERRORED}.
2103     */
2104    public int noteOpNoThrow(String op, int uid, String packageName) {
2105        return noteOpNoThrow(strOpToOp(op), uid, packageName);
2106    }
2107
2108    /**
2109     * Make note of an application performing an operation on behalf of another
2110     * application when handling an IPC. Note that you must pass the package name
2111     * of the application that is being proxied while its UID will be inferred from
2112     * the IPC state; this function will verify that the calling uid and proxied
2113     * package name match, and if not, return {@link #MODE_IGNORED}. If this call
2114     * succeeds, the last execution time of the operation for the proxied app and
2115     * your app will be updated to the current time.
2116     * @param op The operation to note.  One of the OPSTR_* constants.
2117     * @param proxiedPackageName The name of the application calling into the proxy application.
2118     * @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or
2119     * {@link #MODE_IGNORED} if it is not allowed and should be silently ignored (without
2120     * causing the app to crash).
2121     * @throws SecurityException If the app has been configured to crash on this op.
2122     */
2123    public int noteProxyOp(String op, String proxiedPackageName) {
2124        return noteProxyOp(strOpToOp(op), proxiedPackageName);
2125    }
2126
2127    /**
2128     * Like {@link #noteProxyOp(String, String)} but instead
2129     * of throwing a {@link SecurityException} it returns {@link #MODE_ERRORED}.
2130     */
2131    public int noteProxyOpNoThrow(String op, String proxiedPackageName) {
2132        return noteProxyOpNoThrow(strOpToOp(op), proxiedPackageName);
2133    }
2134
2135    /**
2136     * Report that an application has started executing a long-running operation.  Note that you
2137     * must pass in both the uid and name of the application to be checked; this function will
2138     * verify that these two match, and if not, return {@link #MODE_IGNORED}.  If this call
2139     * succeeds, the last execution time of the operation for this app will be updated to
2140     * the current time and the operation will be marked as "running".  In this case you must
2141     * later call {@link #finishOp(String, int, String)} to report when the application is no
2142     * longer performing the operation.
2143     * @param op The operation to start.  One of the OPSTR_* constants.
2144     * @param uid The user id of the application attempting to perform the operation.
2145     * @param packageName The name of the application attempting to perform the operation.
2146     * @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or
2147     * {@link #MODE_IGNORED} if it is not allowed and should be silently ignored (without
2148     * causing the app to crash).
2149     * @throws SecurityException If the app has been configured to crash on this op.
2150     */
2151    public int startOp(String op, int uid, String packageName) {
2152        return startOp(strOpToOp(op), uid, packageName);
2153    }
2154
2155    /**
2156     * Like {@link #startOp} but instead of throwing a {@link SecurityException} it
2157     * returns {@link #MODE_ERRORED}.
2158     */
2159    public int startOpNoThrow(String op, int uid, String packageName) {
2160        return startOpNoThrow(strOpToOp(op), uid, packageName);
2161    }
2162
2163    /**
2164     * Report that an application is no longer performing an operation that had previously
2165     * been started with {@link #startOp(String, int, String)}.  There is no validation of input
2166     * or result; the parameters supplied here must be the exact same ones previously passed
2167     * in when starting the operation.
2168     */
2169    public void finishOp(String op, int uid, String packageName) {
2170        finishOp(strOpToOp(op), uid, packageName);
2171    }
2172
2173    /**
2174     * Do a quick check for whether an application might be able to perform an operation.
2175     * This is <em>not</em> a security check; you must use {@link #noteOp(int, int, String)}
2176     * or {@link #startOp(int, int, String)} for your actual security checks, which also
2177     * ensure that the given uid and package name are consistent.  This function can just be
2178     * used for a quick check to see if an operation has been disabled for the application,
2179     * as an early reject of some work.  This does not modify the time stamp or other data
2180     * about the operation.
2181     *
2182     * <p>Important things this will not do (which you need to ultimate use
2183     * {@link #noteOp(int, int, String)} or {@link #startOp(int, int, String)} to cover):</p>
2184     * <ul>
2185     *     <li>Verifying the uid and package are consistent, so callers can't spoof
2186     *     their identity.</li>
2187     *     <li>Taking into account the current foreground/background state of the
2188     *     app; apps whose mode varies by this state will always be reported
2189     *     as {@link #MODE_ALLOWED}.</li>
2190     * </ul>
2191     *
2192     * @param op The operation to check.  One of the OP_* constants.
2193     * @param uid The user id of the application attempting to perform the operation.
2194     * @param packageName The name of the application attempting to perform the operation.
2195     * @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or
2196     * {@link #MODE_IGNORED} if it is not allowed and should be silently ignored (without
2197     * causing the app to crash).
2198     * @throws SecurityException If the app has been configured to crash on this op.
2199     * @hide
2200     */
2201    public int checkOp(int op, int uid, String packageName) {
2202        try {
2203            int mode = mService.checkOperation(op, uid, packageName);
2204            if (mode == MODE_ERRORED) {
2205                throw new SecurityException(buildSecurityExceptionMsg(op, uid, packageName));
2206            }
2207            return mode;
2208        } catch (RemoteException e) {
2209            throw e.rethrowFromSystemServer();
2210        }
2211    }
2212
2213    /**
2214     * Like {@link #checkOp} but instead of throwing a {@link SecurityException} it
2215     * returns {@link #MODE_ERRORED}.
2216     * @hide
2217     */
2218    public int checkOpNoThrow(int op, int uid, String packageName) {
2219        try {
2220            return mService.checkOperation(op, uid, packageName);
2221        } catch (RemoteException e) {
2222            throw e.rethrowFromSystemServer();
2223        }
2224    }
2225
2226    /**
2227     * Do a quick check to validate if a package name belongs to a UID.
2228     *
2229     * @throws SecurityException if the package name doesn't belong to the given
2230     *             UID, or if ownership cannot be verified.
2231     */
2232    public void checkPackage(int uid, String packageName) {
2233        try {
2234            if (mService.checkPackage(uid, packageName) != MODE_ALLOWED) {
2235                throw new SecurityException(
2236                        "Package " + packageName + " does not belong to " + uid);
2237            }
2238        } catch (RemoteException e) {
2239            throw e.rethrowFromSystemServer();
2240        }
2241    }
2242
2243    /**
2244     * Like {@link #checkOp} but at a stream-level for audio operations.
2245     * @hide
2246     */
2247    public int checkAudioOp(int op, int stream, int uid, String packageName) {
2248        try {
2249            final int mode = mService.checkAudioOperation(op, stream, uid, packageName);
2250            if (mode == MODE_ERRORED) {
2251                throw new SecurityException(buildSecurityExceptionMsg(op, uid, packageName));
2252            }
2253            return mode;
2254        } catch (RemoteException e) {
2255            throw e.rethrowFromSystemServer();
2256        }
2257    }
2258
2259    /**
2260     * Like {@link #checkAudioOp} but instead of throwing a {@link SecurityException} it
2261     * returns {@link #MODE_ERRORED}.
2262     * @hide
2263     */
2264    public int checkAudioOpNoThrow(int op, int stream, int uid, String packageName) {
2265        try {
2266            return mService.checkAudioOperation(op, stream, uid, packageName);
2267        } catch (RemoteException e) {
2268            throw e.rethrowFromSystemServer();
2269        }
2270    }
2271
2272    /**
2273     * Make note of an application performing an operation.  Note that you must pass
2274     * in both the uid and name of the application to be checked; this function will verify
2275     * that these two match, and if not, return {@link #MODE_IGNORED}.  If this call
2276     * succeeds, the last execution time of the operation for this app will be updated to
2277     * the current time.
2278     * @param op The operation to note.  One of the OP_* constants.
2279     * @param uid The user id of the application attempting to perform the operation.
2280     * @param packageName The name of the application attempting to perform the operation.
2281     * @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or
2282     * {@link #MODE_IGNORED} if it is not allowed and should be silently ignored (without
2283     * causing the app to crash).
2284     * @throws SecurityException If the app has been configured to crash on this op.
2285     * @hide
2286     */
2287    public int noteOp(int op, int uid, String packageName) {
2288        final int mode = noteOpNoThrow(op, uid, packageName);
2289        if (mode == MODE_ERRORED) {
2290            throw new SecurityException(buildSecurityExceptionMsg(op, uid, packageName));
2291        }
2292        return mode;
2293    }
2294
2295    /**
2296     * Make note of an application performing an operation on behalf of another
2297     * application when handling an IPC. Note that you must pass the package name
2298     * of the application that is being proxied while its UID will be inferred from
2299     * the IPC state; this function will verify that the calling uid and proxied
2300     * package name match, and if not, return {@link #MODE_IGNORED}. If this call
2301     * succeeds, the last execution time of the operation for the proxied app and
2302     * your app will be updated to the current time.
2303     * @param op The operation to note. One of the OPSTR_* constants.
2304     * @param proxiedPackageName The name of the application calling into the proxy application.
2305     * @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or
2306     * {@link #MODE_IGNORED} if it is not allowed and should be silently ignored (without
2307     * causing the app to crash).
2308     * @throws SecurityException If the proxy or proxied app has been configured to
2309     * crash on this op.
2310     *
2311     * @hide
2312     */
2313    public int noteProxyOp(int op, String proxiedPackageName) {
2314        int mode = noteProxyOpNoThrow(op, proxiedPackageName);
2315        if (mode == MODE_ERRORED) {
2316            throw new SecurityException("Proxy package " + mContext.getOpPackageName()
2317                    + " from uid " + Process.myUid() + " or calling package "
2318                    + proxiedPackageName + " from uid " + Binder.getCallingUid()
2319                    + " not allowed to perform " + sOpNames[op]);
2320        }
2321        return mode;
2322    }
2323
2324    /**
2325     * Like {@link #noteProxyOp(int, String)} but instead
2326     * of throwing a {@link SecurityException} it returns {@link #MODE_ERRORED}.
2327     * @hide
2328     */
2329    public int noteProxyOpNoThrow(int op, String proxiedPackageName) {
2330        try {
2331            return mService.noteProxyOperation(op, mContext.getOpPackageName(),
2332                    Binder.getCallingUid(), proxiedPackageName);
2333        } catch (RemoteException e) {
2334            throw e.rethrowFromSystemServer();
2335        }
2336    }
2337
2338    /**
2339     * Like {@link #noteOp} but instead of throwing a {@link SecurityException} it
2340     * returns {@link #MODE_ERRORED}.
2341     * @hide
2342     */
2343    public int noteOpNoThrow(int op, int uid, String packageName) {
2344        try {
2345            return mService.noteOperation(op, uid, packageName);
2346        } catch (RemoteException e) {
2347            throw e.rethrowFromSystemServer();
2348        }
2349    }
2350
2351    /** @hide */
2352    public int noteOp(int op) {
2353        return noteOp(op, Process.myUid(), mContext.getOpPackageName());
2354    }
2355
2356    /** @hide */
2357    public static IBinder getToken(IAppOpsService service) {
2358        synchronized (AppOpsManager.class) {
2359            if (sToken != null) {
2360                return sToken;
2361            }
2362            try {
2363                sToken = service.getToken(new Binder());
2364            } catch (RemoteException e) {
2365                throw e.rethrowFromSystemServer();
2366            }
2367            return sToken;
2368        }
2369    }
2370
2371    /** @hide */
2372    public int startOp(int op) {
2373        return startOp(op, Process.myUid(), mContext.getOpPackageName());
2374    }
2375
2376    /**
2377     * Report that an application has started executing a long-running operation.  Note that you
2378     * must pass in both the uid and name of the application to be checked; this function will
2379     * verify that these two match, and if not, return {@link #MODE_IGNORED}.  If this call
2380     * succeeds, the last execution time of the operation for this app will be updated to
2381     * the current time and the operation will be marked as "running".  In this case you must
2382     * later call {@link #finishOp(int, int, String)} to report when the application is no
2383     * longer performing the operation.
2384     *
2385     * @param op The operation to start.  One of the OP_* constants.
2386     * @param uid The user id of the application attempting to perform the operation.
2387     * @param packageName The name of the application attempting to perform the operation.
2388     * @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or
2389     * {@link #MODE_IGNORED} if it is not allowed and should be silently ignored (without
2390     * causing the app to crash).
2391     * @throws SecurityException If the app has been configured to crash on this op.
2392     * @hide
2393     */
2394    public int startOp(int op, int uid, String packageName) {
2395        return startOp(op, uid, packageName, false);
2396    }
2397
2398    /**
2399     * Report that an application has started executing a long-running operation. Similar
2400     * to {@link #startOp(String, int, String) except that if the mode is {@link #MODE_DEFAULT}
2401     * the operation should succeed since the caller has performed its standard permission
2402     * checks which passed and would perform the protected operation for this mode.
2403     *
2404     * @param op The operation to start.  One of the OP_* constants.
2405     * @param uid The user id of the application attempting to perform the operation.
2406     * @param packageName The name of the application attempting to perform the operation.
2407     * @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or
2408     * {@link #MODE_IGNORED} if it is not allowed and should be silently ignored (without
2409     * causing the app to crash).
2410     * @param startIfModeDefault Whether to start if mode is {@link #MODE_DEFAULT}.
2411     *
2412     * @throws SecurityException If the app has been configured to crash on this op or
2413     * the package is not in the passed in UID.
2414     *
2415     * @hide
2416     */
2417    public int startOp(int op, int uid, String packageName, boolean startIfModeDefault) {
2418        final int mode = startOpNoThrow(op, uid, packageName, startIfModeDefault);
2419        if (mode == MODE_ERRORED) {
2420            throw new SecurityException(buildSecurityExceptionMsg(op, uid, packageName));
2421        }
2422        return mode;
2423    }
2424
2425    /**
2426     * Like {@link #startOp} but instead of throwing a {@link SecurityException} it
2427     * returns {@link #MODE_ERRORED}.
2428     * @hide
2429     */
2430    public int startOpNoThrow(int op, int uid, String packageName) {
2431        return startOpNoThrow(op, uid, packageName, false);
2432    }
2433
2434    /**
2435     * Like {@link #startOp(int, int, String, boolean)} but instead of throwing a
2436     * {@link SecurityException} it returns {@link #MODE_ERRORED}.
2437     *
2438     * @param op The operation to start.  One of the OP_* constants.
2439     * @param uid The user id of the application attempting to perform the operation.
2440     * @param packageName The name of the application attempting to perform the operation.
2441     * @return Returns {@link #MODE_ALLOWED} if the operation is allowed, or
2442     * {@link #MODE_IGNORED} if it is not allowed and should be silently ignored (without
2443     * causing the app to crash).
2444     * @param startIfModeDefault Whether to start if mode is {@link #MODE_DEFAULT}.
2445     *
2446     * @hide
2447     */
2448    public int startOpNoThrow(int op, int uid, String packageName, boolean startIfModeDefault) {
2449        try {
2450            return mService.startOperation(getToken(mService), op, uid, packageName,
2451                    startIfModeDefault);
2452        } catch (RemoteException e) {
2453            throw e.rethrowFromSystemServer();
2454        }
2455    }
2456
2457    /**
2458     * Report that an application is no longer performing an operation that had previously
2459     * been started with {@link #startOp(int, int, String)}.  There is no validation of input
2460     * or result; the parameters supplied here must be the exact same ones previously passed
2461     * in when starting the operation.
2462     * @hide
2463     */
2464    public void finishOp(int op, int uid, String packageName) {
2465        try {
2466            mService.finishOperation(getToken(mService), op, uid, packageName);
2467        } catch (RemoteException e) {
2468            throw e.rethrowFromSystemServer();
2469        }
2470    }
2471
2472    /** @hide */
2473    public void finishOp(int op) {
2474        finishOp(op, Process.myUid(), mContext.getOpPackageName());
2475    }
2476
2477    /**
2478     * Checks whether the given op for a UID and package is active.
2479     *
2480     * <p> If you don't hold the {@link android.Manifest.permission#WATCH_APPOPS} permission
2481     * you can query only for your UID.
2482     *
2483     * @see #startWatchingActive(int[], OnOpActiveChangedListener)
2484     * @see #stopWatchingMode(OnOpChangedListener)
2485     * @see #finishOp(int)
2486     * @see #startOp(int)
2487     *
2488     * @hide */
2489    @TestApi
2490    // TODO: Uncomment below annotation once b/73559440 is fixed
2491    // @RequiresPermission(value=Manifest.permission.WATCH_APPOPS, conditional=true)
2492    public boolean isOperationActive(int code, int uid, String packageName) {
2493        try {
2494            return mService.isOperationActive(code, uid, packageName);
2495        } catch (RemoteException e) {
2496            throw e.rethrowFromSystemServer();
2497        }
2498    }
2499
2500    /**
2501     * Returns all supported operation names.
2502     * @hide
2503     */
2504    @SystemApi
2505    @TestApi
2506    public static String[] getOpStrs() {
2507        return Arrays.copyOf(sOpToString, sOpToString.length);
2508    }
2509
2510    /**
2511     * @hide
2512     */
2513    public static long maxTime(long[] times, int start, int end) {
2514        long time = 0;
2515        for (int i = start; i < end; i++) {
2516            if (times[i] > time) {
2517                time = times[i];
2518            }
2519        }
2520        return time;
2521    }
2522}
2523