blob: 18d5ced137a8c6414b64d48e59651d9b1cfea04b [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Maggieaa080f92018-01-04 15:35:11 -080019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
20
Wyatt Rileycf879db2017-01-12 13:57:38 -080021import android.annotation.NonNull;
Wyatt Riley49097c02018-03-15 09:14:43 -070022import android.annotation.Nullable;
Maggieaa080f92018-01-04 15:35:11 -080023import android.app.ActivityManager;
24import android.app.AppOpsManager;
25import android.app.PendingIntent;
26import android.content.BroadcastReceiver;
27import android.content.ContentResolver;
28import android.content.Context;
29import android.content.Intent;
30import android.content.IntentFilter;
31import android.content.pm.ApplicationInfo;
32import android.content.pm.PackageInfo;
33import android.content.pm.PackageManager;
34import android.content.pm.PackageManager.NameNotFoundException;
35import android.content.pm.PackageManagerInternal;
36import android.content.pm.ResolveInfo;
37import android.content.pm.Signature;
38import android.content.res.Resources;
39import android.database.ContentObserver;
40import android.hardware.location.ActivityRecognitionHardware;
41import android.location.Address;
42import android.location.Criteria;
43import android.location.GeocoderParams;
44import android.location.Geofence;
45import android.location.IBatchedLocationCallback;
46import android.location.IGnssMeasurementsListener;
47import android.location.IGnssNavigationMessageListener;
48import android.location.IGnssStatusListener;
49import android.location.IGnssStatusProvider;
50import android.location.IGpsGeofenceHardware;
51import android.location.ILocationListener;
52import android.location.ILocationManager;
53import android.location.INetInitiatedListener;
54import android.location.Location;
55import android.location.LocationManager;
56import android.location.LocationProvider;
57import android.location.LocationRequest;
58import android.os.Binder;
59import android.os.Bundle;
60import android.os.Handler;
61import android.os.IBinder;
62import android.os.Looper;
63import android.os.Message;
64import android.os.PowerManager;
65import android.os.Process;
66import android.os.RemoteException;
67import android.os.SystemClock;
68import android.os.UserHandle;
69import android.os.UserManager;
70import android.os.WorkSource;
Narayan Kamath32684dd2018-01-08 17:32:51 +000071import android.os.WorkSource.WorkChain;
Maggieaa080f92018-01-04 15:35:11 -080072import android.provider.Settings;
73import android.text.TextUtils;
Soonil Nagarkar681d7112017-02-23 17:14:16 -080074import android.util.ArrayMap;
Soonil Nagarkar2b565df2017-02-14 13:33:23 -080075import android.util.ArraySet;
Maggieaa080f92018-01-04 15:35:11 -080076import android.util.EventLog;
77import android.util.Log;
78import android.util.Slog;
destradaaea8a8a62014-06-23 18:19:03 -070079import com.android.internal.content.PackageMonitor;
80import com.android.internal.location.ProviderProperties;
81import com.android.internal.location.ProviderRequest;
82import com.android.internal.os.BackgroundThread;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070083import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060084import com.android.internal.util.DumpUtils;
destradaaa4fa3b52014-07-09 10:46:39 -070085import com.android.server.location.ActivityRecognitionProxy;
destradaaea8a8a62014-06-23 18:19:03 -070086import com.android.server.location.GeocoderProxy;
87import com.android.server.location.GeofenceManager;
88import com.android.server.location.GeofenceProxy;
Lifu Tang818aa2c2016-02-01 01:52:00 -080089import com.android.server.location.GnssLocationProvider;
90import com.android.server.location.GnssMeasurementsProvider;
91import com.android.server.location.GnssNavigationMessageProvider;
destradaaea8a8a62014-06-23 18:19:03 -070092import com.android.server.location.LocationBlacklist;
93import com.android.server.location.LocationFudger;
94import com.android.server.location.LocationProviderInterface;
95import com.android.server.location.LocationProviderProxy;
96import com.android.server.location.LocationRequestStatistics;
97import com.android.server.location.LocationRequestStatistics.PackageProviderKey;
98import com.android.server.location.LocationRequestStatistics.PackageStatistics;
99import com.android.server.location.MockProvider;
100import com.android.server.location.PassiveProvider;
Mike Lockwood43e33f22010-03-26 10:41:48 -0400101import java.io.FileDescriptor;
102import java.io.PrintWriter;
103import java.util.ArrayList;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700104import java.util.Arrays;
Mike Lockwood43e33f22010-03-26 10:41:48 -0400105import java.util.HashMap;
106import java.util.HashSet;
107import java.util.List;
108import java.util.Map;
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800109import java.util.Map.Entry;
Wyatt Rileycf879db2017-01-12 13:57:38 -0800110import java.util.NoSuchElementException;
Mike Lockwood43e33f22010-03-26 10:41:48 -0400111import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112
113/**
114 * The service class that manages LocationProviders and issues location
115 * updates and alerts.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116 */
Victoria Lease5cd731a2012-12-19 15:04:21 -0800117public class LocationManagerService extends ILocationManager.Stub {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 private static final String TAG = "LocationManagerService";
JP Abgrallf79811e72013-02-01 18:45:05 -0800119 public static final boolean D = Log.isLoggable(TAG, Log.DEBUG);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700120
Olivier Gaillard7a222662017-11-20 16:07:24 +0000121 private static final String WAKELOCK_KEY = "*location*";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122
Victoria Lease37425c32012-10-16 16:08:48 -0700123 // Location resolution level: no location data whatsoever
124 private static final int RESOLUTION_LEVEL_NONE = 0;
125 // Location resolution level: coarse location data only
126 private static final int RESOLUTION_LEVEL_COARSE = 1;
127 // Location resolution level: fine location data
128 private static final int RESOLUTION_LEVEL_FINE = 2;
129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130 private static final String ACCESS_MOCK_LOCATION =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700131 android.Manifest.permission.ACCESS_MOCK_LOCATION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 private static final String ACCESS_LOCATION_EXTRA_COMMANDS =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700133 android.Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS;
Mike Lockwood275555c2009-05-01 11:30:34 -0400134 private static final String INSTALL_LOCATION_PROVIDER =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700135 android.Manifest.permission.INSTALL_LOCATION_PROVIDER;
136
137 private static final String NETWORK_LOCATION_SERVICE_ACTION =
Stan Chesnutt39062dd2013-07-22 14:33:30 -0700138 "com.android.location.service.v3.NetworkLocationProvider";
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700139 private static final String FUSED_LOCATION_SERVICE_ACTION =
140 "com.android.location.service.FusedLocationProvider";
141
142 private static final int MSG_LOCATION_CHANGED = 1;
143
David Christie1b9b7b12013-04-15 15:31:11 -0700144 private static final long NANOS_PER_MILLI = 1000000L;
145
David Christie0b837452013-07-29 16:02:13 -0700146 // The maximum interval a location request can have and still be considered "high power".
147 private static final long HIGH_POWER_INTERVAL_MS = 5 * 60 * 1000;
148
Soonil Nagarkarebda0282017-04-10 14:55:37 -0700149 private static final int FOREGROUND_IMPORTANCE_CUTOFF
gomo48f1a642017-11-10 20:35:46 -0800150 = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE;
Soonil Nagarkarebda0282017-04-10 14:55:37 -0700151
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800152 // default background throttling interval if not overriden in settings
Soonil Nagarkarde6780a2017-02-07 10:39:41 -0800153 private static final long DEFAULT_BACKGROUND_THROTTLE_INTERVAL_MS = 30 * 60 * 1000;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800154
Nick Pellyf1be6862012-05-15 10:53:42 -0700155 // Location Providers may sometimes deliver location updates
156 // slightly faster that requested - provide grace period so
157 // we don't unnecessarily filter events that are otherwise on
158 // time
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700159 private static final int MAX_PROVIDER_SCHEDULING_JITTER_MS = 100;
Nick Pellyf1be6862012-05-15 10:53:42 -0700160
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700161 private static final LocationRequest DEFAULT_LOCATION_REQUEST = new LocationRequest();
162
163 private final Context mContext;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800164 private final AppOpsManager mAppOps;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700165
166 // used internally for synchronization
167 private final Object mLock = new Object();
168
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700169 // --- fields below are final after systemRunning() ---
Nick Pelly74fa7ea2012-08-13 19:36:38 -0700170 private LocationFudger mLocationFudger;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700171 private GeofenceManager mGeofenceManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700172 private PackageManager mPackageManager;
Victoria Lease0aa28602013-05-29 15:28:26 -0700173 private PowerManager mPowerManager;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800174 private ActivityManager mActivityManager;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700175 private UserManager mUserManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700176 private GeocoderProxy mGeocodeProvider;
Lifu Tang30f95a72016-01-07 23:20:38 -0800177 private IGnssStatusProvider mGnssStatusProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700178 private INetInitiatedListener mNetInitiatedListener;
179 private LocationWorkerHandler mLocationHandler;
Nick Pelly4035f5a2012-08-17 14:43:49 -0700180 private PassiveProvider mPassiveProvider; // track passive provider for special cases
181 private LocationBlacklist mBlacklist;
Lifu Tang818aa2c2016-02-01 01:52:00 -0800182 private GnssMeasurementsProvider mGnssMeasurementsProvider;
183 private GnssNavigationMessageProvider mGnssNavigationMessageProvider;
Wei Liu5241a4c2015-05-11 14:00:36 -0700184 private IGpsGeofenceHardware mGpsGeofenceProxy;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700185
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700186 // --- fields below are protected by mLock ---
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 // Set of providers that are explicitly enabled
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700188 // Only used by passive, fused & test. Network & GPS are controlled separately, and not listed.
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800189 private final Set<String> mEnabledProviders = new HashSet<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190
191 // Set of providers that are explicitly disabled
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800192 private final Set<String> mDisabledProviders = new HashSet<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700194 // Mock (test) providers
195 private final HashMap<String, MockProvider> mMockProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800196 new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700198 // all receivers
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800199 private final HashMap<Object, Receiver> mReceivers = new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700201 // currently installed providers (with mocks replacing real providers)
Mike Lockwoodd03ff942010-02-09 08:46:14 -0500202 private final ArrayList<LocationProviderInterface> mProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800203 new ArrayList<>();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400204
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700205 // real providers, saved here when mocked out
206 private final HashMap<String, LocationProviderInterface> mRealProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800207 new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700209 // mapping from provider name to provider
210 private final HashMap<String, LocationProviderInterface> mProvidersByName =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800211 new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700213 // mapping from provider name to all its UpdateRecords
214 private final HashMap<String, ArrayList<UpdateRecord>> mRecordsByProvider =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800215 new HashMap<>();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700216
David Christie2ff96af2014-01-30 16:09:37 -0800217 private final LocationRequestStatistics mRequestStatistics = new LocationRequestStatistics();
218
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700219 // mapping from provider name to last known location
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800220 private final HashMap<String, Location> mLastLocation = new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221
David Christie1b9b7b12013-04-15 15:31:11 -0700222 // same as mLastLocation, but is not updated faster than LocationFudger.FASTEST_INTERVAL_MS.
223 // locations stored here are not fudged for coarse permissions.
224 private final HashMap<String, Location> mLastLocationCoarseInterval =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800225 new HashMap<>();
David Christie1b9b7b12013-04-15 15:31:11 -0700226
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800227 // all providers that operate over proxy, for authorizing incoming location and whitelisting
228 // throttling
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700229 private final ArrayList<LocationProviderProxy> mProxyProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800230 new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231
Soonil Nagarkar2b565df2017-02-14 13:33:23 -0800232 private final ArraySet<String> mBackgroundThrottlePackageWhitelist = new ArraySet<>();
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800233
Wyatt Riley11cc7492018-01-17 08:48:27 -0800234 private final ArrayMap<IBinder, Identity> mGnssMeasurementsListeners = new ArrayMap<>();
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800235
Wyatt Riley11cc7492018-01-17 08:48:27 -0800236 private final ArrayMap<IBinder, Identity>
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800237 mGnssNavigationMessageListeners = new ArrayMap<>();
238
Victoria Lease38389b62012-09-30 11:44:22 -0700239 // current active user on the device - other users are denied location data
Xiaohui Chena4490622015-09-22 15:29:31 -0700240 private int mCurrentUserId = UserHandle.USER_SYSTEM;
gomo48f1a642017-11-10 20:35:46 -0800241 private int[] mCurrentUserProfiles = new int[]{UserHandle.USER_SYSTEM};
Victoria Lease38389b62012-09-30 11:44:22 -0700242
Lifu Tang9363b942016-02-16 18:07:00 -0800243 private GnssLocationProvider.GnssSystemInfoProvider mGnssSystemInfoProvider;
Lifu Tang82f893d2016-01-21 18:15:33 -0800244
Siddharth Raybb608c82017-03-16 11:33:34 -0700245 private GnssLocationProvider.GnssMetricsProvider mGnssMetricsProvider;
Wyatt Rileyaa420d52017-07-03 15:14:42 -0700246
247 private GnssLocationProvider.GnssBatchingProvider mGnssBatchingProvider;
Wyatt Rileycf879db2017-01-12 13:57:38 -0800248 private IBatchedLocationCallback mGnssBatchingCallback;
249 private LinkedCallback mGnssBatchingDeathCallback;
250 private boolean mGnssBatchingInProgress = false;
251
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700252 public LocationManagerService(Context context) {
253 super();
254 mContext = context;
gomo48f1a642017-11-10 20:35:46 -0800255 mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800256
Svet Ganovadc1cf42015-06-15 16:36:24 -0700257 // Let the package manager query which are the default location
258 // providers as they get certain permissions granted by default.
259 PackageManagerInternal packageManagerInternal = LocalServices.getService(
260 PackageManagerInternal.class);
261 packageManagerInternal.setLocationPackagesProvider(
262 new PackageManagerInternal.PackagesProvider() {
263 @Override
264 public String[] getPackages(int userId) {
265 return mContext.getResources().getStringArray(
266 com.android.internal.R.array.config_locationProviderPackageNames);
267 }
268 });
269
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700270 if (D) Log.d(TAG, "Constructed");
271
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700272 // most startup is deferred until systemRunning()
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700273 }
274
Svetoslav Ganova0027152013-06-25 14:59:53 -0700275 public void systemRunning() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700276 synchronized (mLock) {
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700277 if (D) Log.d(TAG, "systemRunning()");
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700278
Victoria Lease5cd731a2012-12-19 15:04:21 -0800279 // fetch package manager
280 mPackageManager = mContext.getPackageManager();
281
Victoria Lease0aa28602013-05-29 15:28:26 -0700282 // fetch power manager
283 mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
Victoria Lease5cd731a2012-12-19 15:04:21 -0800284
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800285 // fetch activity manager
286 mActivityManager
287 = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
288
Victoria Lease5cd731a2012-12-19 15:04:21 -0800289 // prepare worker thread
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700290 mLocationHandler = new LocationWorkerHandler(BackgroundThread.get().getLooper());
Victoria Lease5cd731a2012-12-19 15:04:21 -0800291
292 // prepare mLocationHandler's dependents
293 mLocationFudger = new LocationFudger(mContext, mLocationHandler);
294 mBlacklist = new LocationBlacklist(mContext, mLocationHandler);
295 mBlacklist.init();
296 mGeofenceManager = new GeofenceManager(mContext, mBlacklist);
297
Dianne Hackbornc2293022013-02-06 23:14:49 -0800298 // Monitor for app ops mode changes.
Dianne Hackborn9bb0ee92013-09-22 12:31:38 -0700299 AppOpsManager.OnOpChangedListener callback
300 = new AppOpsManager.OnOpChangedInternalListener() {
301 public void onOpChanged(int op, String packageName) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800302 synchronized (mLock) {
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700303 for (Receiver receiver : mReceivers.values()) {
304 receiver.updateMonitoring(true);
305 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800306 applyAllProviderRequirementsLocked();
307 }
308 }
309 };
310 mAppOps.startWatchingMode(AppOpsManager.OP_COARSE_LOCATION, null, callback);
311
David Christieb870dbf2015-06-22 12:42:53 -0700312 PackageManager.OnPermissionsChangedListener permissionListener
313 = new PackageManager.OnPermissionsChangedListener() {
314 @Override
315 public void onPermissionsChanged(final int uid) {
316 synchronized (mLock) {
317 applyAllProviderRequirementsLocked();
318 }
319 }
320 };
321 mPackageManager.addOnPermissionsChangeListener(permissionListener);
322
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800323 // listen for background/foreground changes
324 ActivityManager.OnUidImportanceListener uidImportanceListener
325 = new ActivityManager.OnUidImportanceListener() {
326 @Override
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700327 public void onUidImportance(final int uid, final int importance) {
328 mLocationHandler.post(new Runnable() {
329 @Override
330 public void run() {
331 onUidImportanceChanged(uid, importance);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800332 }
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700333 });
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800334 }
335 };
336 mActivityManager.addOnUidImportanceListener(uidImportanceListener,
Soonil Nagarkarebda0282017-04-10 14:55:37 -0700337 FOREGROUND_IMPORTANCE_CUTOFF);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800338
Amith Yamasanib27528d2014-06-05 15:02:10 -0700339 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
340 updateUserProfiles(mCurrentUserId);
341
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800342 updateBackgroundThrottlingWhitelistLocked();
Soonil Nagarkar2b565df2017-02-14 13:33:23 -0800343
Victoria Lease5cd731a2012-12-19 15:04:21 -0800344 // prepare providers
345 loadProvidersLocked();
346 updateProvidersLocked();
347 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700348
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700349 // listen for settings changes
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700350 mContext.getContentResolver().registerContentObserver(
Laurent Tu75defb62012-11-01 16:21:52 -0700351 Settings.Secure.getUriFor(Settings.Secure.LOCATION_PROVIDERS_ALLOWED), true,
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700352 new ContentObserver(mLocationHandler) {
Victoria Lease5cd731a2012-12-19 15:04:21 -0800353 @Override
354 public void onChange(boolean selfChange) {
355 synchronized (mLock) {
356 updateProvidersLocked();
357 }
358 }
359 }, UserHandle.USER_ALL);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800360 mContext.getContentResolver().registerContentObserver(
361 Settings.Global.getUriFor(Settings.Global.LOCATION_BACKGROUND_THROTTLE_INTERVAL_MS),
362 true,
363 new ContentObserver(mLocationHandler) {
364 @Override
365 public void onChange(boolean selfChange) {
366 synchronized (mLock) {
367 updateProvidersLocked();
368 }
369 }
370 }, UserHandle.USER_ALL);
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800371 mContext.getContentResolver().registerContentObserver(
gomo48f1a642017-11-10 20:35:46 -0800372 Settings.Global.getUriFor(
373 Settings.Global.LOCATION_BACKGROUND_THROTTLE_PACKAGE_WHITELIST),
374 true,
375 new ContentObserver(mLocationHandler) {
376 @Override
377 public void onChange(boolean selfChange) {
378 synchronized (mLock) {
379 updateBackgroundThrottlingWhitelistLocked();
380 updateProvidersLocked();
381 }
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800382 }
gomo48f1a642017-11-10 20:35:46 -0800383 }, UserHandle.USER_ALL);
Victoria Lease5cd731a2012-12-19 15:04:21 -0800384 mPackageMonitor.register(mContext, mLocationHandler.getLooper(), true);
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700385
Victoria Lease38389b62012-09-30 11:44:22 -0700386 // listen for user change
387 IntentFilter intentFilter = new IntentFilter();
388 intentFilter.addAction(Intent.ACTION_USER_SWITCHED);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700389 intentFilter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
390 intentFilter.addAction(Intent.ACTION_MANAGED_PROFILE_REMOVED);
destradaab9026982015-08-27 17:34:54 -0700391 intentFilter.addAction(Intent.ACTION_SHUTDOWN);
Victoria Lease38389b62012-09-30 11:44:22 -0700392
393 mContext.registerReceiverAsUser(new BroadcastReceiver() {
394 @Override
395 public void onReceive(Context context, Intent intent) {
396 String action = intent.getAction();
397 if (Intent.ACTION_USER_SWITCHED.equals(action)) {
398 switchUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0));
Amith Yamasanib27528d2014-06-05 15:02:10 -0700399 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)
400 || Intent.ACTION_MANAGED_PROFILE_REMOVED.equals(action)) {
401 updateUserProfiles(mCurrentUserId);
destradaab9026982015-08-27 17:34:54 -0700402 } else if (Intent.ACTION_SHUTDOWN.equals(action)) {
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700403 // shutdown only if UserId indicates whole system, not just one user
gomo48f1a642017-11-10 20:35:46 -0800404 if (D) Log.d(TAG, "Shutdown received with UserId: " + getSendingUserId());
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700405 if (getSendingUserId() == UserHandle.USER_ALL) {
406 shutdownComponents();
407 }
Victoria Lease38389b62012-09-30 11:44:22 -0700408 }
409 }
Victoria Lease5cd731a2012-12-19 15:04:21 -0800410 }, UserHandle.ALL, intentFilter, null, mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700411 }
412
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700413 private void onUidImportanceChanged(int uid, int importance) {
414 boolean foreground = isImportanceForeground(importance);
415 HashSet<String> affectedProviders = new HashSet<>(mRecordsByProvider.size());
416 synchronized (mLock) {
417 for (Entry<String, ArrayList<UpdateRecord>> entry
gomo48f1a642017-11-10 20:35:46 -0800418 : mRecordsByProvider.entrySet()) {
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700419 String provider = entry.getKey();
420 for (UpdateRecord record : entry.getValue()) {
421 if (record.mReceiver.mIdentity.mUid == uid
gomo48f1a642017-11-10 20:35:46 -0800422 && record.mIsForegroundUid != foreground) {
423 if (D) {
424 Log.d(TAG, "request from uid " + uid + " is now "
425 + (foreground ? "foreground" : "background)"));
426 }
Wyatt Rileyf7075e02018-04-12 17:54:26 -0700427 record.updateForeground(foreground);
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700428
429 if (!isThrottlingExemptLocked(record.mReceiver.mIdentity)) {
430 affectedProviders.add(provider);
431 }
432 }
433 }
434 }
435 for (String provider : affectedProviders) {
436 applyRequirementsLocked(provider);
437 }
438
Wyatt Riley11cc7492018-01-17 08:48:27 -0800439 for (Entry<IBinder, Identity> entry : mGnssMeasurementsListeners.entrySet()) {
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700440 if (entry.getValue().mUid == uid) {
gomo48f1a642017-11-10 20:35:46 -0800441 if (D) {
442 Log.d(TAG, "gnss measurements listener from uid " + uid
443 + " is now " + (foreground ? "foreground" : "background)"));
444 }
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700445 if (foreground || isThrottlingExemptLocked(entry.getValue())) {
Wyatt Riley11cc7492018-01-17 08:48:27 -0800446 mGnssMeasurementsProvider.addListener(
447 IGnssMeasurementsListener.Stub.asInterface(entry.getKey()));
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700448 } else {
Wyatt Riley11cc7492018-01-17 08:48:27 -0800449 mGnssMeasurementsProvider.removeListener(
450 IGnssMeasurementsListener.Stub.asInterface(entry.getKey()));
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700451 }
452 }
453 }
454
Wyatt Riley11cc7492018-01-17 08:48:27 -0800455 for (Entry<IBinder, Identity> entry : mGnssNavigationMessageListeners.entrySet()) {
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700456 if (entry.getValue().mUid == uid) {
gomo48f1a642017-11-10 20:35:46 -0800457 if (D) {
458 Log.d(TAG, "gnss navigation message listener from uid "
459 + uid + " is now "
460 + (foreground ? "foreground" : "background)"));
461 }
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700462 if (foreground || isThrottlingExemptLocked(entry.getValue())) {
Wyatt Riley11cc7492018-01-17 08:48:27 -0800463 mGnssNavigationMessageProvider.addListener(
464 IGnssNavigationMessageListener.Stub.asInterface(entry.getKey()));
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700465 } else {
Wyatt Riley11cc7492018-01-17 08:48:27 -0800466 mGnssNavigationMessageProvider.removeListener(
467 IGnssNavigationMessageListener.Stub.asInterface(entry.getKey()));
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700468 }
469 }
470 }
471 }
472 }
473
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800474 private static boolean isImportanceForeground(int importance) {
Soonil Nagarkarebda0282017-04-10 14:55:37 -0700475 return importance <= FOREGROUND_IMPORTANCE_CUTOFF;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800476 }
477
Amith Yamasanib27528d2014-06-05 15:02:10 -0700478 /**
destradaab9026982015-08-27 17:34:54 -0700479 * Provides a way for components held by the {@link LocationManagerService} to clean-up
480 * gracefully on system's shutdown.
481 *
482 * NOTES:
483 * 1) Only provides a chance to clean-up on an opt-in basis. This guarantees back-compat
484 * support for components that do not wish to handle such event.
485 */
486 private void shutdownComponents() {
gomo48f1a642017-11-10 20:35:46 -0800487 if (D) Log.d(TAG, "Shutting down components...");
destradaab9026982015-08-27 17:34:54 -0700488
489 LocationProviderInterface gpsProvider = mProvidersByName.get(LocationManager.GPS_PROVIDER);
490 if (gpsProvider != null && gpsProvider.isEnabled()) {
491 gpsProvider.disable();
492 }
destradaab9026982015-08-27 17:34:54 -0700493 }
494
495 /**
Amith Yamasanib27528d2014-06-05 15:02:10 -0700496 * Makes a list of userids that are related to the current user. This is
497 * relevant when using managed profiles. Otherwise the list only contains
498 * the current user.
499 *
500 * @param currentUserId the current user, who might have an alter-ego.
501 */
502 void updateUserProfiles(int currentUserId) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700503 int[] profileIds = mUserManager.getProfileIdsWithDisabled(currentUserId);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700504 synchronized (mLock) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700505 mCurrentUserProfiles = profileIds;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700506 }
507 }
508
509 /**
510 * Checks if the specified userId matches any of the current foreground
511 * users stored in mCurrentUserProfiles.
512 */
513 private boolean isCurrentProfile(int userId) {
514 synchronized (mLock) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700515 return ArrayUtils.contains(mCurrentUserProfiles, userId);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700516 }
517 }
518
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500519 private void ensureFallbackFusedProviderPresentLocked(ArrayList<String> pkgs) {
520 PackageManager pm = mContext.getPackageManager();
521 String systemPackageName = mContext.getPackageName();
522 ArrayList<HashSet<Signature>> sigSets = ServiceWatcher.getSignatureSets(mContext, pkgs);
523
524 List<ResolveInfo> rInfos = pm.queryIntentServicesAsUser(
525 new Intent(FUSED_LOCATION_SERVICE_ACTION),
526 PackageManager.GET_META_DATA, mCurrentUserId);
527 for (ResolveInfo rInfo : rInfos) {
528 String packageName = rInfo.serviceInfo.packageName;
529
530 // Check that the signature is in the list of supported sigs. If it's not in
531 // this list the standard provider binding logic won't bind to it.
532 try {
533 PackageInfo pInfo;
534 pInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
535 if (!ServiceWatcher.isSignatureMatch(pInfo.signatures, sigSets)) {
536 Log.w(TAG, packageName + " resolves service " + FUSED_LOCATION_SERVICE_ACTION +
537 ", but has wrong signature, ignoring");
538 continue;
539 }
540 } catch (NameNotFoundException e) {
541 Log.e(TAG, "missing package: " + packageName);
542 continue;
543 }
544
545 // Get the version info
546 if (rInfo.serviceInfo.metaData == null) {
547 Log.w(TAG, "Found fused provider without metadata: " + packageName);
548 continue;
549 }
550
551 int version = rInfo.serviceInfo.metaData.getInt(
552 ServiceWatcher.EXTRA_SERVICE_VERSION, -1);
553 if (version == 0) {
554 // This should be the fallback fused location provider.
555
556 // Make sure it's in the system partition.
557 if ((rInfo.serviceInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
558 if (D) Log.d(TAG, "Fallback candidate not in /system: " + packageName);
559 continue;
560 }
561
562 // Check that the fallback is signed the same as the OS
563 // as a proxy for coreApp="true"
564 if (pm.checkSignatures(systemPackageName, packageName)
565 != PackageManager.SIGNATURE_MATCH) {
gomo48f1a642017-11-10 20:35:46 -0800566 if (D) {
567 Log.d(TAG, "Fallback candidate not signed the same as system: "
568 + packageName);
569 }
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500570 continue;
571 }
572
573 // Found a valid fallback.
574 if (D) Log.d(TAG, "Found fallback provider: " + packageName);
575 return;
576 } else {
577 if (D) Log.d(TAG, "Fallback candidate not version 0: " + packageName);
578 }
579 }
580
581 throw new IllegalStateException("Unable to find a fused location provider that is in the "
582 + "system partition with version 0 and signed with the platform certificate. "
583 + "Such a package is needed to provide a default fused location provider in the "
584 + "event that no other fused location provider has been installed or is currently "
585 + "available. For example, coreOnly boot mode when decrypting the data "
586 + "partition. The fallback must also be marked coreApp=\"true\" in the manifest");
587 }
588
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700589 private void loadProvidersLocked() {
Victoria Lease5c24fd02012-10-01 11:00:50 -0700590 // create a passive location provider, which is always enabled
591 PassiveProvider passiveProvider = new PassiveProvider(this);
592 addProviderLocked(passiveProvider);
593 mEnabledProviders.add(passiveProvider.getName());
594 mPassiveProvider = passiveProvider;
595
Lifu Tang30f95a72016-01-07 23:20:38 -0800596 if (GnssLocationProvider.isSupported()) {
Wei Liu5241a4c2015-05-11 14:00:36 -0700597 // Create a gps location provider
Lifu Tang30f95a72016-01-07 23:20:38 -0800598 GnssLocationProvider gnssProvider = new GnssLocationProvider(mContext, this,
Wei Liu5241a4c2015-05-11 14:00:36 -0700599 mLocationHandler.getLooper());
Lifu Tang9363b942016-02-16 18:07:00 -0800600 mGnssSystemInfoProvider = gnssProvider.getGnssSystemInfoProvider();
Wyatt Rileycf879db2017-01-12 13:57:38 -0800601 mGnssBatchingProvider = gnssProvider.getGnssBatchingProvider();
Siddharth Raybb608c82017-03-16 11:33:34 -0700602 mGnssMetricsProvider = gnssProvider.getGnssMetricsProvider();
Lifu Tang30f95a72016-01-07 23:20:38 -0800603 mGnssStatusProvider = gnssProvider.getGnssStatusProvider();
604 mNetInitiatedListener = gnssProvider.getNetInitiatedListener();
605 addProviderLocked(gnssProvider);
606 mRealProviders.put(LocationManager.GPS_PROVIDER, gnssProvider);
Lifu Tang818aa2c2016-02-01 01:52:00 -0800607 mGnssMeasurementsProvider = gnssProvider.getGnssMeasurementsProvider();
608 mGnssNavigationMessageProvider = gnssProvider.getGnssNavigationMessageProvider();
Lifu Tang30f95a72016-01-07 23:20:38 -0800609 mGpsGeofenceProxy = gnssProvider.getGpsGeofenceProxy();
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700610 }
611
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700612 /*
613 Load package name(s) containing location provider support.
614 These packages can contain services implementing location providers:
615 Geocoder Provider, Network Location Provider, and
616 Fused Location Provider. They will each be searched for
617 service components implementing these providers.
618 The location framework also has support for installation
619 of new location providers at run-time. The new package does not
620 have to be explicitly listed here, however it must have a signature
621 that matches the signature of at least one package on this list.
622 */
623 Resources resources = mContext.getResources();
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800624 ArrayList<String> providerPackageNames = new ArrayList<>();
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500625 String[] pkgs = resources.getStringArray(
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700626 com.android.internal.R.array.config_locationProviderPackageNames);
gomo48f1a642017-11-10 20:35:46 -0800627 if (D) {
628 Log.d(TAG, "certificates for location providers pulled from: " +
629 Arrays.toString(pkgs));
630 }
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500631 if (pkgs != null) providerPackageNames.addAll(Arrays.asList(pkgs));
632
633 ensureFallbackFusedProviderPresentLocked(providerPackageNames);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700634
635 // bind to network provider
636 LocationProviderProxy networkProvider = LocationProviderProxy.createAndBind(
637 mContext,
638 LocationManager.NETWORK_PROVIDER,
639 NETWORK_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700640 com.android.internal.R.bool.config_enableNetworkLocationOverlay,
641 com.android.internal.R.string.config_networkLocationProviderPackageName,
642 com.android.internal.R.array.config_locationProviderPackageNames,
643 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700644 if (networkProvider != null) {
645 mRealProviders.put(LocationManager.NETWORK_PROVIDER, networkProvider);
646 mProxyProviders.add(networkProvider);
647 addProviderLocked(networkProvider);
648 } else {
gomo48f1a642017-11-10 20:35:46 -0800649 Slog.w(TAG, "no network location provider found");
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700650 }
651
652 // bind to fused provider
653 LocationProviderProxy fusedLocationProvider = LocationProviderProxy.createAndBind(
654 mContext,
655 LocationManager.FUSED_PROVIDER,
656 FUSED_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700657 com.android.internal.R.bool.config_enableFusedLocationOverlay,
658 com.android.internal.R.string.config_fusedLocationProviderPackageName,
659 com.android.internal.R.array.config_locationProviderPackageNames,
660 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700661 if (fusedLocationProvider != null) {
662 addProviderLocked(fusedLocationProvider);
663 mProxyProviders.add(fusedLocationProvider);
664 mEnabledProviders.add(fusedLocationProvider.getName());
Kenny Rootc3575182012-10-09 12:44:40 -0700665 mRealProviders.put(LocationManager.FUSED_PROVIDER, fusedLocationProvider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700666 } else {
667 Slog.e(TAG, "no fused location provider found",
668 new IllegalStateException("Location service needs a fused location provider"));
669 }
670
671 // bind to geocoder provider
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700672 mGeocodeProvider = GeocoderProxy.createAndBind(mContext,
673 com.android.internal.R.bool.config_enableGeocoderOverlay,
674 com.android.internal.R.string.config_geocoderProviderPackageName,
675 com.android.internal.R.array.config_locationProviderPackageNames,
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800676 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700677 if (mGeocodeProvider == null) {
gomo48f1a642017-11-10 20:35:46 -0800678 Slog.e(TAG, "no geocoder provider found");
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700679 }
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -0700680
destradaaf9a274c2014-07-25 15:11:56 -0700681 // bind to geofence provider
682 GeofenceProxy provider = GeofenceProxy.createAndBind(
gomo48f1a642017-11-10 20:35:46 -0800683 mContext, com.android.internal.R.bool.config_enableGeofenceOverlay,
destradaaf9a274c2014-07-25 15:11:56 -0700684 com.android.internal.R.string.config_geofenceProviderPackageName,
685 com.android.internal.R.array.config_locationProviderPackageNames,
686 mLocationHandler,
Wei Liu5241a4c2015-05-11 14:00:36 -0700687 mGpsGeofenceProxy,
Jiyong Park4cc3a1c2018-03-08 16:43:07 +0900688 null);
destradaaf9a274c2014-07-25 15:11:56 -0700689 if (provider == null) {
gomo48f1a642017-11-10 20:35:46 -0800690 Slog.d(TAG, "Unable to bind FLP Geofence proxy.");
destradaa0682809a2013-08-12 18:50:30 -0700691 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +0900692
destradaa6e2fe752015-06-23 17:25:53 -0700693 // bind to hardware activity recognition
694 boolean activityRecognitionHardwareIsSupported = ActivityRecognitionHardware.isSupported();
695 ActivityRecognitionHardware activityRecognitionHardware = null;
696 if (activityRecognitionHardwareIsSupported) {
697 activityRecognitionHardware = ActivityRecognitionHardware.getInstance(mContext);
destradaaa4fa3b52014-07-09 10:46:39 -0700698 } else {
destradaa6b4893a2016-05-03 15:33:43 -0700699 Slog.d(TAG, "Hardware Activity-Recognition not supported.");
destradaaa4fa3b52014-07-09 10:46:39 -0700700 }
destradaa6e2fe752015-06-23 17:25:53 -0700701 ActivityRecognitionProxy proxy = ActivityRecognitionProxy.createAndBind(
702 mContext,
703 mLocationHandler,
704 activityRecognitionHardwareIsSupported,
705 activityRecognitionHardware,
706 com.android.internal.R.bool.config_enableActivityRecognitionHardwareOverlay,
707 com.android.internal.R.string.config_activityRecognitionHardwarePackageName,
708 com.android.internal.R.array.config_locationProviderPackageNames);
709 if (proxy == null) {
destradaa6b4893a2016-05-03 15:33:43 -0700710 Slog.d(TAG, "Unable to bind ActivityRecognitionProxy.");
destradaa6e2fe752015-06-23 17:25:53 -0700711 }
destradaaa4fa3b52014-07-09 10:46:39 -0700712
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +0900713 String[] testProviderStrings = resources.getStringArray(
714 com.android.internal.R.array.config_testLocationProviders);
715 for (String testProviderString : testProviderStrings) {
716 String fragments[] = testProviderString.split(",");
717 String name = fragments[0].trim();
718 if (mProvidersByName.get(name) != null) {
719 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
720 }
721 ProviderProperties properties = new ProviderProperties(
722 Boolean.parseBoolean(fragments[1]) /* requiresNetwork */,
723 Boolean.parseBoolean(fragments[2]) /* requiresSatellite */,
724 Boolean.parseBoolean(fragments[3]) /* requiresCell */,
725 Boolean.parseBoolean(fragments[4]) /* hasMonetaryCost */,
726 Boolean.parseBoolean(fragments[5]) /* supportsAltitude */,
727 Boolean.parseBoolean(fragments[6]) /* supportsSpeed */,
728 Boolean.parseBoolean(fragments[7]) /* supportsBearing */,
729 Integer.parseInt(fragments[8]) /* powerRequirement */,
730 Integer.parseInt(fragments[9]) /* accuracy */);
731 addTestProviderLocked(name, properties);
732 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700733 }
Mike Lockwood9637d472009-04-02 21:41:57 -0700734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 /**
Victoria Lease38389b62012-09-30 11:44:22 -0700736 * Called when the device's active user changes.
gomo48f1a642017-11-10 20:35:46 -0800737 *
Victoria Lease38389b62012-09-30 11:44:22 -0700738 * @param userId the new active user's UserId
739 */
740 private void switchUser(int userId) {
Jianzheng Zhoud5c69462013-10-10 14:02:09 +0800741 if (mCurrentUserId == userId) {
742 return;
743 }
Victoria Lease83762d22012-10-03 13:51:17 -0700744 mBlacklist.switchUser(userId);
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800745 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED);
Victoria Lease38389b62012-09-30 11:44:22 -0700746 synchronized (mLock) {
Victoria Leaseb711d572012-10-02 13:14:11 -0700747 mLastLocation.clear();
David Christie1b9b7b12013-04-15 15:31:11 -0700748 mLastLocationCoarseInterval.clear();
Victoria Leaseb711d572012-10-02 13:14:11 -0700749 for (LocationProviderInterface p : mProviders) {
Amith Yamasanib27528d2014-06-05 15:02:10 -0700750 updateProviderListenersLocked(p.getName(), false);
Victoria Leaseb711d572012-10-02 13:14:11 -0700751 }
Victoria Lease38389b62012-09-30 11:44:22 -0700752 mCurrentUserId = userId;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700753 updateUserProfiles(userId);
Victoria Leaseb711d572012-10-02 13:14:11 -0700754 updateProvidersLocked();
Victoria Lease38389b62012-09-30 11:44:22 -0700755 }
756 }
757
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800758 private static final class Identity {
759 final int mUid;
760 final int mPid;
761 final String mPackageName;
762
763 Identity(int uid, int pid, String packageName) {
764 mUid = uid;
765 mPid = pid;
766 mPackageName = packageName;
767 }
768 }
769
Victoria Lease38389b62012-09-30 11:44:22 -0700770 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 * A wrapper class holding either an ILocationListener or a PendingIntent to receive
772 * location updates.
773 */
Mike Lockwood48f17512009-04-23 09:12:08 -0700774 private final class Receiver implements IBinder.DeathRecipient, PendingIntent.OnFinished {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800775 final Identity mIdentity;
Victoria Lease37425c32012-10-16 16:08:48 -0700776 final int mAllowedResolutionLevel; // resolution level allowed to receiver
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778 final ILocationListener mListener;
779 final PendingIntent mPendingIntent;
David Christie82edc9b2013-07-19 11:31:42 -0700780 final WorkSource mWorkSource; // WorkSource for battery blame, or null to assign to caller.
David Christie40e57822013-07-30 11:36:48 -0700781 final boolean mHideFromAppOps; // True if AppOps should not monitor this receiver.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 final Object mKey;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700783
gomo48f1a642017-11-10 20:35:46 -0800784 final HashMap<String, UpdateRecord> mUpdateRecords = new HashMap<>();
Nick Pellyf1be6862012-05-15 10:53:42 -0700785
David Christie0b837452013-07-29 16:02:13 -0700786 // True if app ops has started monitoring this receiver for locations.
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700787 boolean mOpMonitoring;
David Christie0b837452013-07-29 16:02:13 -0700788 // True if app ops has started monitoring this receiver for high power (gps) locations.
789 boolean mOpHighPowerMonitoring;
Mike Lockwood48f17512009-04-23 09:12:08 -0700790 int mPendingBroadcasts;
Victoria Lease0aa28602013-05-29 15:28:26 -0700791 PowerManager.WakeLock mWakeLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700793 Receiver(ILocationListener listener, PendingIntent intent, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -0700794 String packageName, WorkSource workSource, boolean hideFromAppOps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 mListener = listener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 mPendingIntent = intent;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700797 if (listener != null) {
798 mKey = listener.asBinder();
799 } else {
800 mKey = intent;
801 }
Victoria Lease37425c32012-10-16 16:08:48 -0700802 mAllowedResolutionLevel = getAllowedResolutionLevel(pid, uid);
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800803 mIdentity = new Identity(uid, pid, packageName);
Narayan Kamath32684dd2018-01-08 17:32:51 +0000804 if (workSource != null && workSource.isEmpty()) {
David Christie82edc9b2013-07-19 11:31:42 -0700805 workSource = null;
806 }
807 mWorkSource = workSource;
David Christie40e57822013-07-30 11:36:48 -0700808 mHideFromAppOps = hideFromAppOps;
Victoria Lease0aa28602013-05-29 15:28:26 -0700809
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700810 updateMonitoring(true);
811
Victoria Lease0aa28602013-05-29 15:28:26 -0700812 // construct/configure wakelock
813 mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY);
David Christie82edc9b2013-07-19 11:31:42 -0700814 if (workSource == null) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800815 workSource = new WorkSource(mIdentity.mUid, mIdentity.mPackageName);
David Christie82edc9b2013-07-19 11:31:42 -0700816 }
817 mWakeLock.setWorkSource(workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 }
819
820 @Override
821 public boolean equals(Object otherObj) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800822 return (otherObj instanceof Receiver) && mKey.equals(((Receiver) otherObj).mKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 }
824
825 @Override
826 public int hashCode() {
827 return mKey.hashCode();
828 }
Mike Lockwood3681f262009-05-12 10:52:03 -0400829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 @Override
831 public String toString() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700832 StringBuilder s = new StringBuilder();
833 s.append("Reciever[");
834 s.append(Integer.toHexString(System.identityHashCode(this)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 if (mListener != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700836 s.append(" listener");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 } else {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700838 s.append(" intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700840 for (String p : mUpdateRecords.keySet()) {
841 s.append(" ").append(mUpdateRecords.get(p).toString());
842 }
843 s.append("]");
844 return s.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 }
846
David Christie15b31912013-08-13 15:54:32 -0700847 /**
848 * Update AppOp monitoring for this receiver.
849 *
850 * @param allow If true receiver is currently active, if false it's been removed.
851 */
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700852 public void updateMonitoring(boolean allow) {
David Christie40e57822013-07-30 11:36:48 -0700853 if (mHideFromAppOps) {
854 return;
855 }
856
David Christie15b31912013-08-13 15:54:32 -0700857 boolean requestingLocation = false;
858 boolean requestingHighPowerLocation = false;
859 if (allow) {
860 // See if receiver has any enabled update records. Also note if any update records
861 // are high power (has a high power provider with an interval under a threshold).
862 for (UpdateRecord updateRecord : mUpdateRecords.values()) {
863 if (isAllowedByCurrentUserSettingsLocked(updateRecord.mProvider)) {
864 requestingLocation = true;
865 LocationProviderInterface locationProvider
David Christie2ff96af2014-01-30 16:09:37 -0800866 = mProvidersByName.get(updateRecord.mProvider);
David Christie15b31912013-08-13 15:54:32 -0700867 ProviderProperties properties = locationProvider != null
868 ? locationProvider.getProperties() : null;
869 if (properties != null
870 && properties.mPowerRequirement == Criteria.POWER_HIGH
871 && updateRecord.mRequest.getInterval() < HIGH_POWER_INTERVAL_MS) {
872 requestingHighPowerLocation = true;
873 break;
874 }
875 }
876 }
877 }
878
David Christie0b837452013-07-29 16:02:13 -0700879 // First update monitoring of any location request (including high power).
David Christie15b31912013-08-13 15:54:32 -0700880 mOpMonitoring = updateMonitoring(
881 requestingLocation,
882 mOpMonitoring,
David Christie0b837452013-07-29 16:02:13 -0700883 AppOpsManager.OP_MONITOR_LOCATION);
884
885 // Now update monitoring of high power requests only.
David Christiec750c1f2013-08-08 12:56:57 -0700886 boolean wasHighPowerMonitoring = mOpHighPowerMonitoring;
David Christie15b31912013-08-13 15:54:32 -0700887 mOpHighPowerMonitoring = updateMonitoring(
888 requestingHighPowerLocation,
889 mOpHighPowerMonitoring,
David Christie0b837452013-07-29 16:02:13 -0700890 AppOpsManager.OP_MONITOR_HIGH_POWER_LOCATION);
David Christiec750c1f2013-08-08 12:56:57 -0700891 if (mOpHighPowerMonitoring != wasHighPowerMonitoring) {
David Christie15b31912013-08-13 15:54:32 -0700892 // Send an intent to notify that a high power request has been added/removed.
David Christiec750c1f2013-08-08 12:56:57 -0700893 Intent intent = new Intent(LocationManager.HIGH_POWER_REQUEST_CHANGE_ACTION);
894 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
895 }
David Christie0b837452013-07-29 16:02:13 -0700896 }
897
898 /**
899 * Update AppOps monitoring for a single location request and op type.
900 *
gomo48f1a642017-11-10 20:35:46 -0800901 * @param allowMonitoring True if monitoring is allowed for this request/op.
David Christie0b837452013-07-29 16:02:13 -0700902 * @param currentlyMonitoring True if AppOps is currently monitoring this request/op.
gomo48f1a642017-11-10 20:35:46 -0800903 * @param op AppOps code for the op to update.
David Christie0b837452013-07-29 16:02:13 -0700904 * @return True if monitoring is on for this request/op after updating.
905 */
906 private boolean updateMonitoring(boolean allowMonitoring, boolean currentlyMonitoring,
907 int op) {
908 if (!currentlyMonitoring) {
909 if (allowMonitoring) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800910 return mAppOps.startOpNoThrow(op, mIdentity.mUid, mIdentity.mPackageName)
David Christie0b837452013-07-29 16:02:13 -0700911 == AppOpsManager.MODE_ALLOWED;
912 }
913 } else {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800914 if (!allowMonitoring
915 || mAppOps.checkOpNoThrow(op, mIdentity.mUid, mIdentity.mPackageName)
David Christie0b837452013-07-29 16:02:13 -0700916 != AppOpsManager.MODE_ALLOWED) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800917 mAppOps.finishOp(op, mIdentity.mUid, mIdentity.mPackageName);
David Christie0b837452013-07-29 16:02:13 -0700918 return false;
919 }
920 }
921
922 return currentlyMonitoring;
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700923 }
924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 public boolean isListener() {
926 return mListener != null;
927 }
928
929 public boolean isPendingIntent() {
930 return mPendingIntent != null;
931 }
932
933 public ILocationListener getListener() {
934 if (mListener != null) {
935 return mListener;
936 }
937 throw new IllegalStateException("Request for non-existent listener");
938 }
939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 public boolean callStatusChangedLocked(String provider, int status, Bundle extras) {
941 if (mListener != null) {
942 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700943 synchronized (this) {
944 // synchronize to ensure incrementPendingBroadcastsLocked()
945 // is called before decrementPendingBroadcasts()
946 mListener.onStatusChanged(provider, status, extras);
Nick Pellye0fd6932012-07-11 10:26:13 -0700947 // call this after broadcasting so we do not increment
948 // if we throw an exeption.
949 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700950 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800951 } catch (RemoteException e) {
952 return false;
953 }
954 } else {
955 Intent statusChanged = new Intent();
Victoria Lease61ecb022012-11-13 15:12:51 -0800956 statusChanged.putExtras(new Bundle(extras));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 statusChanged.putExtra(LocationManager.KEY_STATUS_CHANGED, status);
958 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700959 synchronized (this) {
960 // synchronize to ensure incrementPendingBroadcastsLocked()
961 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700962 mPendingIntent.send(mContext, 0, statusChanged, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700963 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700964 // call this after broadcasting so we do not increment
965 // if we throw an exeption.
966 incrementPendingBroadcastsLocked();
967 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 } catch (PendingIntent.CanceledException e) {
969 return false;
970 }
971 }
972 return true;
973 }
974
975 public boolean callLocationChangedLocked(Location location) {
976 if (mListener != null) {
977 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700978 synchronized (this) {
979 // synchronize to ensure incrementPendingBroadcastsLocked()
980 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c5406a2012-11-29 16:18:01 -0800981 mListener.onLocationChanged(new Location(location));
Nick Pellye0fd6932012-07-11 10:26:13 -0700982 // call this after broadcasting so we do not increment
983 // if we throw an exeption.
984 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 } catch (RemoteException e) {
987 return false;
988 }
989 } else {
990 Intent locationChanged = new Intent();
gomo48f1a642017-11-10 20:35:46 -0800991 locationChanged.putExtra(LocationManager.KEY_LOCATION_CHANGED,
992 new Location(location));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700994 synchronized (this) {
995 // synchronize to ensure incrementPendingBroadcastsLocked()
996 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700997 mPendingIntent.send(mContext, 0, locationChanged, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700998 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700999 // call this after broadcasting so we do not increment
1000 // if we throw an exeption.
1001 incrementPendingBroadcastsLocked();
1002 }
1003 } catch (PendingIntent.CanceledException e) {
1004 return false;
1005 }
1006 }
1007 return true;
1008 }
1009
1010 public boolean callProviderEnabledLocked(String provider, boolean enabled) {
David Christie15b31912013-08-13 15:54:32 -07001011 // First update AppOp monitoring.
1012 // An app may get/lose location access as providers are enabled/disabled.
1013 updateMonitoring(true);
1014
Mike Lockwood48f17512009-04-23 09:12:08 -07001015 if (mListener != null) {
1016 try {
1017 synchronized (this) {
1018 // synchronize to ensure incrementPendingBroadcastsLocked()
1019 // is called before decrementPendingBroadcasts()
1020 if (enabled) {
1021 mListener.onProviderEnabled(provider);
1022 } else {
1023 mListener.onProviderDisabled(provider);
1024 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001025 // call this after broadcasting so we do not increment
1026 // if we throw an exeption.
1027 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001028 }
1029 } catch (RemoteException e) {
1030 return false;
1031 }
1032 } else {
1033 Intent providerIntent = new Intent();
1034 providerIntent.putExtra(LocationManager.KEY_PROVIDER_ENABLED, enabled);
1035 try {
1036 synchronized (this) {
1037 // synchronize to ensure incrementPendingBroadcastsLocked()
1038 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001039 mPendingIntent.send(mContext, 0, providerIntent, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -07001040 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -07001041 // call this after broadcasting so we do not increment
1042 // if we throw an exeption.
1043 incrementPendingBroadcastsLocked();
1044 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 } catch (PendingIntent.CanceledException e) {
1046 return false;
1047 }
1048 }
1049 return true;
1050 }
1051
Nick Pellyf1be6862012-05-15 10:53:42 -07001052 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 public void binderDied() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001054 if (D) Log.d(TAG, "Location listener died");
1055
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001056 synchronized (mLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 removeUpdatesLocked(this);
1058 }
Mike Lockwood48f17512009-04-23 09:12:08 -07001059 synchronized (this) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001060 clearPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001061 }
1062 }
1063
Nick Pellye0fd6932012-07-11 10:26:13 -07001064 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -07001065 public void onSendFinished(PendingIntent pendingIntent, Intent intent,
1066 int resultCode, String resultData, Bundle resultExtras) {
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001067 synchronized (this) {
1068 decrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001069 }
1070 }
1071
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001072 // this must be called while synchronized by caller in a synchronized block
1073 // containing the sending of the broadcaset
1074 private void incrementPendingBroadcastsLocked() {
1075 if (mPendingBroadcasts++ == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001076 mWakeLock.acquire();
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001077 }
1078 }
1079
1080 private void decrementPendingBroadcastsLocked() {
1081 if (--mPendingBroadcasts == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001082 if (mWakeLock.isHeld()) {
1083 mWakeLock.release();
1084 }
1085 }
1086 }
1087
1088 public void clearPendingBroadcastsLocked() {
1089 if (mPendingBroadcasts > 0) {
1090 mPendingBroadcasts = 0;
1091 if (mWakeLock.isHeld()) {
1092 mWakeLock.release();
1093 }
Mike Lockwood48f17512009-04-23 09:12:08 -07001094 }
1095 }
1096 }
1097
Nick Pellye0fd6932012-07-11 10:26:13 -07001098 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -07001099 public void locationCallbackFinished(ILocationListener listener) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001100 //Do not use getReceiverLocked here as that will add the ILocationListener to
Joshua Bartel080b61b2009-10-05 12:44:46 -04001101 //the receiver list if it is not found. If it is not found then the
1102 //LocationListener was removed when it had a pending broadcast and should
1103 //not be added back.
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001104 synchronized (mLock) {
1105 IBinder binder = listener.asBinder();
1106 Receiver receiver = mReceivers.get(binder);
1107 if (receiver != null) {
1108 synchronized (receiver) {
1109 // so wakelock calls will succeed
1110 long identity = Binder.clearCallingIdentity();
1111 receiver.decrementPendingBroadcastsLocked();
1112 Binder.restoreCallingIdentity(identity);
David Christie2ff96af2014-01-30 16:09:37 -08001113 }
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001114 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 }
1116 }
1117
Lifu Tang82f893d2016-01-21 18:15:33 -08001118 /**
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001119 * Returns the year of the GNSS hardware.
Lifu Tang82f893d2016-01-21 18:15:33 -08001120 */
1121 @Override
Lifu Tang9363b942016-02-16 18:07:00 -08001122 public int getGnssYearOfHardware() {
Wyatt Rileycf879db2017-01-12 13:57:38 -08001123 if (mGnssSystemInfoProvider != null) {
Lifu Tang9363b942016-02-16 18:07:00 -08001124 return mGnssSystemInfoProvider.getGnssYearOfHardware();
Lifu Tang82f893d2016-01-21 18:15:33 -08001125 } else {
1126 return 0;
1127 }
1128 }
1129
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001130
1131 /**
1132 * Returns the model name of the GNSS hardware.
1133 */
1134 @Override
Wyatt Riley49097c02018-03-15 09:14:43 -07001135 @Nullable
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001136 public String getGnssHardwareModelName() {
1137 if (mGnssSystemInfoProvider != null) {
1138 return mGnssSystemInfoProvider.getGnssHardwareModelName();
1139 } else {
Wyatt Riley49097c02018-03-15 09:14:43 -07001140 return null;
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001141 }
1142 }
1143
Wyatt Rileycf879db2017-01-12 13:57:38 -08001144 /**
1145 * Runs some checks for GNSS (FINE) level permissions, used by several methods which directly
1146 * (try to) access GNSS information at this layer.
1147 */
1148 private boolean hasGnssPermissions(String packageName) {
1149 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1150 checkResolutionLevelIsSufficientForProviderUse(
1151 allowedResolutionLevel,
1152 LocationManager.GPS_PROVIDER);
1153
1154 int pid = Binder.getCallingPid();
1155 int uid = Binder.getCallingUid();
1156 long identity = Binder.clearCallingIdentity();
1157 boolean hasLocationAccess;
1158 try {
1159 hasLocationAccess = checkLocationAccess(pid, uid, packageName, allowedResolutionLevel);
1160 } finally {
1161 Binder.restoreCallingIdentity(identity);
1162 }
1163
1164 return hasLocationAccess;
1165 }
1166
1167 /**
1168 * Returns the GNSS batching size, if available.
1169 */
1170 @Override
1171 public int getGnssBatchSize(String packageName) {
1172 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1173 "Location Hardware permission not granted to access hardware batching");
1174
1175 if (hasGnssPermissions(packageName) && mGnssBatchingProvider != null) {
1176 return mGnssBatchingProvider.getSize();
1177 } else {
1178 return 0;
1179 }
1180 }
1181
1182 /**
1183 * Adds a callback for GNSS Batching events, if permissions allow, which are transported
1184 * to potentially multiple listeners by the BatchedLocationCallbackTransport above this.
1185 */
1186 @Override
1187 public boolean addGnssBatchingCallback(IBatchedLocationCallback callback, String packageName) {
1188 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1189 "Location Hardware permission not granted to access hardware batching");
1190
1191 if (!hasGnssPermissions(packageName) || mGnssBatchingProvider == null) {
1192 return false;
1193 }
1194
1195 mGnssBatchingCallback = callback;
1196 mGnssBatchingDeathCallback = new LinkedCallback(callback);
1197 try {
1198 callback.asBinder().linkToDeath(mGnssBatchingDeathCallback, 0 /* flags */);
1199 } catch (RemoteException e) {
1200 // if the remote process registering the listener is already dead, just swallow the
1201 // exception and return
1202 Log.e(TAG, "Remote listener already died.", e);
1203 return false;
1204 }
1205
1206 return true;
1207 }
1208
1209 private class LinkedCallback implements IBinder.DeathRecipient {
1210 private final IBatchedLocationCallback mCallback;
1211
1212 public LinkedCallback(@NonNull IBatchedLocationCallback callback) {
1213 mCallback = callback;
1214 }
1215
1216 @NonNull
1217 public IBatchedLocationCallback getUnderlyingListener() {
1218 return mCallback;
1219 }
1220
1221 @Override
1222 public void binderDied() {
1223 Log.d(TAG, "Remote Batching Callback died: " + mCallback);
1224 stopGnssBatch();
1225 removeGnssBatchingCallback();
1226 }
1227 }
1228
1229 /**
1230 * Removes callback for GNSS batching
1231 */
1232 @Override
1233 public void removeGnssBatchingCallback() {
1234 try {
1235 mGnssBatchingCallback.asBinder().unlinkToDeath(mGnssBatchingDeathCallback,
1236 0 /* flags */);
1237 } catch (NoSuchElementException e) {
1238 // if the death callback isn't connected (it should be...), log error, swallow the
1239 // exception and return
1240 Log.e(TAG, "Couldn't unlink death callback.", e);
1241 }
1242 mGnssBatchingCallback = null;
1243 mGnssBatchingDeathCallback = null;
1244 }
1245
1246
1247 /**
1248 * Starts GNSS batching, if available.
1249 */
1250 @Override
1251 public boolean startGnssBatch(long periodNanos, boolean wakeOnFifoFull, String packageName) {
1252 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1253 "Location Hardware permission not granted to access hardware batching");
1254
1255 if (!hasGnssPermissions(packageName) || mGnssBatchingProvider == null) {
1256 return false;
1257 }
1258
1259 if (mGnssBatchingInProgress) {
1260 // Current design does not expect multiple starts to be called repeatedly
1261 Log.e(TAG, "startGnssBatch unexpectedly called w/o stopping prior batch");
1262 // Try to clean up anyway, and continue
1263 stopGnssBatch();
1264 }
1265
1266 mGnssBatchingInProgress = true;
1267 return mGnssBatchingProvider.start(periodNanos, wakeOnFifoFull);
1268 }
1269
1270 /**
1271 * Flushes a GNSS batch in progress
1272 */
1273 @Override
1274 public void flushGnssBatch(String packageName) {
1275 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1276 "Location Hardware permission not granted to access hardware batching");
1277
1278 if (!hasGnssPermissions(packageName)) {
1279 Log.e(TAG, "flushGnssBatch called without GNSS permissions");
1280 return;
1281 }
1282
1283 if (!mGnssBatchingInProgress) {
1284 Log.w(TAG, "flushGnssBatch called with no batch in progress");
1285 }
1286
1287 if (mGnssBatchingProvider != null) {
gomo48f1a642017-11-10 20:35:46 -08001288 mGnssBatchingProvider.flush();
Wyatt Rileycf879db2017-01-12 13:57:38 -08001289 }
1290 }
1291
1292 /**
1293 * Stops GNSS batching
1294 */
1295 @Override
1296 public boolean stopGnssBatch() {
1297 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1298 "Location Hardware permission not granted to access hardware batching");
1299
1300 if (mGnssBatchingProvider != null) {
1301 mGnssBatchingInProgress = false;
1302 return mGnssBatchingProvider.stop();
gomo48f1a642017-11-10 20:35:46 -08001303 } else {
Wyatt Rileycf879db2017-01-12 13:57:38 -08001304 return false;
1305 }
1306 }
1307
1308 @Override
1309 public void reportLocationBatch(List<Location> locations) {
1310 checkCallerIsProvider();
1311
1312 // Currently used only for GNSS locations - update permissions check if changed
1313 if (isAllowedByCurrentUserSettingsLocked(LocationManager.GPS_PROVIDER)) {
1314 if (mGnssBatchingCallback == null) {
1315 Slog.e(TAG, "reportLocationBatch() called without active Callback");
1316 return;
1317 }
1318 try {
1319 mGnssBatchingCallback.onLocationBatch(locations);
1320 } catch (RemoteException e) {
1321 Slog.e(TAG, "mGnssBatchingCallback.onLocationBatch failed", e);
1322 }
1323 } else {
1324 Slog.w(TAG, "reportLocationBatch() called without user permission, locations blocked");
1325 }
1326 }
1327
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001328 private void addProviderLocked(LocationProviderInterface provider) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001329 mProviders.add(provider);
1330 mProvidersByName.put(provider.getName(), provider);
1331 }
1332
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001333 private void removeProviderLocked(LocationProviderInterface provider) {
1334 provider.disable();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001335 mProviders.remove(provider);
1336 mProvidersByName.remove(provider.getName());
1337 }
1338
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001339 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -08001340 * Returns "true" if access to the specified location provider is allowed by the current
1341 * user's settings. Access to all location providers is forbidden to non-location-provider
1342 * processes belonging to background users.
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001343 *
1344 * @param provider the name of the location provider
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001345 */
Victoria Lease09eeaec2013-02-05 11:34:13 -08001346 private boolean isAllowedByCurrentUserSettingsLocked(String provider) {
Maggie2a9409e2018-03-21 11:47:28 -07001347 return isAllowedByUserSettingsLockedForUser(provider, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 }
1349
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001350 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -08001351 * Returns "true" if access to the specified location provider is allowed by the specified
1352 * user's settings. Access to all location providers is forbidden to non-location-provider
1353 * processes belonging to background users.
1354 *
1355 * @param provider the name of the location provider
Maggie2a9409e2018-03-21 11:47:28 -07001356 * @param userId the user id to query
Victoria Lease09eeaec2013-02-05 11:34:13 -08001357 */
Maggie2a9409e2018-03-21 11:47:28 -07001358 private boolean isAllowedByUserSettingsLockedForUser(String provider, int userId) {
1359 if (mEnabledProviders.contains(provider)) {
1360 return true;
1361 }
1362 if (mDisabledProviders.contains(provider)) {
1363 return false;
1364 }
1365 return isLocationProviderEnabledForUser(provider, userId);
1366 }
1367
1368
1369 /**
1370 * Returns "true" if access to the specified location provider is allowed by the specified
1371 * user's settings. Access to all location providers is forbidden to non-location-provider
1372 * processes belonging to background users.
1373 *
1374 * @param provider the name of the location provider
1375 * @param uid the requestor's UID
1376 * @param userId the user id to query
1377 */
1378 private boolean isAllowedByUserSettingsLocked(String provider, int uid, int userId) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001379 if (!isCurrentProfile(UserHandle.getUserId(uid)) && !isUidALocationProvider(uid)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08001380 return false;
1381 }
Maggie2a9409e2018-03-21 11:47:28 -07001382 return isAllowedByUserSettingsLockedForUser(provider, userId);
Victoria Lease09eeaec2013-02-05 11:34:13 -08001383 }
1384
1385 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001386 * Returns the permission string associated with the specified resolution level.
1387 *
1388 * @param resolutionLevel the resolution level
1389 * @return the permission string
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001390 */
Victoria Lease37425c32012-10-16 16:08:48 -07001391 private String getResolutionPermission(int resolutionLevel) {
1392 switch (resolutionLevel) {
1393 case RESOLUTION_LEVEL_FINE:
1394 return android.Manifest.permission.ACCESS_FINE_LOCATION;
1395 case RESOLUTION_LEVEL_COARSE:
1396 return android.Manifest.permission.ACCESS_COARSE_LOCATION;
1397 default:
1398 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 }
Victoria Leaseda479c52012-10-15 15:24:16 -07001400 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001401
Victoria Leaseda479c52012-10-15 15:24:16 -07001402 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001403 * Returns the resolution level allowed to the given PID/UID pair.
1404 *
1405 * @param pid the PID
1406 * @param uid the UID
1407 * @return resolution level allowed to the pid/uid pair
Victoria Leaseda479c52012-10-15 15:24:16 -07001408 */
Victoria Lease37425c32012-10-16 16:08:48 -07001409 private int getAllowedResolutionLevel(int pid, int uid) {
1410 if (mContext.checkPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
Maggieaa080f92018-01-04 15:35:11 -08001411 pid, uid) == PERMISSION_GRANTED) {
Victoria Lease37425c32012-10-16 16:08:48 -07001412 return RESOLUTION_LEVEL_FINE;
1413 } else if (mContext.checkPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION,
Maggieaa080f92018-01-04 15:35:11 -08001414 pid, uid) == PERMISSION_GRANTED) {
Victoria Lease37425c32012-10-16 16:08:48 -07001415 return RESOLUTION_LEVEL_COARSE;
1416 } else {
1417 return RESOLUTION_LEVEL_NONE;
Victoria Leaseda479c52012-10-15 15:24:16 -07001418 }
Victoria Lease4fab68b2012-09-13 13:20:59 -07001419 }
1420
1421 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001422 * Returns the resolution level allowed to the caller
1423 *
1424 * @return resolution level allowed to caller
Victoria Lease4fab68b2012-09-13 13:20:59 -07001425 */
Victoria Lease37425c32012-10-16 16:08:48 -07001426 private int getCallerAllowedResolutionLevel() {
1427 return getAllowedResolutionLevel(Binder.getCallingPid(), Binder.getCallingUid());
1428 }
1429
1430 /**
1431 * Throw SecurityException if specified resolution level is insufficient to use geofences.
1432 *
1433 * @param allowedResolutionLevel resolution level allowed to caller
1434 */
1435 private void checkResolutionLevelIsSufficientForGeofenceUse(int allowedResolutionLevel) {
1436 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
Victoria Lease4fab68b2012-09-13 13:20:59 -07001437 throw new SecurityException("Geofence usage requires ACCESS_FINE_LOCATION permission");
1438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 }
1440
Victoria Lease37425c32012-10-16 16:08:48 -07001441 /**
1442 * Return the minimum resolution level required to use the specified location provider.
1443 *
1444 * @param provider the name of the location provider
1445 * @return minimum resolution level required for provider
1446 */
1447 private int getMinimumResolutionLevelForProviderUse(String provider) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001448 if (LocationManager.GPS_PROVIDER.equals(provider) ||
1449 LocationManager.PASSIVE_PROVIDER.equals(provider)) {
1450 // gps and passive providers require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001451 return RESOLUTION_LEVEL_FINE;
Victoria Lease8dbb6342012-09-21 16:55:53 -07001452 } else if (LocationManager.NETWORK_PROVIDER.equals(provider) ||
1453 LocationManager.FUSED_PROVIDER.equals(provider)) {
1454 // network and fused providers are ok with COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001455 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001456 } else {
1457 // mock providers
1458 LocationProviderInterface lp = mMockProviders.get(provider);
1459 if (lp != null) {
1460 ProviderProperties properties = lp.getProperties();
1461 if (properties != null) {
1462 if (properties.mRequiresSatellite) {
1463 // provider requiring satellites require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001464 return RESOLUTION_LEVEL_FINE;
Laurent Tu941221c2012-10-04 14:21:52 -07001465 } else if (properties.mRequiresNetwork || properties.mRequiresCell) {
1466 // provider requiring network and or cell require COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001467 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001468 }
1469 }
1470 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001471 }
Victoria Lease37425c32012-10-16 16:08:48 -07001472 return RESOLUTION_LEVEL_FINE; // if in doubt, require FINE
Victoria Leaseda479c52012-10-15 15:24:16 -07001473 }
1474
Victoria Lease37425c32012-10-16 16:08:48 -07001475 /**
1476 * Throw SecurityException if specified resolution level is insufficient to use the named
1477 * location provider.
1478 *
1479 * @param allowedResolutionLevel resolution level allowed to caller
gomo48f1a642017-11-10 20:35:46 -08001480 * @param providerName the name of the location provider
Victoria Lease37425c32012-10-16 16:08:48 -07001481 */
1482 private void checkResolutionLevelIsSufficientForProviderUse(int allowedResolutionLevel,
1483 String providerName) {
1484 int requiredResolutionLevel = getMinimumResolutionLevelForProviderUse(providerName);
1485 if (allowedResolutionLevel < requiredResolutionLevel) {
1486 switch (requiredResolutionLevel) {
1487 case RESOLUTION_LEVEL_FINE:
1488 throw new SecurityException("\"" + providerName + "\" location provider " +
1489 "requires ACCESS_FINE_LOCATION permission.");
1490 case RESOLUTION_LEVEL_COARSE:
1491 throw new SecurityException("\"" + providerName + "\" location provider " +
1492 "requires ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission.");
1493 default:
1494 throw new SecurityException("Insufficient permission for \"" + providerName +
1495 "\" location provider.");
Victoria Leaseda479c52012-10-15 15:24:16 -07001496 }
1497 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001498 }
1499
David Christie82edc9b2013-07-19 11:31:42 -07001500 /**
1501 * Throw SecurityException if WorkSource use is not allowed (i.e. can't blame other packages
1502 * for battery).
1503 */
David Christie40e57822013-07-30 11:36:48 -07001504 private void checkDeviceStatsAllowed() {
David Christie82edc9b2013-07-19 11:31:42 -07001505 mContext.enforceCallingOrSelfPermission(
1506 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
1507 }
1508
David Christie40e57822013-07-30 11:36:48 -07001509 private void checkUpdateAppOpsAllowed() {
1510 mContext.enforceCallingOrSelfPermission(
1511 android.Manifest.permission.UPDATE_APP_OPS_STATS, null);
1512 }
1513
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001514 public static int resolutionLevelToOp(int allowedResolutionLevel) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001515 if (allowedResolutionLevel != RESOLUTION_LEVEL_NONE) {
1516 if (allowedResolutionLevel == RESOLUTION_LEVEL_COARSE) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001517 return AppOpsManager.OP_COARSE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001518 } else {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001519 return AppOpsManager.OP_FINE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001520 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001521 }
1522 return -1;
1523 }
1524
David Christieb870dbf2015-06-22 12:42:53 -07001525 boolean reportLocationAccessNoThrow(
1526 int pid, int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001527 int op = resolutionLevelToOp(allowedResolutionLevel);
1528 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001529 if (mAppOps.noteOpNoThrow(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1530 return false;
1531 }
1532 }
David Christieb870dbf2015-06-22 12:42:53 -07001533
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001534 return getAllowedResolutionLevel(pid, uid) >= allowedResolutionLevel;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001535 }
1536
David Christieb870dbf2015-06-22 12:42:53 -07001537 boolean checkLocationAccess(int pid, int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001538 int op = resolutionLevelToOp(allowedResolutionLevel);
1539 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001540 if (mAppOps.checkOp(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1541 return false;
1542 }
1543 }
David Christieb870dbf2015-06-22 12:42:53 -07001544
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001545 return getAllowedResolutionLevel(pid, uid) >= allowedResolutionLevel;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001546 }
1547
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001548 /**
Maggie91e630c2018-01-24 17:31:46 -08001549 * Returns all providers by name, including passive and the ones that are not permitted to
1550 * be accessed by the calling activity or are currently disabled, but excluding fused.
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001551 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001552 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 public List<String> getAllProviders() {
Maggie91e630c2018-01-24 17:31:46 -08001554 ArrayList<String> out;
1555 synchronized (mLock) {
1556 out = new ArrayList<>(mProviders.size());
1557 for (LocationProviderInterface provider : mProviders) {
1558 String name = provider.getName();
1559 if (LocationManager.FUSED_PROVIDER.equals(name)) {
1560 continue;
1561 }
1562 out.add(name);
1563 }
1564 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001565 if (D) Log.d(TAG, "getAllProviders()=" + out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566 return out;
1567 }
1568
Mike Lockwood03ca2162010-04-01 08:10:09 -07001569 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001570 * Return all providers by name, that match criteria and are optionally
1571 * enabled.
1572 * Can return passive provider, but never returns fused provider.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001573 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001574 @Override
1575 public List<String> getProviders(Criteria criteria, boolean enabledOnly) {
Victoria Lease37425c32012-10-16 16:08:48 -07001576 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001577 ArrayList<String> out;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001578 int uid = Binder.getCallingUid();
Victoria Lease269518e2012-10-29 08:25:39 -07001579 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001580 try {
1581 synchronized (mLock) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001582 out = new ArrayList<>(mProviders.size());
Victoria Leaseb711d572012-10-02 13:14:11 -07001583 for (LocationProviderInterface provider : mProviders) {
1584 String name = provider.getName();
1585 if (LocationManager.FUSED_PROVIDER.equals(name)) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001586 continue;
1587 }
Victoria Lease37425c32012-10-16 16:08:48 -07001588 if (allowedResolutionLevel >= getMinimumResolutionLevelForProviderUse(name)) {
Maggie2a9409e2018-03-21 11:47:28 -07001589 if (enabledOnly
1590 && !isAllowedByUserSettingsLocked(name, uid, mCurrentUserId)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001591 continue;
1592 }
1593 if (criteria != null && !LocationProvider.propertiesMeetCriteria(
1594 name, provider.getProperties(), criteria)) {
1595 continue;
1596 }
1597 out.add(name);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001598 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001599 }
Mike Lockwood03ca2162010-04-01 08:10:09 -07001600 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001601 } finally {
1602 Binder.restoreCallingIdentity(identity);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001603 }
1604
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001605 if (D) Log.d(TAG, "getProviders()=" + out);
1606 return out;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001607 }
1608
1609 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001610 * Return the name of the best provider given a Criteria object.
1611 * This method has been deprecated from the public API,
Victoria Lease8dbb6342012-09-21 16:55:53 -07001612 * and the whole LocationProvider (including #meetsCriteria)
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001613 * has been deprecated as well. So this method now uses
1614 * some simplified logic.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001615 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001616 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001617 public String getBestProvider(Criteria criteria, boolean enabledOnly) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001618 String result = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001619
1620 List<String> providers = getProviders(criteria, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001621 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001622 result = pickBest(providers);
1623 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1624 return result;
1625 }
1626 providers = getProviders(null, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001627 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001628 result = pickBest(providers);
1629 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1630 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001631 }
1632
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001633 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001634 return null;
1635 }
1636
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001637 private String pickBest(List<String> providers) {
Victoria Lease1925e292012-09-24 17:00:18 -07001638 if (providers.contains(LocationManager.GPS_PROVIDER)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001639 return LocationManager.GPS_PROVIDER;
Victoria Lease1925e292012-09-24 17:00:18 -07001640 } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
1641 return LocationManager.NETWORK_PROVIDER;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001642 } else {
1643 return providers.get(0);
1644 }
1645 }
1646
Nick Pellye0fd6932012-07-11 10:26:13 -07001647 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001648 public boolean providerMeetsCriteria(String provider, Criteria criteria) {
1649 LocationProviderInterface p = mProvidersByName.get(provider);
1650 if (p == null) {
1651 throw new IllegalArgumentException("provider=" + provider);
1652 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001653
1654 boolean result = LocationProvider.propertiesMeetCriteria(
1655 p.getName(), p.getProperties(), criteria);
1656 if (D) Log.d(TAG, "providerMeetsCriteria(" + provider + ", " + criteria + ")=" + result);
1657 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001658 }
1659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 private void updateProvidersLocked() {
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001661 boolean changesMade = false;
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001662 for (int i = mProviders.size() - 1; i >= 0; i--) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001663 LocationProviderInterface p = mProviders.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 boolean isEnabled = p.isEnabled();
1665 String name = p.getName();
Victoria Lease09eeaec2013-02-05 11:34:13 -08001666 boolean shouldBeEnabled = isAllowedByCurrentUserSettingsLocked(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 if (isEnabled && !shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001668 updateProviderListenersLocked(name, false);
David Christieb084fef2013-12-18 14:33:57 -08001669 // If any provider has been disabled, clear all last locations for all providers.
1670 // This is to be on the safe side in case a provider has location derived from
1671 // this disabled provider.
1672 mLastLocation.clear();
1673 mLastLocationCoarseInterval.clear();
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001674 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 } else if (!isEnabled && shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001676 updateProviderListenersLocked(name, true);
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001677 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 }
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001679 }
1680 if (changesMade) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001681 mContext.sendBroadcastAsUser(new Intent(LocationManager.PROVIDERS_CHANGED_ACTION),
1682 UserHandle.ALL);
Tom O'Neill40a86c22013-09-03 18:05:13 -07001683 mContext.sendBroadcastAsUser(new Intent(LocationManager.MODE_CHANGED_ACTION),
1684 UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 }
1686 }
1687
Amith Yamasanib27528d2014-06-05 15:02:10 -07001688 private void updateProviderListenersLocked(String provider, boolean enabled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 int listeners = 0;
1690
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001691 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001692 if (p == null) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693
1694 ArrayList<Receiver> deadReceivers = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07001695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1697 if (records != null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001698 for (UpdateRecord record : records) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001699 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mIdentity.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001700 // Sends a notification message to the receiver
1701 if (!record.mReceiver.callProviderEnabledLocked(provider, enabled)) {
1702 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001703 deadReceivers = new ArrayList<>();
Victoria Leaseb711d572012-10-02 13:14:11 -07001704 }
1705 deadReceivers.add(record.mReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001707 listeners++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 }
1710 }
1711
1712 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001713 for (int i = deadReceivers.size() - 1; i >= 0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 removeUpdatesLocked(deadReceivers.get(i));
1715 }
1716 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 if (enabled) {
1719 p.enable();
1720 if (listeners > 0) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001721 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 }
1723 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 p.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 }
1727
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001728 private void applyRequirementsLocked(String provider) {
1729 LocationProviderInterface p = mProvidersByName.get(provider);
1730 if (p == null) return;
1731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001733 WorkSource worksource = new WorkSource();
1734 ProviderRequest providerRequest = new ProviderRequest();
1735
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001736 ContentResolver resolver = mContext.getContentResolver();
1737 long backgroundThrottleInterval = Settings.Global.getLong(
1738 resolver,
1739 Settings.Global.LOCATION_BACKGROUND_THROTTLE_INTERVAL_MS,
1740 DEFAULT_BACKGROUND_THROTTLE_INTERVAL_MS);
gomo48f1a642017-11-10 20:35:46 -08001741 // initialize the low power mode to true and set to false if any of the records requires
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001742
gomo48f1a642017-11-10 20:35:46 -08001743 providerRequest.lowPowerMode = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001744 if (records != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001745 for (UpdateRecord record : records) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001746 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mIdentity.mUid))) {
David Christieb870dbf2015-06-22 12:42:53 -07001747 if (checkLocationAccess(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001748 record.mReceiver.mIdentity.mPid,
1749 record.mReceiver.mIdentity.mUid,
1750 record.mReceiver.mIdentity.mPackageName,
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001751 record.mReceiver.mAllowedResolutionLevel)) {
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001752 LocationRequest locationRequest = record.mRealRequest;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001753 long interval = locationRequest.getInterval();
1754
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001755 if (!isThrottlingExemptLocked(record.mReceiver.mIdentity)) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001756 if (!record.mIsForegroundUid) {
1757 interval = Math.max(interval, backgroundThrottleInterval);
1758 }
1759 if (interval != locationRequest.getInterval()) {
1760 locationRequest = new LocationRequest(locationRequest);
1761 locationRequest.setInterval(interval);
1762 }
1763 }
1764
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001765 record.mRequest = locationRequest;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001766 providerRequest.locationRequests.add(locationRequest);
gomo48f1a642017-11-10 20:35:46 -08001767 if (!locationRequest.isLowPowerMode()) {
1768 providerRequest.lowPowerMode = false;
1769 }
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001770 if (interval < providerRequest.interval) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001771 providerRequest.reportLocation = true;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001772 providerRequest.interval = interval;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001773 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001774 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001775 }
1776 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001777
1778 if (providerRequest.reportLocation) {
1779 // calculate who to blame for power
1780 // This is somewhat arbitrary. We pick a threshold interval
1781 // that is slightly higher that the minimum interval, and
1782 // spread the blame across all applications with a request
1783 // under that threshold.
1784 long thresholdInterval = (providerRequest.interval + 1000) * 3 / 2;
1785 for (UpdateRecord record : records) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001786 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mIdentity.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001787 LocationRequest locationRequest = record.mRequest;
Svet Ganove998c732016-06-10 00:12:38 -07001788
1789 // Don't assign battery blame for update records whose
1790 // client has no permission to receive location data.
1791 if (!providerRequest.locationRequests.contains(locationRequest)) {
1792 continue;
1793 }
1794
Victoria Leaseb711d572012-10-02 13:14:11 -07001795 if (locationRequest.getInterval() <= thresholdInterval) {
David Christiee55c9682013-08-22 10:10:34 -07001796 if (record.mReceiver.mWorkSource != null
Narayan Kamath32684dd2018-01-08 17:32:51 +00001797 && isValidWorkSource(record.mReceiver.mWorkSource)) {
David Christie82edc9b2013-07-19 11:31:42 -07001798 worksource.add(record.mReceiver.mWorkSource);
1799 } else {
Narayan Kamath32684dd2018-01-08 17:32:51 +00001800 // Assign blame to caller if there's no WorkSource associated with
1801 // the request or if it's invalid.
David Christie82edc9b2013-07-19 11:31:42 -07001802 worksource.add(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001803 record.mReceiver.mIdentity.mUid,
1804 record.mReceiver.mIdentity.mPackageName);
David Christie82edc9b2013-07-19 11:31:42 -07001805 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001806 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001807 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 }
1810 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001811
1812 if (D) Log.d(TAG, "provider request: " + provider + " " + providerRequest);
1813 p.setRequest(providerRequest, worksource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 }
1815
Narayan Kamath32684dd2018-01-08 17:32:51 +00001816 /**
1817 * Whether a given {@code WorkSource} associated with a Location request is valid.
1818 */
1819 private static boolean isValidWorkSource(WorkSource workSource) {
1820 if (workSource.size() > 0) {
1821 // If the WorkSource has one or more non-chained UIDs, make sure they're accompanied
1822 // by tags.
1823 return workSource.getName(0) != null;
1824 } else {
1825 // For now, make sure callers have supplied an attribution tag for use with
1826 // AppOpsManager. This might be relaxed in the future.
1827 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
1828 return workChains != null && !workChains.isEmpty() &&
1829 workChains.get(0).getAttributionTag() != null;
1830 }
1831 }
1832
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001833 @Override
1834 public String[] getBackgroundThrottlingWhitelist() {
1835 synchronized (mLock) {
1836 return mBackgroundThrottlePackageWhitelist.toArray(
gomo48f1a642017-11-10 20:35:46 -08001837 new String[mBackgroundThrottlePackageWhitelist.size()]);
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001838 }
1839 }
1840
1841 private void updateBackgroundThrottlingWhitelistLocked() {
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001842 String setting = Settings.Global.getString(
gomo48f1a642017-11-10 20:35:46 -08001843 mContext.getContentResolver(),
1844 Settings.Global.LOCATION_BACKGROUND_THROTTLE_PACKAGE_WHITELIST);
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001845 if (setting == null) {
1846 setting = "";
1847 }
1848
1849 mBackgroundThrottlePackageWhitelist.clear();
1850 mBackgroundThrottlePackageWhitelist.addAll(
gomo48f1a642017-11-10 20:35:46 -08001851 SystemConfig.getInstance().getAllowUnthrottledLocation());
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001852 mBackgroundThrottlePackageWhitelist.addAll(
gomo48f1a642017-11-10 20:35:46 -08001853 Arrays.asList(setting.split(",")));
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001854 }
1855
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001856 private boolean isThrottlingExemptLocked(Identity identity) {
1857 if (identity.mUid == Process.SYSTEM_UID) {
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001858 return true;
1859 }
1860
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001861 if (mBackgroundThrottlePackageWhitelist.contains(identity.mPackageName)) {
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001862 return true;
1863 }
1864
1865 for (LocationProviderProxy provider : mProxyProviders) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001866 if (identity.mPackageName.equals(provider.getConnectedPackageName())) {
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001867 return true;
1868 }
1869 }
1870
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001871 return false;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001872 }
1873
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001874 private class UpdateRecord {
1875 final String mProvider;
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001876 final LocationRequest mRealRequest; // original request from client
1877 LocationRequest mRequest; // possibly throttled version of the request
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 final Receiver mReceiver;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001879 boolean mIsForegroundUid;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001880 Location mLastFixBroadcast;
1881 long mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882
1883 /**
1884 * Note: must be constructed with lock held.
1885 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001886 UpdateRecord(String provider, LocationRequest request, Receiver receiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 mProvider = provider;
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001888 mRealRequest = request;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001889 mRequest = request;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 mReceiver = receiver;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001891 mIsForegroundUid = isImportanceForeground(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001892 mActivityManager.getPackageImportance(mReceiver.mIdentity.mPackageName));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893
1894 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1895 if (records == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001896 records = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001897 mRecordsByProvider.put(provider, records);
1898 }
1899 if (!records.contains(this)) {
1900 records.add(this);
1901 }
David Christie2ff96af2014-01-30 16:09:37 -08001902
1903 // Update statistics for historical location requests by package/provider
1904 mRequestStatistics.startRequesting(
Wyatt Rileyf7075e02018-04-12 17:54:26 -07001905 mReceiver.mIdentity.mPackageName, provider, request.getInterval(),
1906 mIsForegroundUid);
1907 }
1908
1909 /**
1910 * Method to be called when record changes foreground/background
1911 */
1912 void updateForeground(boolean isForeground){
1913 mIsForegroundUid = isForeground;
1914 mRequestStatistics.updateForeground(
1915 mReceiver.mIdentity.mPackageName, mProvider, isForeground);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001916 }
1917
1918 /**
David Christie2ff96af2014-01-30 16:09:37 -08001919 * Method to be called when a record will no longer be used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001921 void disposeLocked(boolean removeReceiver) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001922 mRequestStatistics.stopRequesting(mReceiver.mIdentity.mPackageName, mProvider);
David Christie2ff96af2014-01-30 16:09:37 -08001923
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001924 // remove from mRecordsByProvider
1925 ArrayList<UpdateRecord> globalRecords = mRecordsByProvider.get(this.mProvider);
1926 if (globalRecords != null) {
1927 globalRecords.remove(this);
1928 }
1929
1930 if (!removeReceiver) return; // the caller will handle the rest
1931
1932 // remove from Receiver#mUpdateRecords
1933 HashMap<String, UpdateRecord> receiverRecords = mReceiver.mUpdateRecords;
1934 if (receiverRecords != null) {
1935 receiverRecords.remove(this.mProvider);
1936
1937 // and also remove the Receiver if it has no more update records
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001938 if (receiverRecords.size() == 0) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001939 removeUpdatesLocked(mReceiver);
1940 }
Mike Lockwood3a76fd62009-09-01 07:26:56 -04001941 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942 }
1943
1944 @Override
1945 public String toString() {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001946 return "UpdateRecord[" + mProvider + " " + mReceiver.mIdentity.mPackageName
gomo48f1a642017-11-10 20:35:46 -08001947 + "(" + mReceiver.mIdentity.mUid + (mIsForegroundUid ? " foreground"
1948 : " background")
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001949 + ")" + " " + mRealRequest + "]";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 }
1952
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001953 private Receiver getReceiverLocked(ILocationListener listener, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -07001954 String packageName, WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001955 IBinder binder = listener.asBinder();
1956 Receiver receiver = mReceivers.get(binder);
1957 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07001958 receiver = new Receiver(listener, null, pid, uid, packageName, workSource,
1959 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001960 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001961 receiver.getListener().asBinder().linkToDeath(receiver, 0);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001962 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001963 Slog.e(TAG, "linkToDeath failed:", e);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001964 return null;
1965 }
Wen Jingcb3ab222014-03-27 13:42:59 +08001966 mReceivers.put(binder, receiver);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001967 }
1968 return receiver;
1969 }
1970
David Christie82edc9b2013-07-19 11:31:42 -07001971 private Receiver getReceiverLocked(PendingIntent intent, int pid, int uid, String packageName,
David Christie40e57822013-07-30 11:36:48 -07001972 WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001973 Receiver receiver = mReceivers.get(intent);
1974 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07001975 receiver = new Receiver(null, intent, pid, uid, packageName, workSource,
1976 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001977 mReceivers.put(intent, receiver);
1978 }
1979 return receiver;
1980 }
1981
Victoria Lease37425c32012-10-16 16:08:48 -07001982 /**
1983 * Creates a LocationRequest based upon the supplied LocationRequest that to meets resolution
1984 * and consistency requirements.
1985 *
1986 * @param request the LocationRequest from which to create a sanitized version
Victoria Lease37425c32012-10-16 16:08:48 -07001987 * @return a version of request that meets the given resolution and consistency requirements
1988 * @hide
1989 */
gomo48f1a642017-11-10 20:35:46 -08001990 private LocationRequest createSanitizedRequest(LocationRequest request, int resolutionLevel,
1991 boolean callerHasLocationHardwarePermission) {
Victoria Lease37425c32012-10-16 16:08:48 -07001992 LocationRequest sanitizedRequest = new LocationRequest(request);
gomo48f1a642017-11-10 20:35:46 -08001993 if (!callerHasLocationHardwarePermission) {
1994 // allow setting low power mode only for callers with location hardware permission
1995 sanitizedRequest.setLowPowerMode(false);
1996 }
Victoria Lease37425c32012-10-16 16:08:48 -07001997 if (resolutionLevel < RESOLUTION_LEVEL_FINE) {
1998 switch (sanitizedRequest.getQuality()) {
Victoria Lease09016ab2012-09-16 12:33:15 -07001999 case LocationRequest.ACCURACY_FINE:
Victoria Lease37425c32012-10-16 16:08:48 -07002000 sanitizedRequest.setQuality(LocationRequest.ACCURACY_BLOCK);
Victoria Lease09016ab2012-09-16 12:33:15 -07002001 break;
2002 case LocationRequest.POWER_HIGH:
Victoria Lease37425c32012-10-16 16:08:48 -07002003 sanitizedRequest.setQuality(LocationRequest.POWER_LOW);
Victoria Lease09016ab2012-09-16 12:33:15 -07002004 break;
2005 }
2006 // throttle
Victoria Lease37425c32012-10-16 16:08:48 -07002007 if (sanitizedRequest.getInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
2008 sanitizedRequest.setInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07002009 }
Victoria Lease37425c32012-10-16 16:08:48 -07002010 if (sanitizedRequest.getFastestInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
2011 sanitizedRequest.setFastestInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07002012 }
Nick Pelly74fa7ea2012-08-13 19:36:38 -07002013 }
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002014 // make getFastestInterval() the minimum of interval and fastest interval
Victoria Lease37425c32012-10-16 16:08:48 -07002015 if (sanitizedRequest.getFastestInterval() > sanitizedRequest.getInterval()) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002016 request.setFastestInterval(request.getInterval());
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002017 }
Victoria Lease37425c32012-10-16 16:08:48 -07002018 return sanitizedRequest;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002019 }
2020
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002021 private void checkPackageName(String packageName) {
Nick Pellye0fd6932012-07-11 10:26:13 -07002022 if (packageName == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002023 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07002024 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002025 int uid = Binder.getCallingUid();
Nick Pellye0fd6932012-07-11 10:26:13 -07002026 String[] packages = mPackageManager.getPackagesForUid(uid);
2027 if (packages == null) {
2028 throw new SecurityException("invalid UID " + uid);
2029 }
2030 for (String pkg : packages) {
2031 if (packageName.equals(pkg)) return;
2032 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002033 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07002034 }
2035
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002036 private void checkPendingIntent(PendingIntent intent) {
2037 if (intent == null) {
2038 throw new IllegalArgumentException("invalid pending intent: " + intent);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002039 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002040 }
2041
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002042 private Receiver checkListenerOrIntentLocked(ILocationListener listener, PendingIntent intent,
David Christie40e57822013-07-30 11:36:48 -07002043 int pid, int uid, String packageName, WorkSource workSource, boolean hideFromAppOps) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002044 if (intent == null && listener == null) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002045 throw new IllegalArgumentException("need either listener or intent");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002046 } else if (intent != null && listener != null) {
2047 throw new IllegalArgumentException("cannot register both listener and intent");
2048 } else if (intent != null) {
2049 checkPendingIntent(intent);
David Christie40e57822013-07-30 11:36:48 -07002050 return getReceiverLocked(intent, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002051 } else {
David Christie40e57822013-07-30 11:36:48 -07002052 return getReceiverLocked(listener, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002053 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002054 }
2055
Nick Pellye0fd6932012-07-11 10:26:13 -07002056 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002057 public void requestLocationUpdates(LocationRequest request, ILocationListener listener,
2058 PendingIntent intent, String packageName) {
2059 if (request == null) request = DEFAULT_LOCATION_REQUEST;
2060 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002061 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
2062 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
2063 request.getProvider());
David Christie82edc9b2013-07-19 11:31:42 -07002064 WorkSource workSource = request.getWorkSource();
Narayan Kamath32684dd2018-01-08 17:32:51 +00002065 if (workSource != null && !workSource.isEmpty()) {
David Christie40e57822013-07-30 11:36:48 -07002066 checkDeviceStatsAllowed();
2067 }
2068 boolean hideFromAppOps = request.getHideFromAppOps();
2069 if (hideFromAppOps) {
2070 checkUpdateAppOpsAllowed();
David Christie82edc9b2013-07-19 11:31:42 -07002071 }
gomo48f1a642017-11-10 20:35:46 -08002072 boolean callerHasLocationHardwarePermission =
2073 mContext.checkCallingPermission(android.Manifest.permission.LOCATION_HARDWARE)
Maggieaa080f92018-01-04 15:35:11 -08002074 == PERMISSION_GRANTED;
gomo48f1a642017-11-10 20:35:46 -08002075 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel,
2076 callerHasLocationHardwarePermission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002078 final int pid = Binder.getCallingPid();
2079 final int uid = Binder.getCallingUid();
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002080 // providers may use public location API's, need to clear identity
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 long identity = Binder.clearCallingIdentity();
2082 try {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002083 // We don't check for MODE_IGNORED here; we will do that when we go to deliver
2084 // a location.
David Christieb870dbf2015-06-22 12:42:53 -07002085 checkLocationAccess(pid, uid, packageName, allowedResolutionLevel);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002086
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002087 synchronized (mLock) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002088 Receiver recevier = checkListenerOrIntentLocked(listener, intent, pid, uid,
David Christie40e57822013-07-30 11:36:48 -07002089 packageName, workSource, hideFromAppOps);
Victoria Lease37425c32012-10-16 16:08:48 -07002090 requestLocationUpdatesLocked(sanitizedRequest, recevier, pid, uid, packageName);
Mike Lockwood2d4d1bf2010-10-18 17:06:26 -04002091 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002092 } finally {
2093 Binder.restoreCallingIdentity(identity);
2094 }
2095 }
2096
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002097 private void requestLocationUpdatesLocked(LocationRequest request, Receiver receiver,
2098 int pid, int uid, String packageName) {
2099 // Figure out the provider. Either its explicitly request (legacy use cases), or
2100 // use the fused provider
2101 if (request == null) request = DEFAULT_LOCATION_REQUEST;
2102 String name = request.getProvider();
Victoria Lease09016ab2012-09-16 12:33:15 -07002103 if (name == null) {
2104 throw new IllegalArgumentException("provider name must not be null");
2105 }
Zhentao Sunc5fc9982013-04-17 17:47:53 -07002106
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002107 LocationProviderInterface provider = mProvidersByName.get(name);
2108 if (provider == null) {
Victoria Leaseb30f3832013-10-13 12:15:40 -07002109 throw new IllegalArgumentException("provider doesn't exist: " + name);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002110 }
2111
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002112 UpdateRecord record = new UpdateRecord(name, request, receiver);
gomo48f1a642017-11-10 20:35:46 -08002113 if (D) {
2114 Log.d(TAG, "request " + Integer.toHexString(System.identityHashCode(receiver))
2115 + " " + name + " " + request + " from " + packageName + "(" + uid + " "
2116 + (record.mIsForegroundUid ? "foreground" : "background")
2117 + (isThrottlingExemptLocked(receiver.mIdentity)
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002118 ? " [whitelisted]" : "") + ")");
gomo48f1a642017-11-10 20:35:46 -08002119 }
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002120
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002121 UpdateRecord oldRecord = receiver.mUpdateRecords.put(name, record);
2122 if (oldRecord != null) {
2123 oldRecord.disposeLocked(false);
2124 }
2125
Maggie2a9409e2018-03-21 11:47:28 -07002126 boolean isProviderEnabled = isAllowedByUserSettingsLocked(name, uid, mCurrentUserId);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002127 if (isProviderEnabled) {
2128 applyRequirementsLocked(name);
2129 } else {
2130 // Notify the listener that updates are currently disabled
2131 receiver.callProviderEnabledLocked(name, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132 }
David Christie0b837452013-07-29 16:02:13 -07002133 // Update the monitoring here just in case multiple location requests were added to the
2134 // same receiver (this request may be high power and the initial might not have been).
2135 receiver.updateMonitoring(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002136 }
2137
Nick Pellye0fd6932012-07-11 10:26:13 -07002138 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002139 public void removeUpdates(ILocationListener listener, PendingIntent intent,
2140 String packageName) {
2141 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002142
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002143 final int pid = Binder.getCallingPid();
2144 final int uid = Binder.getCallingUid();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002145
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002146 synchronized (mLock) {
David Christie82edc9b2013-07-19 11:31:42 -07002147 WorkSource workSource = null;
David Christie40e57822013-07-30 11:36:48 -07002148 boolean hideFromAppOps = false;
2149 Receiver receiver = checkListenerOrIntentLocked(listener, intent, pid, uid,
2150 packageName, workSource, hideFromAppOps);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002151
2152 // providers may use public location API's, need to clear identity
2153 long identity = Binder.clearCallingIdentity();
2154 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002155 removeUpdatesLocked(receiver);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002156 } finally {
2157 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002158 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002159 }
2160 }
2161
2162 private void removeUpdatesLocked(Receiver receiver) {
Dianne Hackborn7ff30112012-11-08 11:12:09 -08002163 if (D) Log.i(TAG, "remove " + Integer.toHexString(System.identityHashCode(receiver)));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002164
2165 if (mReceivers.remove(receiver.mKey) != null && receiver.isListener()) {
2166 receiver.getListener().asBinder().unlinkToDeath(receiver, 0);
2167 synchronized (receiver) {
Victoria Lease0aa28602013-05-29 15:28:26 -07002168 receiver.clearPendingBroadcastsLocked();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002169 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002170 }
2171
Dianne Hackborn1304f4a2013-07-09 18:17:27 -07002172 receiver.updateMonitoring(false);
2173
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002174 // Record which providers were associated with this listener
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002175 HashSet<String> providers = new HashSet<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002176 HashMap<String, UpdateRecord> oldRecords = receiver.mUpdateRecords;
2177 if (oldRecords != null) {
2178 // Call dispose() on the obsolete update records.
2179 for (UpdateRecord record : oldRecords.values()) {
David Christie2ff96af2014-01-30 16:09:37 -08002180 // Update statistics for historical location requests by package/provider
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002181 record.disposeLocked(false);
2182 }
2183 // Accumulate providers
2184 providers.addAll(oldRecords.keySet());
2185 }
2186
2187 // update provider
2188 for (String provider : providers) {
2189 // If provider is already disabled, don't need to do anything
Victoria Lease09eeaec2013-02-05 11:34:13 -08002190 if (!isAllowedByCurrentUserSettingsLocked(provider)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002191 continue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002192 }
2193
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002194 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002195 }
2196 }
2197
Dianne Hackbornc2293022013-02-06 23:14:49 -08002198 private void applyAllProviderRequirementsLocked() {
2199 for (LocationProviderInterface p : mProviders) {
2200 // If provider is already disabled, don't need to do anything
Dianne Hackborn64d41d72013-02-07 00:33:31 -08002201 if (!isAllowedByCurrentUserSettingsLocked(p.getName())) {
Dianne Hackbornc2293022013-02-06 23:14:49 -08002202 continue;
2203 }
2204
2205 applyRequirementsLocked(p.getName());
2206 }
2207 }
2208
Nick Pellye0fd6932012-07-11 10:26:13 -07002209 @Override
Nick Pelly4035f5a2012-08-17 14:43:49 -07002210 public Location getLastLocation(LocationRequest request, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002211 if (D) Log.d(TAG, "getLastLocation: " + request);
2212 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07002213 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly4035f5a2012-08-17 14:43:49 -07002214 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002215 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
2216 request.getProvider());
2217 // no need to sanitize this request, as only the provider name is used
Nick Pelly4035f5a2012-08-17 14:43:49 -07002218
David Christieb870dbf2015-06-22 12:42:53 -07002219 final int pid = Binder.getCallingPid();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002220 final int uid = Binder.getCallingUid();
2221 final long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07002222 try {
2223 if (mBlacklist.isBlacklisted(packageName)) {
gomo48f1a642017-11-10 20:35:46 -08002224 if (D) {
2225 Log.d(TAG, "not returning last loc for blacklisted app: " +
2226 packageName);
2227 }
Victoria Lease09016ab2012-09-16 12:33:15 -07002228 return null;
2229 }
Victoria Leaseb711d572012-10-02 13:14:11 -07002230
David Christieb870dbf2015-06-22 12:42:53 -07002231 if (!reportLocationAccessNoThrow(pid, uid, packageName, allowedResolutionLevel)) {
gomo48f1a642017-11-10 20:35:46 -08002232 if (D) {
2233 Log.d(TAG, "not returning last loc for no op app: " +
2234 packageName);
2235 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002236 return null;
2237 }
2238
Victoria Leaseb711d572012-10-02 13:14:11 -07002239 synchronized (mLock) {
2240 // Figure out the provider. Either its explicitly request (deprecated API's),
2241 // or use the fused provider
2242 String name = request.getProvider();
2243 if (name == null) name = LocationManager.FUSED_PROVIDER;
2244 LocationProviderInterface provider = mProvidersByName.get(name);
2245 if (provider == null) return null;
2246
Maggie2a9409e2018-03-21 11:47:28 -07002247 if (!isAllowedByUserSettingsLocked(name, uid, mCurrentUserId)) return null;
Victoria Leaseb711d572012-10-02 13:14:11 -07002248
David Christie1b9b7b12013-04-15 15:31:11 -07002249 Location location;
2250 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
2251 // Make sure that an app with coarse permissions can't get frequent location
2252 // updates by calling LocationManager.getLastKnownLocation repeatedly.
2253 location = mLastLocationCoarseInterval.get(name);
2254 } else {
2255 location = mLastLocation.get(name);
2256 }
Victoria Leaseb711d572012-10-02 13:14:11 -07002257 if (location == null) {
2258 return null;
2259 }
Victoria Lease37425c32012-10-16 16:08:48 -07002260 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
gomo48f1a642017-11-10 20:35:46 -08002261 Location noGPSLocation = location.getExtraLocation(
2262 Location.EXTRA_NO_GPS_LOCATION);
Victoria Leaseb711d572012-10-02 13:14:11 -07002263 if (noGPSLocation != null) {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08002264 return new Location(mLocationFudger.getOrCreate(noGPSLocation));
Victoria Leaseb711d572012-10-02 13:14:11 -07002265 }
Victoria Lease37425c32012-10-16 16:08:48 -07002266 } else {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08002267 return new Location(location);
Victoria Lease09016ab2012-09-16 12:33:15 -07002268 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002269 }
Victoria Leaseb711d572012-10-02 13:14:11 -07002270 return null;
2271 } finally {
2272 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002273 }
2274 }
2275
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002276 /**
2277 * Provides an interface to inject and set the last location if location is not available
2278 * currently.
2279 *
2280 * This helps in cases where the product (Cars for example) has saved the last known location
2281 * before powering off. This interface lets the client inject the saved location while the GPS
2282 * chipset is getting its first fix, there by improving user experience.
2283 *
2284 * @param location - Location object to inject
2285 * @return true if update was successful, false if not
2286 */
2287 @Override
2288 public boolean injectLocation(Location location) {
2289 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
2290 "Location Hardware permission not granted to inject location");
2291 mContext.enforceCallingPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
2292 "Access Fine Location permission not granted to inject Location");
2293
2294 if (location == null) {
2295 if (D) {
2296 Log.d(TAG, "injectLocation(): called with null location");
2297 }
2298 return false;
2299 }
2300 LocationProviderInterface p = null;
2301 String provider = location.getProvider();
2302 if (provider != null) {
2303 p = mProvidersByName.get(provider);
2304 }
2305 if (p == null) {
2306 if (D) {
2307 Log.d(TAG, "injectLocation(): unknown provider");
2308 }
2309 return false;
2310 }
2311 synchronized (mLock) {
2312 if (!isAllowedByCurrentUserSettingsLocked(provider)) {
2313 if (D) {
2314 Log.d(TAG, "Location disabled in Settings for current user:" + mCurrentUserId);
2315 }
2316 return false;
2317 } else {
2318 // NOTE: If last location is already available, location is not injected. If
2319 // provider's normal source (like a GPS chipset) have already provided an output,
2320 // there is no need to inject this location.
2321 if (mLastLocation.get(provider) == null) {
2322 updateLastLocationLocked(location, provider);
2323 } else {
2324 if (D) {
2325 Log.d(TAG, "injectLocation(): Location exists. Not updating");
2326 }
2327 return false;
2328 }
2329 }
2330 }
2331 return true;
2332 }
2333
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002334 @Override
2335 public void requestGeofence(LocationRequest request, Geofence geofence, PendingIntent intent,
2336 String packageName) {
2337 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07002338 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
2339 checkResolutionLevelIsSufficientForGeofenceUse(allowedResolutionLevel);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002340 checkPendingIntent(intent);
2341 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002342 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
2343 request.getProvider());
gomo48f1a642017-11-10 20:35:46 -08002344 // Require that caller can manage given document
2345 boolean callerHasLocationHardwarePermission =
2346 mContext.checkCallingPermission(android.Manifest.permission.LOCATION_HARDWARE)
Maggieaa080f92018-01-04 15:35:11 -08002347 == PERMISSION_GRANTED;
gomo48f1a642017-11-10 20:35:46 -08002348 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel,
2349 callerHasLocationHardwarePermission);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002350
Victoria Lease37425c32012-10-16 16:08:48 -07002351 if (D) Log.d(TAG, "requestGeofence: " + sanitizedRequest + " " + geofence + " " + intent);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002352
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002353 // geo-fence manager uses the public location API, need to clear identity
2354 int uid = Binder.getCallingUid();
Xiaohui Chena4490622015-09-22 15:29:31 -07002355 // TODO: http://b/23822629
2356 if (UserHandle.getUserId(uid) != UserHandle.USER_SYSTEM) {
Victoria Lease56e675b2012-11-05 19:25:06 -08002357 // temporary measure until geofences work for secondary users
2358 Log.w(TAG, "proximity alerts are currently available only to the primary user");
2359 return;
2360 }
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002361 long identity = Binder.clearCallingIdentity();
2362 try {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002363 mGeofenceManager.addFence(sanitizedRequest, geofence, intent, allowedResolutionLevel,
2364 uid, packageName);
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002365 } finally {
2366 Binder.restoreCallingIdentity(identity);
2367 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002368 }
2369
2370 @Override
2371 public void removeGeofence(Geofence geofence, PendingIntent intent, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002372 checkPendingIntent(intent);
2373 checkPackageName(packageName);
2374
2375 if (D) Log.d(TAG, "removeGeofence: " + geofence + " " + intent);
2376
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002377 // geo-fence manager uses the public location API, need to clear identity
2378 long identity = Binder.clearCallingIdentity();
2379 try {
2380 mGeofenceManager.removeFence(geofence, intent);
2381 } finally {
2382 Binder.restoreCallingIdentity(identity);
2383 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002384 }
2385
2386
2387 @Override
Lifu Tang30f95a72016-01-07 23:20:38 -08002388 public boolean registerGnssStatusCallback(IGnssStatusListener callback, String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002389 if (!hasGnssPermissions(packageName) || mGnssStatusProvider == null) {
Takayuki Hoshib254ab6a2014-10-23 16:46:02 +09002390 return false;
2391 }
2392
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002393 try {
Lifu Tang30f95a72016-01-07 23:20:38 -08002394 mGnssStatusProvider.registerGnssStatusCallback(callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002395 } catch (RemoteException e) {
Lifu Tang30f95a72016-01-07 23:20:38 -08002396 Slog.e(TAG, "mGpsStatusProvider.registerGnssStatusCallback failed", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002397 return false;
2398 }
2399 return true;
2400 }
2401
Nick Pellye0fd6932012-07-11 10:26:13 -07002402 @Override
Lifu Tang30f95a72016-01-07 23:20:38 -08002403 public void unregisterGnssStatusCallback(IGnssStatusListener callback) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002404 synchronized (mLock) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002405 try {
Lifu Tang30f95a72016-01-07 23:20:38 -08002406 mGnssStatusProvider.unregisterGnssStatusCallback(callback);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002407 } catch (Exception e) {
Lifu Tang30f95a72016-01-07 23:20:38 -08002408 Slog.e(TAG, "mGpsStatusProvider.unregisterGnssStatusCallback failed", e);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002409 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002410 }
2411 }
2412
Nick Pellye0fd6932012-07-11 10:26:13 -07002413 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002414 public boolean addGnssMeasurementsListener(
gomo48f1a642017-11-10 20:35:46 -08002415 IGnssMeasurementsListener listener, String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002416 if (!hasGnssPermissions(packageName) || mGnssMeasurementsProvider == null) {
destradaaea8a8a62014-06-23 18:19:03 -07002417 return false;
2418 }
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002419
2420 synchronized (mLock) {
2421 Identity callerIdentity
2422 = new Identity(Binder.getCallingUid(), Binder.getCallingPid(), packageName);
Wyatt Riley11cc7492018-01-17 08:48:27 -08002423 mGnssMeasurementsListeners.put(listener.asBinder(), callerIdentity);
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002424 long identity = Binder.clearCallingIdentity();
2425 try {
2426 if (isThrottlingExemptLocked(callerIdentity)
2427 || isImportanceForeground(
gomo48f1a642017-11-10 20:35:46 -08002428 mActivityManager.getPackageImportance(packageName))) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002429 return mGnssMeasurementsProvider.addListener(listener);
2430 }
2431 } finally {
2432 Binder.restoreCallingIdentity(identity);
2433 }
2434
2435 return true;
2436 }
destradaaea8a8a62014-06-23 18:19:03 -07002437 }
2438
2439 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002440 public void removeGnssMeasurementsListener(IGnssMeasurementsListener listener) {
2441 if (mGnssMeasurementsProvider != null) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002442 synchronized (mLock) {
Wyatt Riley11cc7492018-01-17 08:48:27 -08002443 mGnssMeasurementsListeners.remove(listener.asBinder());
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002444 mGnssMeasurementsProvider.removeListener(listener);
2445 }
Wei Liu5241a4c2015-05-11 14:00:36 -07002446 }
destradaaea8a8a62014-06-23 18:19:03 -07002447 }
2448
2449 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002450 public boolean addGnssNavigationMessageListener(
2451 IGnssNavigationMessageListener listener,
destradaa4b3e3932014-07-21 18:01:47 -07002452 String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002453 if (!hasGnssPermissions(packageName) || mGnssNavigationMessageProvider == null) {
destradaa4b3e3932014-07-21 18:01:47 -07002454 return false;
2455 }
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002456
2457 synchronized (mLock) {
2458 Identity callerIdentity
gomo48f1a642017-11-10 20:35:46 -08002459 = new Identity(Binder.getCallingUid(), Binder.getCallingPid(), packageName);
Wyatt Riley11cc7492018-01-17 08:48:27 -08002460 mGnssNavigationMessageListeners.put(listener.asBinder(), callerIdentity);
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002461 long identity = Binder.clearCallingIdentity();
2462 try {
2463 if (isThrottlingExemptLocked(callerIdentity)
2464 || isImportanceForeground(
gomo48f1a642017-11-10 20:35:46 -08002465 mActivityManager.getPackageImportance(packageName))) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002466 return mGnssNavigationMessageProvider.addListener(listener);
2467 }
2468 } finally {
2469 Binder.restoreCallingIdentity(identity);
2470 }
2471
2472 return true;
2473 }
destradaa4b3e3932014-07-21 18:01:47 -07002474 }
2475
2476 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002477 public void removeGnssNavigationMessageListener(IGnssNavigationMessageListener listener) {
2478 if (mGnssNavigationMessageProvider != null) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002479 synchronized (mLock) {
Wyatt Riley11cc7492018-01-17 08:48:27 -08002480 mGnssNavigationMessageListeners.remove(listener.asBinder());
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002481 mGnssNavigationMessageProvider.removeListener(listener);
2482 }
Wei Liu5241a4c2015-05-11 14:00:36 -07002483 }
destradaa4b3e3932014-07-21 18:01:47 -07002484 }
2485
2486 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002487 public boolean sendExtraCommand(String provider, String command, Bundle extras) {
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04002488 if (provider == null) {
2489 // throw NullPointerException to remain compatible with previous implementation
2490 throw new NullPointerException();
2491 }
Victoria Lease37425c32012-10-16 16:08:48 -07002492 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
2493 provider);
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04002494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 // and check for ACCESS_LOCATION_EXTRA_COMMANDS
Mike Lockwoodb7e99222009-07-07 13:18:21 -04002496 if ((mContext.checkCallingOrSelfPermission(ACCESS_LOCATION_EXTRA_COMMANDS)
Maggieaa080f92018-01-04 15:35:11 -08002497 != PERMISSION_GRANTED)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498 throw new SecurityException("Requires ACCESS_LOCATION_EXTRA_COMMANDS permission");
2499 }
2500
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002501 synchronized (mLock) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002502 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002503 if (p == null) return false;
Nick Pellye0fd6932012-07-11 10:26:13 -07002504
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002505 return p.sendExtraCommand(command, extras);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002506 }
2507 }
2508
Nick Pellye0fd6932012-07-11 10:26:13 -07002509 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002510 public boolean sendNiResponse(int notifId, int userResponse) {
Mike Lockwood18ad9f62009-08-27 14:01:23 -07002511 if (Binder.getCallingUid() != Process.myUid()) {
2512 throw new SecurityException(
2513 "calling sendNiResponse from outside of the system is not allowed");
2514 }
Danke Xie22d1f9f2009-08-18 18:28:45 -04002515 try {
2516 return mNetInitiatedListener.sendNiResponse(notifId, userResponse);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002517 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002518 Slog.e(TAG, "RemoteException in LocationManagerService.sendNiResponse");
Danke Xie22d1f9f2009-08-18 18:28:45 -04002519 return false;
2520 }
2521 }
2522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 /**
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002524 * @return null if the provider does not exist
Alexey Tarasovf2db9fb2009-09-01 02:37:07 +11002525 * @throws SecurityException if the provider is not allowed to be
gomo48f1a642017-11-10 20:35:46 -08002526 * accessed by the caller
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 */
Nick Pellye0fd6932012-07-11 10:26:13 -07002528 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002529 public ProviderProperties getProviderProperties(String provider) {
Laurent Tub7f9d252012-10-16 14:25:00 -07002530 if (mProvidersByName.get(provider) == null) {
David Christie2ff96af2014-01-30 16:09:37 -08002531 return null;
Laurent Tub7f9d252012-10-16 14:25:00 -07002532 }
2533
Victoria Lease37425c32012-10-16 16:08:48 -07002534 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
2535 provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002537 LocationProviderInterface p;
2538 synchronized (mLock) {
2539 p = mProvidersByName.get(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002540 }
2541
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002542 if (p == null) return null;
2543 return p.getProperties();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 }
2545
Jason Monkb71218a2015-06-17 14:44:39 -04002546 /**
2547 * @return null if the provider does not exist
2548 * @throws SecurityException if the provider is not allowed to be
gomo48f1a642017-11-10 20:35:46 -08002549 * accessed by the caller
Jason Monkb71218a2015-06-17 14:44:39 -04002550 */
2551 @Override
2552 public String getNetworkProviderPackage() {
2553 LocationProviderInterface p;
2554 synchronized (mLock) {
2555 if (mProvidersByName.get(LocationManager.NETWORK_PROVIDER) == null) {
2556 return null;
2557 }
2558 p = mProvidersByName.get(LocationManager.NETWORK_PROVIDER);
2559 }
2560
2561 if (p instanceof LocationProviderProxy) {
2562 return ((LocationProviderProxy) p).getConnectedPackageName();
2563 }
2564 return null;
2565 }
2566
Maggieaa080f92018-01-04 15:35:11 -08002567 /**
Maggie2a9409e2018-03-21 11:47:28 -07002568 * Returns the current location enabled/disabled status for a user
2569 *
2570 * @param userId the id of the user
2571 * @return true if location is enabled
2572 */
2573 @Override
2574 public boolean isLocationEnabledForUser(int userId) {
2575 // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
2576 checkInteractAcrossUsersPermission(userId);
2577
2578 long identity = Binder.clearCallingIdentity();
2579 try {
2580 synchronized (mLock) {
2581 final String allowedProviders = Settings.Secure.getStringForUser(
2582 mContext.getContentResolver(),
2583 Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
2584 userId);
2585 if (allowedProviders == null) {
2586 return false;
2587 }
2588 final List<String> providerList = Arrays.asList(allowedProviders.split(","));
2589 for(String provider : mRealProviders.keySet()) {
2590 if (provider.equals(LocationManager.PASSIVE_PROVIDER)
2591 || provider.equals(LocationManager.FUSED_PROVIDER)) {
2592 continue;
2593 }
2594 if (providerList.contains(provider)) {
2595 return true;
2596 }
2597 }
2598 return false;
2599 }
2600 } finally {
2601 Binder.restoreCallingIdentity(identity);
2602 }
2603 }
2604
2605 /**
2606 * Enable or disable location for a user
2607 *
2608 * @param enabled true to enable location, false to disable location
2609 * @param userId the id of the user
2610 */
2611 @Override
2612 public void setLocationEnabledForUser(boolean enabled, int userId) {
2613 mContext.enforceCallingPermission(
2614 android.Manifest.permission.WRITE_SECURE_SETTINGS,
2615 "Requires WRITE_SECURE_SETTINGS permission");
2616
2617 // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
2618 checkInteractAcrossUsersPermission(userId);
2619
2620 long identity = Binder.clearCallingIdentity();
2621 try {
2622 synchronized (mLock) {
2623 final Set<String> allRealProviders = mRealProviders.keySet();
2624 // Update all providers on device plus gps and network provider when disabling
2625 // location
2626 Set<String> allProvidersSet = new ArraySet<>(allRealProviders.size() + 2);
2627 allProvidersSet.addAll(allRealProviders);
2628 // When disabling location, disable gps and network provider that could have been
2629 // enabled by location mode api.
2630 if (enabled == false) {
2631 allProvidersSet.add(LocationManager.GPS_PROVIDER);
2632 allProvidersSet.add(LocationManager.NETWORK_PROVIDER);
2633 }
2634 if (allProvidersSet.isEmpty()) {
2635 return;
2636 }
2637 // to ensure thread safety, we write the provider name with a '+' or '-'
2638 // and let the SettingsProvider handle it rather than reading and modifying
2639 // the list of enabled providers.
2640 final String prefix = enabled ? "+" : "-";
2641 StringBuilder locationProvidersAllowed = new StringBuilder();
2642 for (String provider : allProvidersSet) {
2643 if (provider.equals(LocationManager.PASSIVE_PROVIDER)
2644 || provider.equals(LocationManager.FUSED_PROVIDER)) {
2645 continue;
2646 }
2647 locationProvidersAllowed.append(prefix);
2648 locationProvidersAllowed.append(provider);
2649 locationProvidersAllowed.append(",");
2650 }
2651 // Remove the trailing comma
2652 locationProvidersAllowed.setLength(locationProvidersAllowed.length() - 1);
2653 Settings.Secure.putStringForUser(
2654 mContext.getContentResolver(),
2655 Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
2656 locationProvidersAllowed.toString(),
2657 userId);
2658 }
2659 } finally {
2660 Binder.restoreCallingIdentity(identity);
2661 }
2662 }
2663
2664 /**
2665 * Returns the current enabled/disabled status of a location provider and user
2666 *
2667 * @param provider name of the provider
2668 * @param userId the id of the user
2669 * @return true if the provider exists and is enabled
2670 */
2671 @Override
2672 public boolean isProviderEnabledForUser(String provider, int userId) {
2673 // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
2674 checkInteractAcrossUsersPermission(userId);
2675
2676 // Fused provider is accessed indirectly via criteria rather than the provider-based APIs,
2677 // so we discourage its use
2678 if (LocationManager.FUSED_PROVIDER.equals(provider)) return false;
2679
2680 int uid = Binder.getCallingUid();
2681 synchronized (mLock) {
2682 LocationProviderInterface p = mProvidersByName.get(provider);
2683 return p != null
2684 && isAllowedByUserSettingsLocked(provider, uid, userId);
2685 }
2686 }
2687
2688 /**
2689 * Enable or disable a single location provider.
2690 *
2691 * @param provider name of the provider
2692 * @param enabled true to enable the provider. False to disable the provider
2693 * @param userId the id of the user to set
2694 * @return true if the value was set, false on errors
2695 */
2696 @Override
2697 public boolean setProviderEnabledForUser(String provider, boolean enabled, int userId) {
2698 mContext.enforceCallingPermission(
2699 android.Manifest.permission.WRITE_SECURE_SETTINGS,
2700 "Requires WRITE_SECURE_SETTINGS permission");
2701
2702 // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
2703 checkInteractAcrossUsersPermission(userId);
2704
2705 // Fused provider is accessed indirectly via criteria rather than the provider-based APIs,
2706 // so we discourage its use
2707 if (LocationManager.FUSED_PROVIDER.equals(provider)) return false;
2708
2709 long identity = Binder.clearCallingIdentity();
2710 try {
2711 synchronized (mLock) {
2712 // No such provider exists
2713 if (!mProvidersByName.containsKey(provider)) return false;
2714
2715 // If it is a test provider, do not write to Settings.Secure
2716 if (mMockProviders.containsKey(provider)) {
2717 setTestProviderEnabled(provider, enabled);
2718 return true;
2719 }
2720
2721 // to ensure thread safety, we write the provider name with a '+' or '-'
2722 // and let the SettingsProvider handle it rather than reading and modifying
2723 // the list of enabled providers.
2724 String providerChange = (enabled ? "+" : "-") + provider;
2725 return Settings.Secure.putStringForUser(
2726 mContext.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
2727 providerChange, userId);
2728 }
2729 } finally {
2730 Binder.restoreCallingIdentity(identity);
2731 }
2732 }
2733
2734 /**
Maggieaa080f92018-01-04 15:35:11 -08002735 * Read location provider status from Settings.Secure
2736 *
2737 * @param provider the location provider to query
2738 * @param userId the user id to query
2739 * @return true if the provider is enabled
2740 */
2741 private boolean isLocationProviderEnabledForUser(String provider, int userId) {
2742 long identity = Binder.clearCallingIdentity();
2743 try {
2744 // Use system settings
2745 ContentResolver cr = mContext.getContentResolver();
2746 String allowedProviders = Settings.Secure.getStringForUser(
2747 cr, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
2748 return TextUtils.delimitedStringContains(allowedProviders, ',', provider);
2749 } finally {
2750 Binder.restoreCallingIdentity(identity);
2751 }
2752 }
2753
2754 /**
Maggie2a9409e2018-03-21 11:47:28 -07002755 * Method for checking INTERACT_ACROSS_USERS permission if specified user id is not the same as
2756 * current user id
2757 *
2758 * @param userId the user id to get or set value
2759 */
2760 private void checkInteractAcrossUsersPermission(int userId) {
2761 int uid = Binder.getCallingUid();
2762 if (UserHandle.getUserId(uid) != userId) {
2763 if (ActivityManager.checkComponentPermission(
2764 android.Manifest.permission.INTERACT_ACROSS_USERS, uid, -1, true)
2765 != PERMISSION_GRANTED) {
2766 throw new SecurityException("Requires INTERACT_ACROSS_USERS permission");
2767 }
2768 }
2769 }
2770
2771 /**
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002772 * Returns "true" if the UID belongs to a bound location provider.
2773 *
2774 * @param uid the uid
2775 * @return true if uid belongs to a bound location provider
2776 */
2777 private boolean isUidALocationProvider(int uid) {
2778 if (uid == Process.SYSTEM_UID) {
2779 return true;
2780 }
2781 if (mGeocodeProvider != null) {
David Christie1f141c12014-05-14 15:11:15 -07002782 if (doesUidHavePackage(uid, mGeocodeProvider.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002783 }
2784 for (LocationProviderProxy proxy : mProxyProviders) {
David Christie1f141c12014-05-14 15:11:15 -07002785 if (doesUidHavePackage(uid, proxy.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002786 }
2787 return false;
2788 }
2789
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002790 private void checkCallerIsProvider() {
2791 if (mContext.checkCallingOrSelfPermission(INSTALL_LOCATION_PROVIDER)
Maggieaa080f92018-01-04 15:35:11 -08002792 == PERMISSION_GRANTED) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002793 return;
2794 }
2795
2796 // Previously we only used the INSTALL_LOCATION_PROVIDER
2797 // check. But that is system or signature
2798 // protection level which is not flexible enough for
2799 // providers installed oustide the system image. So
2800 // also allow providers with a UID matching the
2801 // currently bound package name
2802
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002803 if (isUidALocationProvider(Binder.getCallingUid())) {
2804 return;
2805 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002806
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002807 throw new SecurityException("need INSTALL_LOCATION_PROVIDER permission, " +
2808 "or UID of a currently bound location provider");
2809 }
2810
David Christie1f141c12014-05-14 15:11:15 -07002811 /**
2812 * Returns true if the given package belongs to the given uid.
2813 */
2814 private boolean doesUidHavePackage(int uid, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002815 if (packageName == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 return false;
2817 }
David Christie1f141c12014-05-14 15:11:15 -07002818 String[] packageNames = mPackageManager.getPackagesForUid(uid);
2819 if (packageNames == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002820 return false;
2821 }
David Christie1f141c12014-05-14 15:11:15 -07002822 for (String name : packageNames) {
2823 if (packageName.equals(name)) {
2824 return true;
2825 }
2826 }
2827 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002828 }
2829
Nick Pellye0fd6932012-07-11 10:26:13 -07002830 @Override
Mike Lockwooda4903f22010-02-17 06:42:23 -05002831 public void reportLocation(Location location, boolean passive) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002832 checkCallerIsProvider();
Mike Lockwood275555c2009-05-01 11:30:34 -04002833
Nick Pelly2eeeec22012-07-18 13:13:37 -07002834 if (!location.isComplete()) {
2835 Log.w(TAG, "Dropping incomplete location: " + location);
2836 return;
2837 }
2838
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002839 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED, location);
2840 Message m = Message.obtain(mLocationHandler, MSG_LOCATION_CHANGED, location);
Mike Lockwooda4903f22010-02-17 06:42:23 -05002841 m.arg1 = (passive ? 1 : 0);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002842 mLocationHandler.sendMessageAtFrontOfQueue(m);
2843 }
2844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002845
Laurent Tu75defb62012-11-01 16:21:52 -07002846 private static boolean shouldBroadcastSafe(
2847 Location loc, Location lastLoc, UpdateRecord record, long now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 // Always broadcast the first update
2849 if (lastLoc == null) {
2850 return true;
2851 }
2852
Nick Pellyf1be6862012-05-15 10:53:42 -07002853 // Check whether sufficient time has passed
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002854 long minTime = record.mRealRequest.getFastestInterval();
David Christie1b9b7b12013-04-15 15:31:11 -07002855 long delta = (loc.getElapsedRealtimeNanos() - lastLoc.getElapsedRealtimeNanos())
2856 / NANOS_PER_MILLI;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002857 if (delta < minTime - MAX_PROVIDER_SCHEDULING_JITTER_MS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002858 return false;
2859 }
2860
2861 // Check whether sufficient distance has been traveled
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002862 double minDistance = record.mRealRequest.getSmallestDisplacement();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 if (minDistance > 0.0) {
2864 if (loc.distanceTo(lastLoc) <= minDistance) {
2865 return false;
2866 }
2867 }
2868
Laurent Tu75defb62012-11-01 16:21:52 -07002869 // Check whether sufficient number of udpates is left
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002870 if (record.mRealRequest.getNumUpdates() <= 0) {
Laurent Tu75defb62012-11-01 16:21:52 -07002871 return false;
2872 }
2873
2874 // Check whether the expiry date has passed
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002875 return record.mRealRequest.getExpireAt() >= now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002876 }
2877
Mike Lockwooda4903f22010-02-17 06:42:23 -05002878 private void handleLocationChangedLocked(Location location, boolean passive) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002879 if (D) Log.d(TAG, "incoming location: " + location);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002880 long now = SystemClock.elapsedRealtime();
Mike Lockwooda4903f22010-02-17 06:42:23 -05002881 String provider = (passive ? LocationManager.PASSIVE_PROVIDER : location.getProvider());
Laurent Tu60ec50a2012-10-04 17:00:10 -07002882 // Skip if the provider is unknown.
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002883 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002884 if (p == null) return;
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002885 updateLastLocationLocked(location, provider);
2886 // mLastLocation should have been updated from the updateLastLocationLocked call above.
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002887 Location lastLocation = mLastLocation.get(provider);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002888 if (lastLocation == null) {
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002889 Log.e(TAG, "handleLocationChangedLocked() updateLastLocation failed");
2890 return;
Mike Lockwood4e50b782009-04-03 08:24:43 -07002891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892
David Christie1b9b7b12013-04-15 15:31:11 -07002893 // Update last known coarse interval location if enough time has passed.
2894 Location lastLocationCoarseInterval = mLastLocationCoarseInterval.get(provider);
2895 if (lastLocationCoarseInterval == null) {
2896 lastLocationCoarseInterval = new Location(location);
2897 mLastLocationCoarseInterval.put(provider, lastLocationCoarseInterval);
2898 }
2899 long timeDiffNanos = location.getElapsedRealtimeNanos()
2900 - lastLocationCoarseInterval.getElapsedRealtimeNanos();
2901 if (timeDiffNanos > LocationFudger.FASTEST_INTERVAL_MS * NANOS_PER_MILLI) {
2902 lastLocationCoarseInterval.set(location);
2903 }
2904 // Don't ever return a coarse location that is more recent than the allowed update
2905 // interval (i.e. don't allow an app to keep registering and unregistering for
2906 // location updates to overcome the minimum interval).
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002907 Location noGPSLocation =
David Christie1b9b7b12013-04-15 15:31:11 -07002908 lastLocationCoarseInterval.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2909
Laurent Tu60ec50a2012-10-04 17:00:10 -07002910 // Skip if there are no UpdateRecords for this provider.
2911 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
2912 if (records == null || records.size() == 0) return;
2913
Victoria Lease09016ab2012-09-16 12:33:15 -07002914 // Fetch coarse location
2915 Location coarseLocation = null;
David Christie1b9b7b12013-04-15 15:31:11 -07002916 if (noGPSLocation != null) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002917 coarseLocation = mLocationFudger.getOrCreate(noGPSLocation);
2918 }
2919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002920 // Fetch latest status update time
2921 long newStatusUpdateTime = p.getStatusUpdateTime();
2922
David Christie2ff96af2014-01-30 16:09:37 -08002923 // Get latest status
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002924 Bundle extras = new Bundle();
2925 int status = p.getStatus(extras);
2926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002927 ArrayList<Receiver> deadReceivers = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002928 ArrayList<UpdateRecord> deadUpdateRecords = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07002929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002930 // Broadcast location or status to all listeners
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002931 for (UpdateRecord r : records) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 Receiver receiver = r.mReceiver;
Mike Lockwood03ca2162010-04-01 08:10:09 -07002933 boolean receiverDead = false;
Nick Pelly4035f5a2012-08-17 14:43:49 -07002934
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002935 int receiverUserId = UserHandle.getUserId(receiver.mIdentity.mUid);
2936 if (!isCurrentProfile(receiverUserId)
2937 && !isUidALocationProvider(receiver.mIdentity.mUid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07002938 if (D) {
Victoria Lease269518e2012-10-29 08:25:39 -07002939 Log.d(TAG, "skipping loc update for background user " + receiverUserId +
Victoria Leaseb711d572012-10-02 13:14:11 -07002940 " (current user: " + mCurrentUserId + ", app: " +
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002941 receiver.mIdentity.mPackageName + ")");
Victoria Leaseb711d572012-10-02 13:14:11 -07002942 }
2943 continue;
2944 }
2945
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002946 if (mBlacklist.isBlacklisted(receiver.mIdentity.mPackageName)) {
gomo48f1a642017-11-10 20:35:46 -08002947 if (D) {
2948 Log.d(TAG, "skipping loc update for blacklisted app: " +
2949 receiver.mIdentity.mPackageName);
2950 }
Nick Pelly4035f5a2012-08-17 14:43:49 -07002951 continue;
2952 }
2953
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002954 if (!reportLocationAccessNoThrow(
2955 receiver.mIdentity.mPid,
2956 receiver.mIdentity.mUid,
2957 receiver.mIdentity.mPackageName,
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002958 receiver.mAllowedResolutionLevel)) {
gomo48f1a642017-11-10 20:35:46 -08002959 if (D) {
2960 Log.d(TAG, "skipping loc update for no op app: " +
2961 receiver.mIdentity.mPackageName);
2962 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002963 continue;
2964 }
2965
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002966 Location notifyLocation;
Victoria Lease37425c32012-10-16 16:08:48 -07002967 if (receiver.mAllowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
2968 notifyLocation = coarseLocation; // use coarse location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002969 } else {
Victoria Lease37425c32012-10-16 16:08:48 -07002970 notifyLocation = lastLocation; // use fine location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002971 }
Victoria Lease09016ab2012-09-16 12:33:15 -07002972 if (notifyLocation != null) {
2973 Location lastLoc = r.mLastFixBroadcast;
Laurent Tu75defb62012-11-01 16:21:52 -07002974 if ((lastLoc == null) || shouldBroadcastSafe(notifyLocation, lastLoc, r, now)) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002975 if (lastLoc == null) {
2976 lastLoc = new Location(notifyLocation);
2977 r.mLastFixBroadcast = lastLoc;
2978 } else {
2979 lastLoc.set(notifyLocation);
2980 }
2981 if (!receiver.callLocationChangedLocked(notifyLocation)) {
2982 Slog.w(TAG, "RemoteException calling onLocationChanged on " + receiver);
2983 receiverDead = true;
2984 }
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002985 r.mRealRequest.decrementNumUpdates();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002986 }
2987 }
2988
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002989 long prevStatusUpdateTime = r.mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002990 if ((newStatusUpdateTime > prevStatusUpdateTime) &&
Victoria Lease09016ab2012-09-16 12:33:15 -07002991 (prevStatusUpdateTime != 0 || status != LocationProvider.AVAILABLE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002992
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002993 r.mLastStatusBroadcast = newStatusUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002994 if (!receiver.callStatusChangedLocked(provider, status, extras)) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07002995 receiverDead = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002996 Slog.w(TAG, "RemoteException calling onStatusChanged on " + receiver);
Mike Lockwood03ca2162010-04-01 08:10:09 -07002997 }
2998 }
2999
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003000 // track expired records
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07003001 if (r.mRealRequest.getNumUpdates() <= 0 || r.mRealRequest.getExpireAt() < now) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003002 if (deadUpdateRecords == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08003003 deadUpdateRecords = new ArrayList<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003004 }
3005 deadUpdateRecords.add(r);
3006 }
3007 // track dead receivers
3008 if (receiverDead) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07003009 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08003010 deadReceivers = new ArrayList<>();
Mike Lockwood03ca2162010-04-01 08:10:09 -07003011 }
3012 if (!deadReceivers.contains(receiver)) {
3013 deadReceivers.add(receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003014 }
3015 }
3016 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003017
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003018 // remove dead records and receivers outside the loop
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003019 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003020 for (Receiver receiver : deadReceivers) {
3021 removeUpdatesLocked(receiver);
3022 }
3023 }
3024 if (deadUpdateRecords != null) {
3025 for (UpdateRecord r : deadUpdateRecords) {
3026 r.disposeLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003027 }
Victoria Lease8b38b292012-12-04 15:04:43 -08003028 applyRequirementsLocked(provider);
3029 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003030 }
3031
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08003032 /**
3033 * Updates last location with the given location
3034 *
3035 * @param location new location to update
3036 * @param provider Location provider to update for
3037 */
3038 private void updateLastLocationLocked(Location location, String provider) {
3039 Location noGPSLocation = location.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
3040 Location lastNoGPSLocation;
3041 Location lastLocation = mLastLocation.get(provider);
3042 if (lastLocation == null) {
3043 lastLocation = new Location(provider);
3044 mLastLocation.put(provider, lastLocation);
3045 } else {
3046 lastNoGPSLocation = lastLocation.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
3047 if (noGPSLocation == null && lastNoGPSLocation != null) {
3048 // New location has no no-GPS location: adopt last no-GPS location. This is set
3049 // directly into location because we do not want to notify COARSE clients.
3050 location.setExtraLocation(Location.EXTRA_NO_GPS_LOCATION, lastNoGPSLocation);
3051 }
3052 }
3053 lastLocation.set(location);
3054 }
3055
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003056 private class LocationWorkerHandler extends Handler {
Victoria Lease5cd731a2012-12-19 15:04:21 -08003057 public LocationWorkerHandler(Looper looper) {
3058 super(looper, null, true);
3059 }
3060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003061 @Override
3062 public void handleMessage(Message msg) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003063 switch (msg.what) {
3064 case MSG_LOCATION_CHANGED:
3065 handleLocationChanged((Location) msg.obj, msg.arg1 == 1);
3066 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003067 }
3068 }
3069 }
3070
Victoria Lease54ca7ae2013-01-08 09:39:50 -08003071 private boolean isMockProvider(String provider) {
3072 synchronized (mLock) {
3073 return mMockProviders.containsKey(provider);
3074 }
3075 }
3076
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003077 private void handleLocationChanged(Location location, boolean passive) {
Victoria Lease54ca7ae2013-01-08 09:39:50 -08003078 // create a working copy of the incoming Location so that the service can modify it without
3079 // disturbing the caller's copy
3080 Location myLocation = new Location(location);
3081 String provider = myLocation.getProvider();
3082
3083 // set "isFromMockProvider" bit if location came from a mock provider. we do not clear this
3084 // bit if location did not come from a mock provider because passive/fused providers can
3085 // forward locations from mock providers, and should not grant them legitimacy in doing so.
3086 if (!myLocation.isFromMockProvider() && isMockProvider(provider)) {
3087 myLocation.setIsFromMockProvider(true);
3088 }
Jeff Sharkey5e613312012-01-30 11:16:20 -08003089
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003090 synchronized (mLock) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08003091 if (isAllowedByCurrentUserSettingsLocked(provider)) {
3092 if (!passive) {
3093 // notify passive provider of the new location
3094 mPassiveProvider.updateLocation(myLocation);
3095 }
Victoria Lease54ca7ae2013-01-08 09:39:50 -08003096 handleLocationChangedLocked(myLocation, passive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003097 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003098 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003099 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003100
Mike Lockwoode97ae402010-09-29 15:23:46 -04003101 private final PackageMonitor mPackageMonitor = new PackageMonitor() {
3102 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003103 public void onPackageDisappeared(String packageName, int reason) {
3104 // remove all receivers associated with this package name
3105 synchronized (mLock) {
3106 ArrayList<Receiver> deadReceivers = null;
3107
3108 for (Receiver receiver : mReceivers.values()) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08003109 if (receiver.mIdentity.mPackageName.equals(packageName)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003110 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08003111 deadReceivers = new ArrayList<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003112 }
3113 deadReceivers.add(receiver);
3114 }
3115 }
3116
3117 // perform removal outside of mReceivers loop
3118 if (deadReceivers != null) {
3119 for (Receiver receiver : deadReceivers) {
3120 removeUpdatesLocked(receiver);
3121 }
3122 }
3123 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003124 }
Mike Lockwoode97ae402010-09-29 15:23:46 -04003125 };
3126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003127 // Geocoder
3128
Nick Pellye0fd6932012-07-11 10:26:13 -07003129 @Override
Mike Lockwoode15735a2010-09-20 17:48:47 -04003130 public boolean geocoderIsPresent() {
Mark Vandevoorde01ac80b2010-05-21 15:43:26 -07003131 return mGeocodeProvider != null;
3132 }
3133
Nick Pellye0fd6932012-07-11 10:26:13 -07003134 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003135 public String getFromLocation(double latitude, double longitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05003136 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04003137 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05003138 return mGeocodeProvider.getFromLocation(latitude, longitude, maxResults,
3139 params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003140 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04003141 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003142 }
3143
Mike Lockwooda55c3212009-04-15 11:10:11 -04003144
Nick Pellye0fd6932012-07-11 10:26:13 -07003145 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003146 public String getFromLocationName(String locationName,
Mike Lockwooda55c3212009-04-15 11:10:11 -04003147 double lowerLeftLatitude, double lowerLeftLongitude,
3148 double upperRightLatitude, double upperRightLongitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05003149 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04003150
3151 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05003152 return mGeocodeProvider.getFromLocationName(locationName, lowerLeftLatitude,
3153 lowerLeftLongitude, upperRightLatitude, upperRightLongitude,
3154 maxResults, params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003155 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04003156 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003157 }
3158
3159 // Mock Providers
3160
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003161 private boolean canCallerAccessMockLocation(String opPackageName) {
3162 return mAppOps.noteOp(AppOpsManager.OP_MOCK_LOCATION, Binder.getCallingUid(),
3163 opPackageName) == AppOpsManager.MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003164 }
3165
Nick Pellye0fd6932012-07-11 10:26:13 -07003166 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003167 public void addTestProvider(String name, ProviderProperties properties, String opPackageName) {
3168 if (!canCallerAccessMockLocation(opPackageName)) {
3169 return;
3170 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003171
Mike Lockwooda4903f22010-02-17 06:42:23 -05003172 if (LocationManager.PASSIVE_PROVIDER.equals(name)) {
3173 throw new IllegalArgumentException("Cannot mock the passive location provider");
3174 }
3175
Mike Lockwood86328a92009-10-23 08:38:25 -04003176 long identity = Binder.clearCallingIdentity();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003177 synchronized (mLock) {
Mike Lockwood7566c1d2009-08-25 10:05:18 -07003178 // remove the real provider if we are replacing GPS or network provider
3179 if (LocationManager.GPS_PROVIDER.equals(name)
Nick Pelly1332b532012-08-21 16:25:47 -07003180 || LocationManager.NETWORK_PROVIDER.equals(name)
3181 || LocationManager.FUSED_PROVIDER.equals(name)) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05003182 LocationProviderInterface p = mProvidersByName.get(name);
3183 if (p != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003184 removeProviderLocked(p);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07003185 }
3186 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09003187 addTestProviderLocked(name, properties);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003188 updateProvidersLocked();
3189 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003190 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003191 }
3192
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09003193 private void addTestProviderLocked(String name, ProviderProperties properties) {
3194 if (mProvidersByName.get(name) != null) {
3195 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
3196 }
3197 MockProvider provider = new MockProvider(name, this, properties);
3198 addProviderLocked(provider);
3199 mMockProviders.put(name, provider);
3200 mLastLocation.put(name, null);
3201 mLastLocationCoarseInterval.put(name, null);
3202 }
3203
Nick Pellye0fd6932012-07-11 10:26:13 -07003204 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003205 public void removeTestProvider(String provider, String opPackageName) {
3206 if (!canCallerAccessMockLocation(opPackageName)) {
3207 return;
3208 }
3209
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003210 synchronized (mLock) {
Tom O'Neill07ee5d12014-03-03 17:48:35 -08003211
3212 // These methods can't be called after removing the test provider, so first make sure
Tom O'Neillfe6d3c52014-03-04 08:26:17 -08003213 // we don't leave anything dangling.
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003214 clearTestProviderEnabled(provider, opPackageName);
3215 clearTestProviderLocation(provider, opPackageName);
3216 clearTestProviderStatus(provider, opPackageName);
Tom O'Neill07ee5d12014-03-03 17:48:35 -08003217
You Kima6d0b6f2012-10-28 03:58:44 +09003218 MockProvider mockProvider = mMockProviders.remove(provider);
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003219 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3221 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003222 long identity = Binder.clearCallingIdentity();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003223 removeProviderLocked(mProvidersByName.get(provider));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003224
3225 // reinstate real provider if available
3226 LocationProviderInterface realProvider = mRealProviders.get(provider);
3227 if (realProvider != null) {
3228 addProviderLocked(realProvider);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07003229 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003230 mLastLocation.put(provider, null);
David Christie1b9b7b12013-04-15 15:31:11 -07003231 mLastLocationCoarseInterval.put(provider, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003232 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04003233 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003234 }
3235 }
3236
Nick Pellye0fd6932012-07-11 10:26:13 -07003237 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003238 public void setTestProviderLocation(String provider, Location loc, String opPackageName) {
3239 if (!canCallerAccessMockLocation(opPackageName)) {
3240 return;
3241 }
3242
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003243 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003244 MockProvider mockProvider = mMockProviders.get(provider);
3245 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003246 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3247 }
Tom O'Neilla206a0f2016-12-15 10:26:28 -08003248
3249 // Ensure that the location is marked as being mock. There's some logic to do this in
3250 // handleLocationChanged(), but it fails if loc has the wrong provider (bug 33091107).
3251 Location mock = new Location(loc);
3252 mock.setIsFromMockProvider(true);
3253
3254 if (!TextUtils.isEmpty(loc.getProvider()) && !provider.equals(loc.getProvider())) {
3255 // The location has an explicit provider that is different from the mock provider
3256 // name. The caller may be trying to fool us via bug 33091107.
3257 EventLog.writeEvent(0x534e4554, "33091107", Binder.getCallingUid(),
3258 provider + "!=" + loc.getProvider());
3259 }
3260
Mike Lockwood95427cd2009-05-07 13:27:54 -04003261 // clear calling identity so INSTALL_LOCATION_PROVIDER permission is not required
3262 long identity = Binder.clearCallingIdentity();
Tom O'Neilla206a0f2016-12-15 10:26:28 -08003263 mockProvider.setLocation(mock);
Mike Lockwood95427cd2009-05-07 13:27:54 -04003264 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003265 }
3266 }
3267
Nick Pellye0fd6932012-07-11 10:26:13 -07003268 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003269 public void clearTestProviderLocation(String provider, String opPackageName) {
3270 if (!canCallerAccessMockLocation(opPackageName)) {
3271 return;
3272 }
3273
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003274 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003275 MockProvider mockProvider = mMockProviders.get(provider);
3276 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003277 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3278 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003279 mockProvider.clearLocation();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003280 }
3281 }
3282
Nick Pellye0fd6932012-07-11 10:26:13 -07003283 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003284 public void setTestProviderEnabled(String provider, boolean enabled, String opPackageName) {
3285 if (!canCallerAccessMockLocation(opPackageName)) {
3286 return;
3287 }
Maggie2a9409e2018-03-21 11:47:28 -07003288 setTestProviderEnabled(provider, enabled);
3289 }
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003290
Maggie2a9409e2018-03-21 11:47:28 -07003291 /** Enable or disable a test location provider. */
3292 private void setTestProviderEnabled(String provider, boolean enabled) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003293 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003294 MockProvider mockProvider = mMockProviders.get(provider);
3295 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003296 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3297 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003298 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003299 if (enabled) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003300 mockProvider.enable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003301 mEnabledProviders.add(provider);
3302 mDisabledProviders.remove(provider);
3303 } else {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003304 mockProvider.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003305 mEnabledProviders.remove(provider);
3306 mDisabledProviders.add(provider);
3307 }
3308 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04003309 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003310 }
3311 }
3312
Nick Pellye0fd6932012-07-11 10:26:13 -07003313 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003314 public void clearTestProviderEnabled(String provider, String opPackageName) {
3315 if (!canCallerAccessMockLocation(opPackageName)) {
3316 return;
3317 }
3318
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003319 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003320 MockProvider mockProvider = mMockProviders.get(provider);
3321 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003322 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3323 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003324 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 mEnabledProviders.remove(provider);
3326 mDisabledProviders.remove(provider);
3327 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04003328 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003329 }
3330 }
3331
Nick Pellye0fd6932012-07-11 10:26:13 -07003332 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003333 public void setTestProviderStatus(String provider, int status, Bundle extras, long updateTime,
3334 String opPackageName) {
3335 if (!canCallerAccessMockLocation(opPackageName)) {
3336 return;
3337 }
3338
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003339 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003340 MockProvider mockProvider = mMockProviders.get(provider);
3341 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003342 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3343 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003344 mockProvider.setStatus(status, extras, updateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 }
3346 }
3347
Nick Pellye0fd6932012-07-11 10:26:13 -07003348 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003349 public void clearTestProviderStatus(String provider, String opPackageName) {
3350 if (!canCallerAccessMockLocation(opPackageName)) {
3351 return;
3352 }
3353
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003354 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003355 MockProvider mockProvider = mMockProviders.get(provider);
3356 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003357 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3358 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003359 mockProvider.clearStatus();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003360 }
3361 }
3362
3363 private void log(String log) {
3364 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003365 Slog.d(TAG, log);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003366 }
3367 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003368
3369 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003370 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003371 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Nick Pellye0fd6932012-07-11 10:26:13 -07003372
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003373 synchronized (mLock) {
Siddharth Raybb608c82017-03-16 11:33:34 -07003374 if (args.length > 0 && args[0].equals("--gnssmetrics")) {
3375 if (mGnssMetricsProvider != null) {
3376 pw.append(mGnssMetricsProvider.getGnssMetricsAsProtoString());
3377 }
3378 return;
3379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003380 pw.println("Current Location Manager state:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 pw.println(" Location Listeners:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003382 for (Receiver receiver : mReceivers.values()) {
3383 pw.println(" " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003384 }
David Christie2ff96af2014-01-30 16:09:37 -08003385 pw.println(" Active Records by Provider:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003386 for (Map.Entry<String, ArrayList<UpdateRecord>> entry : mRecordsByProvider.entrySet()) {
3387 pw.println(" " + entry.getKey() + ":");
3388 for (UpdateRecord record : entry.getValue()) {
3389 pw.println(" " + record);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003390 }
3391 }
Wyatt Riley11cc7492018-01-17 08:48:27 -08003392 pw.println(" Active GnssMeasurement Listeners:");
3393 for (Identity identity : mGnssMeasurementsListeners.values()) {
3394 pw.println(" " + identity.mPid + " " + identity.mUid + " "
3395 + identity.mPackageName + ": " + isThrottlingExemptLocked(identity));
3396 }
3397 pw.println(" Active GnssNavigationMessage Listeners:");
3398 for (Identity identity : mGnssNavigationMessageListeners.values()) {
3399 pw.println(" " + identity.mPid + " " + identity.mUid + " "
3400 + identity.mPackageName + ": " + isThrottlingExemptLocked(identity));
3401 }
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08003402 pw.println(" Overlay Provider Packages:");
3403 for (LocationProviderInterface provider : mProviders) {
3404 if (provider instanceof LocationProviderProxy) {
3405 pw.println(" " + provider.getName() + ": "
3406 + ((LocationProviderProxy) provider).getConnectedPackageName());
3407 }
3408 }
David Christie2ff96af2014-01-30 16:09:37 -08003409 pw.println(" Historical Records by Provider:");
3410 for (Map.Entry<PackageProviderKey, PackageStatistics> entry
3411 : mRequestStatistics.statistics.entrySet()) {
3412 PackageProviderKey key = entry.getKey();
3413 PackageStatistics stats = entry.getValue();
3414 pw.println(" " + key.packageName + ": " + key.providerName + ": " + stats);
3415 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003416 pw.println(" Last Known Locations:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003417 for (Map.Entry<String, Location> entry : mLastLocation.entrySet()) {
3418 String provider = entry.getKey();
3419 Location location = entry.getValue();
3420 pw.println(" " + provider + ": " + location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003421 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003422
David Christie1b9b7b12013-04-15 15:31:11 -07003423 pw.println(" Last Known Locations Coarse Intervals:");
3424 for (Map.Entry<String, Location> entry : mLastLocationCoarseInterval.entrySet()) {
3425 String provider = entry.getKey();
3426 Location location = entry.getValue();
3427 pw.println(" " + provider + ": " + location);
3428 }
3429
Nick Pellye0fd6932012-07-11 10:26:13 -07003430 mGeofenceManager.dump(pw);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003432 if (mEnabledProviders.size() > 0) {
3433 pw.println(" Enabled Providers:");
3434 for (String i : mEnabledProviders) {
3435 pw.println(" " + i);
3436 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003437
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003438 }
3439 if (mDisabledProviders.size() > 0) {
3440 pw.println(" Disabled Providers:");
3441 for (String i : mDisabledProviders) {
3442 pw.println(" " + i);
3443 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003444 }
Nick Pelly4035f5a2012-08-17 14:43:49 -07003445 pw.append(" ");
3446 mBlacklist.dump(pw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003447 if (mMockProviders.size() > 0) {
3448 pw.println(" Mock Providers:");
3449 for (Map.Entry<String, MockProvider> i : mMockProviders.entrySet()) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003450 i.getValue().dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003451 }
3452 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003453
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08003454 if (!mBackgroundThrottlePackageWhitelist.isEmpty()) {
3455 pw.println(" Throttling Whitelisted Packages:");
3456 for (String packageName : mBackgroundThrottlePackageWhitelist) {
3457 pw.println(" " + packageName);
3458 }
3459 }
3460
Nick Pelly74fa7ea2012-08-13 19:36:38 -07003461 pw.append(" fudger: ");
gomo48f1a642017-11-10 20:35:46 -08003462 mLocationFudger.dump(fd, pw, args);
Nick Pelly74fa7ea2012-08-13 19:36:38 -07003463
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003464 if (args.length > 0 && "short".equals(args[0])) {
3465 return;
3466 }
gomo48f1a642017-11-10 20:35:46 -08003467 for (LocationProviderInterface provider : mProviders) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003468 pw.print(provider.getName() + " Internal State");
3469 if (provider instanceof LocationProviderProxy) {
3470 LocationProviderProxy proxy = (LocationProviderProxy) provider;
3471 pw.print(" (" + proxy.getConnectedPackageName() + ")");
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06003472 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003473 pw.println(":");
3474 provider.dump(fd, pw, args);
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06003475 }
Wyatt Rileycf879db2017-01-12 13:57:38 -08003476 if (mGnssBatchingInProgress) {
3477 pw.println(" GNSS batching in progress");
3478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003479 }
3480 }
3481}