blob: d4290ee615c0df604963ef14e937d5eb17ff51e9 [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 }
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700427 record.mIsForegroundUid = foreground;
428
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,
Lifu Tang519f0d02018-04-12 16:39:39 -0700963 getResolutionPermission(mAllowedResolutionLevel),
964 PendingIntentUtils.createDontSendToRestrictedAppsBundle(null));
Mike Lockwood48f17512009-04-23 09:12:08 -0700965 // call this after broadcasting so we do not increment
966 // if we throw an exeption.
967 incrementPendingBroadcastsLocked();
968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 } catch (PendingIntent.CanceledException e) {
970 return false;
971 }
972 }
973 return true;
974 }
975
976 public boolean callLocationChangedLocked(Location location) {
977 if (mListener != null) {
978 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700979 synchronized (this) {
980 // synchronize to ensure incrementPendingBroadcastsLocked()
981 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c5406a2012-11-29 16:18:01 -0800982 mListener.onLocationChanged(new Location(location));
Nick Pellye0fd6932012-07-11 10:26:13 -0700983 // call this after broadcasting so we do not increment
984 // if we throw an exeption.
985 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700986 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 } catch (RemoteException e) {
988 return false;
989 }
990 } else {
991 Intent locationChanged = new Intent();
gomo48f1a642017-11-10 20:35:46 -0800992 locationChanged.putExtra(LocationManager.KEY_LOCATION_CHANGED,
993 new Location(location));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700995 synchronized (this) {
996 // synchronize to ensure incrementPendingBroadcastsLocked()
997 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700998 mPendingIntent.send(mContext, 0, locationChanged, this, mLocationHandler,
Lifu Tang519f0d02018-04-12 16:39:39 -0700999 getResolutionPermission(mAllowedResolutionLevel),
1000 PendingIntentUtils.createDontSendToRestrictedAppsBundle(null));
Mike Lockwood48f17512009-04-23 09:12:08 -07001001 // call this after broadcasting so we do not increment
1002 // if we throw an exeption.
1003 incrementPendingBroadcastsLocked();
1004 }
1005 } catch (PendingIntent.CanceledException e) {
1006 return false;
1007 }
1008 }
1009 return true;
1010 }
1011
1012 public boolean callProviderEnabledLocked(String provider, boolean enabled) {
David Christie15b31912013-08-13 15:54:32 -07001013 // First update AppOp monitoring.
1014 // An app may get/lose location access as providers are enabled/disabled.
1015 updateMonitoring(true);
1016
Mike Lockwood48f17512009-04-23 09:12:08 -07001017 if (mListener != null) {
1018 try {
1019 synchronized (this) {
1020 // synchronize to ensure incrementPendingBroadcastsLocked()
1021 // is called before decrementPendingBroadcasts()
1022 if (enabled) {
1023 mListener.onProviderEnabled(provider);
1024 } else {
1025 mListener.onProviderDisabled(provider);
1026 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001027 // call this after broadcasting so we do not increment
1028 // if we throw an exeption.
1029 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001030 }
1031 } catch (RemoteException e) {
1032 return false;
1033 }
1034 } else {
1035 Intent providerIntent = new Intent();
1036 providerIntent.putExtra(LocationManager.KEY_PROVIDER_ENABLED, enabled);
1037 try {
1038 synchronized (this) {
1039 // synchronize to ensure incrementPendingBroadcastsLocked()
1040 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001041 mPendingIntent.send(mContext, 0, providerIntent, this, mLocationHandler,
Lifu Tang519f0d02018-04-12 16:39:39 -07001042 getResolutionPermission(mAllowedResolutionLevel),
1043 PendingIntentUtils.createDontSendToRestrictedAppsBundle(null));
Mike Lockwood48f17512009-04-23 09:12:08 -07001044 // call this after broadcasting so we do not increment
1045 // if we throw an exeption.
1046 incrementPendingBroadcastsLocked();
1047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 } catch (PendingIntent.CanceledException e) {
1049 return false;
1050 }
1051 }
1052 return true;
1053 }
1054
Nick Pellyf1be6862012-05-15 10:53:42 -07001055 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 public void binderDied() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001057 if (D) Log.d(TAG, "Location listener died");
1058
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001059 synchronized (mLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 removeUpdatesLocked(this);
1061 }
Mike Lockwood48f17512009-04-23 09:12:08 -07001062 synchronized (this) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001063 clearPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001064 }
1065 }
1066
Nick Pellye0fd6932012-07-11 10:26:13 -07001067 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -07001068 public void onSendFinished(PendingIntent pendingIntent, Intent intent,
1069 int resultCode, String resultData, Bundle resultExtras) {
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001070 synchronized (this) {
1071 decrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001072 }
1073 }
1074
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001075 // this must be called while synchronized by caller in a synchronized block
1076 // containing the sending of the broadcaset
1077 private void incrementPendingBroadcastsLocked() {
1078 if (mPendingBroadcasts++ == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001079 mWakeLock.acquire();
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001080 }
1081 }
1082
1083 private void decrementPendingBroadcastsLocked() {
1084 if (--mPendingBroadcasts == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001085 if (mWakeLock.isHeld()) {
1086 mWakeLock.release();
1087 }
1088 }
1089 }
1090
1091 public void clearPendingBroadcastsLocked() {
1092 if (mPendingBroadcasts > 0) {
1093 mPendingBroadcasts = 0;
1094 if (mWakeLock.isHeld()) {
1095 mWakeLock.release();
1096 }
Mike Lockwood48f17512009-04-23 09:12:08 -07001097 }
1098 }
1099 }
1100
Nick Pellye0fd6932012-07-11 10:26:13 -07001101 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -07001102 public void locationCallbackFinished(ILocationListener listener) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001103 //Do not use getReceiverLocked here as that will add the ILocationListener to
Joshua Bartel080b61b2009-10-05 12:44:46 -04001104 //the receiver list if it is not found. If it is not found then the
1105 //LocationListener was removed when it had a pending broadcast and should
1106 //not be added back.
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001107 synchronized (mLock) {
1108 IBinder binder = listener.asBinder();
1109 Receiver receiver = mReceivers.get(binder);
1110 if (receiver != null) {
1111 synchronized (receiver) {
1112 // so wakelock calls will succeed
1113 long identity = Binder.clearCallingIdentity();
1114 receiver.decrementPendingBroadcastsLocked();
1115 Binder.restoreCallingIdentity(identity);
David Christie2ff96af2014-01-30 16:09:37 -08001116 }
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001117 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 }
1119 }
1120
Lifu Tang82f893d2016-01-21 18:15:33 -08001121 /**
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001122 * Returns the year of the GNSS hardware.
Lifu Tang82f893d2016-01-21 18:15:33 -08001123 */
1124 @Override
Lifu Tang9363b942016-02-16 18:07:00 -08001125 public int getGnssYearOfHardware() {
Wyatt Rileycf879db2017-01-12 13:57:38 -08001126 if (mGnssSystemInfoProvider != null) {
Lifu Tang9363b942016-02-16 18:07:00 -08001127 return mGnssSystemInfoProvider.getGnssYearOfHardware();
Lifu Tang82f893d2016-01-21 18:15:33 -08001128 } else {
1129 return 0;
1130 }
1131 }
1132
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001133
1134 /**
1135 * Returns the model name of the GNSS hardware.
1136 */
1137 @Override
Wyatt Riley49097c02018-03-15 09:14:43 -07001138 @Nullable
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001139 public String getGnssHardwareModelName() {
1140 if (mGnssSystemInfoProvider != null) {
1141 return mGnssSystemInfoProvider.getGnssHardwareModelName();
1142 } else {
Wyatt Riley49097c02018-03-15 09:14:43 -07001143 return null;
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001144 }
1145 }
1146
Wyatt Rileycf879db2017-01-12 13:57:38 -08001147 /**
1148 * Runs some checks for GNSS (FINE) level permissions, used by several methods which directly
1149 * (try to) access GNSS information at this layer.
1150 */
1151 private boolean hasGnssPermissions(String packageName) {
1152 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1153 checkResolutionLevelIsSufficientForProviderUse(
1154 allowedResolutionLevel,
1155 LocationManager.GPS_PROVIDER);
1156
1157 int pid = Binder.getCallingPid();
1158 int uid = Binder.getCallingUid();
1159 long identity = Binder.clearCallingIdentity();
1160 boolean hasLocationAccess;
1161 try {
1162 hasLocationAccess = checkLocationAccess(pid, uid, packageName, allowedResolutionLevel);
1163 } finally {
1164 Binder.restoreCallingIdentity(identity);
1165 }
1166
1167 return hasLocationAccess;
1168 }
1169
1170 /**
1171 * Returns the GNSS batching size, if available.
1172 */
1173 @Override
1174 public int getGnssBatchSize(String packageName) {
1175 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1176 "Location Hardware permission not granted to access hardware batching");
1177
1178 if (hasGnssPermissions(packageName) && mGnssBatchingProvider != null) {
1179 return mGnssBatchingProvider.getSize();
1180 } else {
1181 return 0;
1182 }
1183 }
1184
1185 /**
1186 * Adds a callback for GNSS Batching events, if permissions allow, which are transported
1187 * to potentially multiple listeners by the BatchedLocationCallbackTransport above this.
1188 */
1189 @Override
1190 public boolean addGnssBatchingCallback(IBatchedLocationCallback callback, String packageName) {
1191 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1192 "Location Hardware permission not granted to access hardware batching");
1193
1194 if (!hasGnssPermissions(packageName) || mGnssBatchingProvider == null) {
1195 return false;
1196 }
1197
1198 mGnssBatchingCallback = callback;
1199 mGnssBatchingDeathCallback = new LinkedCallback(callback);
1200 try {
1201 callback.asBinder().linkToDeath(mGnssBatchingDeathCallback, 0 /* flags */);
1202 } catch (RemoteException e) {
1203 // if the remote process registering the listener is already dead, just swallow the
1204 // exception and return
1205 Log.e(TAG, "Remote listener already died.", e);
1206 return false;
1207 }
1208
1209 return true;
1210 }
1211
1212 private class LinkedCallback implements IBinder.DeathRecipient {
1213 private final IBatchedLocationCallback mCallback;
1214
1215 public LinkedCallback(@NonNull IBatchedLocationCallback callback) {
1216 mCallback = callback;
1217 }
1218
1219 @NonNull
1220 public IBatchedLocationCallback getUnderlyingListener() {
1221 return mCallback;
1222 }
1223
1224 @Override
1225 public void binderDied() {
1226 Log.d(TAG, "Remote Batching Callback died: " + mCallback);
1227 stopGnssBatch();
1228 removeGnssBatchingCallback();
1229 }
1230 }
1231
1232 /**
1233 * Removes callback for GNSS batching
1234 */
1235 @Override
1236 public void removeGnssBatchingCallback() {
1237 try {
1238 mGnssBatchingCallback.asBinder().unlinkToDeath(mGnssBatchingDeathCallback,
1239 0 /* flags */);
1240 } catch (NoSuchElementException e) {
1241 // if the death callback isn't connected (it should be...), log error, swallow the
1242 // exception and return
1243 Log.e(TAG, "Couldn't unlink death callback.", e);
1244 }
1245 mGnssBatchingCallback = null;
1246 mGnssBatchingDeathCallback = null;
1247 }
1248
1249
1250 /**
1251 * Starts GNSS batching, if available.
1252 */
1253 @Override
1254 public boolean startGnssBatch(long periodNanos, boolean wakeOnFifoFull, String packageName) {
1255 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1256 "Location Hardware permission not granted to access hardware batching");
1257
1258 if (!hasGnssPermissions(packageName) || mGnssBatchingProvider == null) {
1259 return false;
1260 }
1261
1262 if (mGnssBatchingInProgress) {
1263 // Current design does not expect multiple starts to be called repeatedly
1264 Log.e(TAG, "startGnssBatch unexpectedly called w/o stopping prior batch");
1265 // Try to clean up anyway, and continue
1266 stopGnssBatch();
1267 }
1268
1269 mGnssBatchingInProgress = true;
1270 return mGnssBatchingProvider.start(periodNanos, wakeOnFifoFull);
1271 }
1272
1273 /**
1274 * Flushes a GNSS batch in progress
1275 */
1276 @Override
1277 public void flushGnssBatch(String packageName) {
1278 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1279 "Location Hardware permission not granted to access hardware batching");
1280
1281 if (!hasGnssPermissions(packageName)) {
1282 Log.e(TAG, "flushGnssBatch called without GNSS permissions");
1283 return;
1284 }
1285
1286 if (!mGnssBatchingInProgress) {
1287 Log.w(TAG, "flushGnssBatch called with no batch in progress");
1288 }
1289
1290 if (mGnssBatchingProvider != null) {
gomo48f1a642017-11-10 20:35:46 -08001291 mGnssBatchingProvider.flush();
Wyatt Rileycf879db2017-01-12 13:57:38 -08001292 }
1293 }
1294
1295 /**
1296 * Stops GNSS batching
1297 */
1298 @Override
1299 public boolean stopGnssBatch() {
1300 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1301 "Location Hardware permission not granted to access hardware batching");
1302
1303 if (mGnssBatchingProvider != null) {
1304 mGnssBatchingInProgress = false;
1305 return mGnssBatchingProvider.stop();
gomo48f1a642017-11-10 20:35:46 -08001306 } else {
Wyatt Rileycf879db2017-01-12 13:57:38 -08001307 return false;
1308 }
1309 }
1310
1311 @Override
1312 public void reportLocationBatch(List<Location> locations) {
1313 checkCallerIsProvider();
1314
1315 // Currently used only for GNSS locations - update permissions check if changed
1316 if (isAllowedByCurrentUserSettingsLocked(LocationManager.GPS_PROVIDER)) {
1317 if (mGnssBatchingCallback == null) {
1318 Slog.e(TAG, "reportLocationBatch() called without active Callback");
1319 return;
1320 }
1321 try {
1322 mGnssBatchingCallback.onLocationBatch(locations);
1323 } catch (RemoteException e) {
1324 Slog.e(TAG, "mGnssBatchingCallback.onLocationBatch failed", e);
1325 }
1326 } else {
1327 Slog.w(TAG, "reportLocationBatch() called without user permission, locations blocked");
1328 }
1329 }
1330
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001331 private void addProviderLocked(LocationProviderInterface provider) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001332 mProviders.add(provider);
1333 mProvidersByName.put(provider.getName(), provider);
1334 }
1335
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001336 private void removeProviderLocked(LocationProviderInterface provider) {
1337 provider.disable();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001338 mProviders.remove(provider);
1339 mProvidersByName.remove(provider.getName());
1340 }
1341
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001342 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -08001343 * Returns "true" if access to the specified location provider is allowed by the current
1344 * user's settings. Access to all location providers is forbidden to non-location-provider
1345 * processes belonging to background users.
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001346 *
1347 * @param provider the name of the location provider
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001348 */
Victoria Lease09eeaec2013-02-05 11:34:13 -08001349 private boolean isAllowedByCurrentUserSettingsLocked(String provider) {
Maggie2a9409e2018-03-21 11:47:28 -07001350 return isAllowedByUserSettingsLockedForUser(provider, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 }
1352
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001353 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -08001354 * Returns "true" if access to the specified location provider is allowed by the specified
1355 * user's settings. Access to all location providers is forbidden to non-location-provider
1356 * processes belonging to background users.
1357 *
1358 * @param provider the name of the location provider
Maggie2a9409e2018-03-21 11:47:28 -07001359 * @param userId the user id to query
Victoria Lease09eeaec2013-02-05 11:34:13 -08001360 */
Maggie2a9409e2018-03-21 11:47:28 -07001361 private boolean isAllowedByUserSettingsLockedForUser(String provider, int userId) {
1362 if (mEnabledProviders.contains(provider)) {
1363 return true;
1364 }
1365 if (mDisabledProviders.contains(provider)) {
1366 return false;
1367 }
1368 return isLocationProviderEnabledForUser(provider, userId);
1369 }
1370
1371
1372 /**
1373 * Returns "true" if access to the specified location provider is allowed by the specified
1374 * user's settings. Access to all location providers is forbidden to non-location-provider
1375 * processes belonging to background users.
1376 *
1377 * @param provider the name of the location provider
1378 * @param uid the requestor's UID
1379 * @param userId the user id to query
1380 */
1381 private boolean isAllowedByUserSettingsLocked(String provider, int uid, int userId) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001382 if (!isCurrentProfile(UserHandle.getUserId(uid)) && !isUidALocationProvider(uid)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08001383 return false;
1384 }
Maggie2a9409e2018-03-21 11:47:28 -07001385 return isAllowedByUserSettingsLockedForUser(provider, userId);
Victoria Lease09eeaec2013-02-05 11:34:13 -08001386 }
1387
1388 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001389 * Returns the permission string associated with the specified resolution level.
1390 *
1391 * @param resolutionLevel the resolution level
1392 * @return the permission string
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001393 */
Victoria Lease37425c32012-10-16 16:08:48 -07001394 private String getResolutionPermission(int resolutionLevel) {
1395 switch (resolutionLevel) {
1396 case RESOLUTION_LEVEL_FINE:
1397 return android.Manifest.permission.ACCESS_FINE_LOCATION;
1398 case RESOLUTION_LEVEL_COARSE:
1399 return android.Manifest.permission.ACCESS_COARSE_LOCATION;
1400 default:
1401 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 }
Victoria Leaseda479c52012-10-15 15:24:16 -07001403 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001404
Victoria Leaseda479c52012-10-15 15:24:16 -07001405 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001406 * Returns the resolution level allowed to the given PID/UID pair.
1407 *
1408 * @param pid the PID
1409 * @param uid the UID
1410 * @return resolution level allowed to the pid/uid pair
Victoria Leaseda479c52012-10-15 15:24:16 -07001411 */
Victoria Lease37425c32012-10-16 16:08:48 -07001412 private int getAllowedResolutionLevel(int pid, int uid) {
1413 if (mContext.checkPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
Maggieaa080f92018-01-04 15:35:11 -08001414 pid, uid) == PERMISSION_GRANTED) {
Victoria Lease37425c32012-10-16 16:08:48 -07001415 return RESOLUTION_LEVEL_FINE;
1416 } else if (mContext.checkPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION,
Maggieaa080f92018-01-04 15:35:11 -08001417 pid, uid) == PERMISSION_GRANTED) {
Victoria Lease37425c32012-10-16 16:08:48 -07001418 return RESOLUTION_LEVEL_COARSE;
1419 } else {
1420 return RESOLUTION_LEVEL_NONE;
Victoria Leaseda479c52012-10-15 15:24:16 -07001421 }
Victoria Lease4fab68b2012-09-13 13:20:59 -07001422 }
1423
1424 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001425 * Returns the resolution level allowed to the caller
1426 *
1427 * @return resolution level allowed to caller
Victoria Lease4fab68b2012-09-13 13:20:59 -07001428 */
Victoria Lease37425c32012-10-16 16:08:48 -07001429 private int getCallerAllowedResolutionLevel() {
1430 return getAllowedResolutionLevel(Binder.getCallingPid(), Binder.getCallingUid());
1431 }
1432
1433 /**
1434 * Throw SecurityException if specified resolution level is insufficient to use geofences.
1435 *
1436 * @param allowedResolutionLevel resolution level allowed to caller
1437 */
1438 private void checkResolutionLevelIsSufficientForGeofenceUse(int allowedResolutionLevel) {
1439 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
Victoria Lease4fab68b2012-09-13 13:20:59 -07001440 throw new SecurityException("Geofence usage requires ACCESS_FINE_LOCATION permission");
1441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 }
1443
Victoria Lease37425c32012-10-16 16:08:48 -07001444 /**
1445 * Return the minimum resolution level required to use the specified location provider.
1446 *
1447 * @param provider the name of the location provider
1448 * @return minimum resolution level required for provider
1449 */
1450 private int getMinimumResolutionLevelForProviderUse(String provider) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001451 if (LocationManager.GPS_PROVIDER.equals(provider) ||
1452 LocationManager.PASSIVE_PROVIDER.equals(provider)) {
1453 // gps and passive providers require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001454 return RESOLUTION_LEVEL_FINE;
Victoria Lease8dbb6342012-09-21 16:55:53 -07001455 } else if (LocationManager.NETWORK_PROVIDER.equals(provider) ||
1456 LocationManager.FUSED_PROVIDER.equals(provider)) {
1457 // network and fused providers are ok with COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001458 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001459 } else {
1460 // mock providers
1461 LocationProviderInterface lp = mMockProviders.get(provider);
1462 if (lp != null) {
1463 ProviderProperties properties = lp.getProperties();
1464 if (properties != null) {
1465 if (properties.mRequiresSatellite) {
1466 // provider requiring satellites require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001467 return RESOLUTION_LEVEL_FINE;
Laurent Tu941221c2012-10-04 14:21:52 -07001468 } else if (properties.mRequiresNetwork || properties.mRequiresCell) {
1469 // provider requiring network and or cell require COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001470 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001471 }
1472 }
1473 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001474 }
Victoria Lease37425c32012-10-16 16:08:48 -07001475 return RESOLUTION_LEVEL_FINE; // if in doubt, require FINE
Victoria Leaseda479c52012-10-15 15:24:16 -07001476 }
1477
Victoria Lease37425c32012-10-16 16:08:48 -07001478 /**
1479 * Throw SecurityException if specified resolution level is insufficient to use the named
1480 * location provider.
1481 *
1482 * @param allowedResolutionLevel resolution level allowed to caller
gomo48f1a642017-11-10 20:35:46 -08001483 * @param providerName the name of the location provider
Victoria Lease37425c32012-10-16 16:08:48 -07001484 */
1485 private void checkResolutionLevelIsSufficientForProviderUse(int allowedResolutionLevel,
1486 String providerName) {
1487 int requiredResolutionLevel = getMinimumResolutionLevelForProviderUse(providerName);
1488 if (allowedResolutionLevel < requiredResolutionLevel) {
1489 switch (requiredResolutionLevel) {
1490 case RESOLUTION_LEVEL_FINE:
1491 throw new SecurityException("\"" + providerName + "\" location provider " +
1492 "requires ACCESS_FINE_LOCATION permission.");
1493 case RESOLUTION_LEVEL_COARSE:
1494 throw new SecurityException("\"" + providerName + "\" location provider " +
1495 "requires ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission.");
1496 default:
1497 throw new SecurityException("Insufficient permission for \"" + providerName +
1498 "\" location provider.");
Victoria Leaseda479c52012-10-15 15:24:16 -07001499 }
1500 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001501 }
1502
David Christie82edc9b2013-07-19 11:31:42 -07001503 /**
1504 * Throw SecurityException if WorkSource use is not allowed (i.e. can't blame other packages
1505 * for battery).
1506 */
David Christie40e57822013-07-30 11:36:48 -07001507 private void checkDeviceStatsAllowed() {
David Christie82edc9b2013-07-19 11:31:42 -07001508 mContext.enforceCallingOrSelfPermission(
1509 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
1510 }
1511
David Christie40e57822013-07-30 11:36:48 -07001512 private void checkUpdateAppOpsAllowed() {
1513 mContext.enforceCallingOrSelfPermission(
1514 android.Manifest.permission.UPDATE_APP_OPS_STATS, null);
1515 }
1516
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001517 public static int resolutionLevelToOp(int allowedResolutionLevel) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001518 if (allowedResolutionLevel != RESOLUTION_LEVEL_NONE) {
1519 if (allowedResolutionLevel == RESOLUTION_LEVEL_COARSE) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001520 return AppOpsManager.OP_COARSE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001521 } else {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001522 return AppOpsManager.OP_FINE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001523 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001524 }
1525 return -1;
1526 }
1527
David Christieb870dbf2015-06-22 12:42:53 -07001528 boolean reportLocationAccessNoThrow(
1529 int pid, int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001530 int op = resolutionLevelToOp(allowedResolutionLevel);
1531 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001532 if (mAppOps.noteOpNoThrow(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1533 return false;
1534 }
1535 }
David Christieb870dbf2015-06-22 12:42:53 -07001536
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001537 return getAllowedResolutionLevel(pid, uid) >= allowedResolutionLevel;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001538 }
1539
David Christieb870dbf2015-06-22 12:42:53 -07001540 boolean checkLocationAccess(int pid, int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001541 int op = resolutionLevelToOp(allowedResolutionLevel);
1542 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001543 if (mAppOps.checkOp(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1544 return false;
1545 }
1546 }
David Christieb870dbf2015-06-22 12:42:53 -07001547
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001548 return getAllowedResolutionLevel(pid, uid) >= allowedResolutionLevel;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001549 }
1550
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001551 /**
Maggie91e630c2018-01-24 17:31:46 -08001552 * Returns all providers by name, including passive and the ones that are not permitted to
1553 * be accessed by the calling activity or are currently disabled, but excluding fused.
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001554 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001555 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 public List<String> getAllProviders() {
Maggie91e630c2018-01-24 17:31:46 -08001557 ArrayList<String> out;
1558 synchronized (mLock) {
1559 out = new ArrayList<>(mProviders.size());
1560 for (LocationProviderInterface provider : mProviders) {
1561 String name = provider.getName();
1562 if (LocationManager.FUSED_PROVIDER.equals(name)) {
1563 continue;
1564 }
1565 out.add(name);
1566 }
1567 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001568 if (D) Log.d(TAG, "getAllProviders()=" + out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569 return out;
1570 }
1571
Mike Lockwood03ca2162010-04-01 08:10:09 -07001572 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001573 * Return all providers by name, that match criteria and are optionally
1574 * enabled.
1575 * Can return passive provider, but never returns fused provider.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001576 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001577 @Override
1578 public List<String> getProviders(Criteria criteria, boolean enabledOnly) {
Victoria Lease37425c32012-10-16 16:08:48 -07001579 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001580 ArrayList<String> out;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001581 int uid = Binder.getCallingUid();
Victoria Lease269518e2012-10-29 08:25:39 -07001582 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001583 try {
1584 synchronized (mLock) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001585 out = new ArrayList<>(mProviders.size());
Victoria Leaseb711d572012-10-02 13:14:11 -07001586 for (LocationProviderInterface provider : mProviders) {
1587 String name = provider.getName();
1588 if (LocationManager.FUSED_PROVIDER.equals(name)) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001589 continue;
1590 }
Victoria Lease37425c32012-10-16 16:08:48 -07001591 if (allowedResolutionLevel >= getMinimumResolutionLevelForProviderUse(name)) {
Maggie2a9409e2018-03-21 11:47:28 -07001592 if (enabledOnly
1593 && !isAllowedByUserSettingsLocked(name, uid, mCurrentUserId)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001594 continue;
1595 }
1596 if (criteria != null && !LocationProvider.propertiesMeetCriteria(
1597 name, provider.getProperties(), criteria)) {
1598 continue;
1599 }
1600 out.add(name);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001601 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001602 }
Mike Lockwood03ca2162010-04-01 08:10:09 -07001603 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001604 } finally {
1605 Binder.restoreCallingIdentity(identity);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001606 }
1607
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001608 if (D) Log.d(TAG, "getProviders()=" + out);
1609 return out;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001610 }
1611
1612 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001613 * Return the name of the best provider given a Criteria object.
1614 * This method has been deprecated from the public API,
Victoria Lease8dbb6342012-09-21 16:55:53 -07001615 * and the whole LocationProvider (including #meetsCriteria)
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001616 * has been deprecated as well. So this method now uses
1617 * some simplified logic.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001618 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001619 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001620 public String getBestProvider(Criteria criteria, boolean enabledOnly) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001621 String result = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001622
1623 List<String> providers = getProviders(criteria, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001624 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001625 result = pickBest(providers);
1626 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1627 return result;
1628 }
1629 providers = getProviders(null, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001630 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001631 result = pickBest(providers);
1632 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1633 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001634 }
1635
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001636 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001637 return null;
1638 }
1639
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001640 private String pickBest(List<String> providers) {
Victoria Lease1925e292012-09-24 17:00:18 -07001641 if (providers.contains(LocationManager.GPS_PROVIDER)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001642 return LocationManager.GPS_PROVIDER;
Victoria Lease1925e292012-09-24 17:00:18 -07001643 } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
1644 return LocationManager.NETWORK_PROVIDER;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001645 } else {
1646 return providers.get(0);
1647 }
1648 }
1649
Nick Pellye0fd6932012-07-11 10:26:13 -07001650 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001651 public boolean providerMeetsCriteria(String provider, Criteria criteria) {
1652 LocationProviderInterface p = mProvidersByName.get(provider);
1653 if (p == null) {
1654 throw new IllegalArgumentException("provider=" + provider);
1655 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001656
1657 boolean result = LocationProvider.propertiesMeetCriteria(
1658 p.getName(), p.getProperties(), criteria);
1659 if (D) Log.d(TAG, "providerMeetsCriteria(" + provider + ", " + criteria + ")=" + result);
1660 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001661 }
1662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 private void updateProvidersLocked() {
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001664 boolean changesMade = false;
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001665 for (int i = mProviders.size() - 1; i >= 0; i--) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001666 LocationProviderInterface p = mProviders.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 boolean isEnabled = p.isEnabled();
1668 String name = p.getName();
Victoria Lease09eeaec2013-02-05 11:34:13 -08001669 boolean shouldBeEnabled = isAllowedByCurrentUserSettingsLocked(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 if (isEnabled && !shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001671 updateProviderListenersLocked(name, false);
David Christieb084fef2013-12-18 14:33:57 -08001672 // If any provider has been disabled, clear all last locations for all providers.
1673 // This is to be on the safe side in case a provider has location derived from
1674 // this disabled provider.
1675 mLastLocation.clear();
1676 mLastLocationCoarseInterval.clear();
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001677 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 } else if (!isEnabled && shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001679 updateProviderListenersLocked(name, true);
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001680 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 }
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001682 }
1683 if (changesMade) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001684 mContext.sendBroadcastAsUser(new Intent(LocationManager.PROVIDERS_CHANGED_ACTION),
1685 UserHandle.ALL);
Tom O'Neill40a86c22013-09-03 18:05:13 -07001686 mContext.sendBroadcastAsUser(new Intent(LocationManager.MODE_CHANGED_ACTION),
1687 UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 }
1689 }
1690
Amith Yamasanib27528d2014-06-05 15:02:10 -07001691 private void updateProviderListenersLocked(String provider, boolean enabled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 int listeners = 0;
1693
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001694 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001695 if (p == null) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696
1697 ArrayList<Receiver> deadReceivers = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07001698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1700 if (records != null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001701 for (UpdateRecord record : records) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001702 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mIdentity.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001703 // Sends a notification message to the receiver
1704 if (!record.mReceiver.callProviderEnabledLocked(provider, enabled)) {
1705 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001706 deadReceivers = new ArrayList<>();
Victoria Leaseb711d572012-10-02 13:14:11 -07001707 }
1708 deadReceivers.add(record.mReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001710 listeners++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 }
1713 }
1714
1715 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001716 for (int i = deadReceivers.size() - 1; i >= 0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 removeUpdatesLocked(deadReceivers.get(i));
1718 }
1719 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 if (enabled) {
1722 p.enable();
1723 if (listeners > 0) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001724 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 }
1726 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 p.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 }
1730
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001731 private void applyRequirementsLocked(String provider) {
1732 LocationProviderInterface p = mProvidersByName.get(provider);
1733 if (p == null) return;
1734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001736 WorkSource worksource = new WorkSource();
1737 ProviderRequest providerRequest = new ProviderRequest();
1738
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001739 ContentResolver resolver = mContext.getContentResolver();
1740 long backgroundThrottleInterval = Settings.Global.getLong(
1741 resolver,
1742 Settings.Global.LOCATION_BACKGROUND_THROTTLE_INTERVAL_MS,
1743 DEFAULT_BACKGROUND_THROTTLE_INTERVAL_MS);
gomo48f1a642017-11-10 20:35:46 -08001744 // initialize the low power mode to true and set to false if any of the records requires
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001745
gomo48f1a642017-11-10 20:35:46 -08001746 providerRequest.lowPowerMode = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 if (records != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001748 for (UpdateRecord record : records) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001749 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mIdentity.mUid))) {
David Christieb870dbf2015-06-22 12:42:53 -07001750 if (checkLocationAccess(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001751 record.mReceiver.mIdentity.mPid,
1752 record.mReceiver.mIdentity.mUid,
1753 record.mReceiver.mIdentity.mPackageName,
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001754 record.mReceiver.mAllowedResolutionLevel)) {
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001755 LocationRequest locationRequest = record.mRealRequest;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001756 long interval = locationRequest.getInterval();
1757
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001758 if (!isThrottlingExemptLocked(record.mReceiver.mIdentity)) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001759 if (!record.mIsForegroundUid) {
1760 interval = Math.max(interval, backgroundThrottleInterval);
1761 }
1762 if (interval != locationRequest.getInterval()) {
1763 locationRequest = new LocationRequest(locationRequest);
1764 locationRequest.setInterval(interval);
1765 }
1766 }
1767
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001768 record.mRequest = locationRequest;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001769 providerRequest.locationRequests.add(locationRequest);
gomo48f1a642017-11-10 20:35:46 -08001770 if (!locationRequest.isLowPowerMode()) {
1771 providerRequest.lowPowerMode = false;
1772 }
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001773 if (interval < providerRequest.interval) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001774 providerRequest.reportLocation = true;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001775 providerRequest.interval = interval;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001776 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001777 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001778 }
1779 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001780
1781 if (providerRequest.reportLocation) {
1782 // calculate who to blame for power
1783 // This is somewhat arbitrary. We pick a threshold interval
1784 // that is slightly higher that the minimum interval, and
1785 // spread the blame across all applications with a request
1786 // under that threshold.
1787 long thresholdInterval = (providerRequest.interval + 1000) * 3 / 2;
1788 for (UpdateRecord record : records) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001789 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mIdentity.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001790 LocationRequest locationRequest = record.mRequest;
Svet Ganove998c732016-06-10 00:12:38 -07001791
1792 // Don't assign battery blame for update records whose
1793 // client has no permission to receive location data.
1794 if (!providerRequest.locationRequests.contains(locationRequest)) {
1795 continue;
1796 }
1797
Victoria Leaseb711d572012-10-02 13:14:11 -07001798 if (locationRequest.getInterval() <= thresholdInterval) {
David Christiee55c9682013-08-22 10:10:34 -07001799 if (record.mReceiver.mWorkSource != null
Narayan Kamath32684dd2018-01-08 17:32:51 +00001800 && isValidWorkSource(record.mReceiver.mWorkSource)) {
David Christie82edc9b2013-07-19 11:31:42 -07001801 worksource.add(record.mReceiver.mWorkSource);
1802 } else {
Narayan Kamath32684dd2018-01-08 17:32:51 +00001803 // Assign blame to caller if there's no WorkSource associated with
1804 // the request or if it's invalid.
David Christie82edc9b2013-07-19 11:31:42 -07001805 worksource.add(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001806 record.mReceiver.mIdentity.mUid,
1807 record.mReceiver.mIdentity.mPackageName);
David Christie82edc9b2013-07-19 11:31:42 -07001808 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001809 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001810 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001811 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 }
1813 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001814
1815 if (D) Log.d(TAG, "provider request: " + provider + " " + providerRequest);
1816 p.setRequest(providerRequest, worksource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 }
1818
Narayan Kamath32684dd2018-01-08 17:32:51 +00001819 /**
1820 * Whether a given {@code WorkSource} associated with a Location request is valid.
1821 */
1822 private static boolean isValidWorkSource(WorkSource workSource) {
1823 if (workSource.size() > 0) {
1824 // If the WorkSource has one or more non-chained UIDs, make sure they're accompanied
1825 // by tags.
1826 return workSource.getName(0) != null;
1827 } else {
1828 // For now, make sure callers have supplied an attribution tag for use with
1829 // AppOpsManager. This might be relaxed in the future.
1830 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
1831 return workChains != null && !workChains.isEmpty() &&
1832 workChains.get(0).getAttributionTag() != null;
1833 }
1834 }
1835
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001836 @Override
1837 public String[] getBackgroundThrottlingWhitelist() {
1838 synchronized (mLock) {
1839 return mBackgroundThrottlePackageWhitelist.toArray(
gomo48f1a642017-11-10 20:35:46 -08001840 new String[mBackgroundThrottlePackageWhitelist.size()]);
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001841 }
1842 }
1843
1844 private void updateBackgroundThrottlingWhitelistLocked() {
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001845 String setting = Settings.Global.getString(
gomo48f1a642017-11-10 20:35:46 -08001846 mContext.getContentResolver(),
1847 Settings.Global.LOCATION_BACKGROUND_THROTTLE_PACKAGE_WHITELIST);
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001848 if (setting == null) {
1849 setting = "";
1850 }
1851
1852 mBackgroundThrottlePackageWhitelist.clear();
1853 mBackgroundThrottlePackageWhitelist.addAll(
gomo48f1a642017-11-10 20:35:46 -08001854 SystemConfig.getInstance().getAllowUnthrottledLocation());
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001855 mBackgroundThrottlePackageWhitelist.addAll(
gomo48f1a642017-11-10 20:35:46 -08001856 Arrays.asList(setting.split(",")));
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001857 }
1858
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001859 private boolean isThrottlingExemptLocked(Identity identity) {
1860 if (identity.mUid == Process.SYSTEM_UID) {
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001861 return true;
1862 }
1863
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001864 if (mBackgroundThrottlePackageWhitelist.contains(identity.mPackageName)) {
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001865 return true;
1866 }
1867
1868 for (LocationProviderProxy provider : mProxyProviders) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001869 if (identity.mPackageName.equals(provider.getConnectedPackageName())) {
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001870 return true;
1871 }
1872 }
1873
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001874 return false;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001875 }
1876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 private class UpdateRecord {
1878 final String mProvider;
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001879 final LocationRequest mRealRequest; // original request from client
1880 LocationRequest mRequest; // possibly throttled version of the request
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 final Receiver mReceiver;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001882 boolean mIsForegroundUid;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001883 Location mLastFixBroadcast;
1884 long mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885
1886 /**
1887 * Note: must be constructed with lock held.
1888 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001889 UpdateRecord(String provider, LocationRequest request, Receiver receiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 mProvider = provider;
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001891 mRealRequest = request;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001892 mRequest = request;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 mReceiver = receiver;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001894 mIsForegroundUid = isImportanceForeground(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001895 mActivityManager.getPackageImportance(mReceiver.mIdentity.mPackageName));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896
1897 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1898 if (records == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001899 records = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 mRecordsByProvider.put(provider, records);
1901 }
1902 if (!records.contains(this)) {
1903 records.add(this);
1904 }
David Christie2ff96af2014-01-30 16:09:37 -08001905
1906 // Update statistics for historical location requests by package/provider
1907 mRequestStatistics.startRequesting(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001908 mReceiver.mIdentity.mPackageName, provider, request.getInterval());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 }
1910
1911 /**
David Christie2ff96af2014-01-30 16:09:37 -08001912 * Method to be called when a record will no longer be used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001914 void disposeLocked(boolean removeReceiver) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001915 mRequestStatistics.stopRequesting(mReceiver.mIdentity.mPackageName, mProvider);
David Christie2ff96af2014-01-30 16:09:37 -08001916
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001917 // remove from mRecordsByProvider
1918 ArrayList<UpdateRecord> globalRecords = mRecordsByProvider.get(this.mProvider);
1919 if (globalRecords != null) {
1920 globalRecords.remove(this);
1921 }
1922
1923 if (!removeReceiver) return; // the caller will handle the rest
1924
1925 // remove from Receiver#mUpdateRecords
1926 HashMap<String, UpdateRecord> receiverRecords = mReceiver.mUpdateRecords;
1927 if (receiverRecords != null) {
1928 receiverRecords.remove(this.mProvider);
1929
1930 // and also remove the Receiver if it has no more update records
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001931 if (receiverRecords.size() == 0) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001932 removeUpdatesLocked(mReceiver);
1933 }
Mike Lockwood3a76fd62009-09-01 07:26:56 -04001934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 }
1936
1937 @Override
1938 public String toString() {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001939 return "UpdateRecord[" + mProvider + " " + mReceiver.mIdentity.mPackageName
gomo48f1a642017-11-10 20:35:46 -08001940 + "(" + mReceiver.mIdentity.mUid + (mIsForegroundUid ? " foreground"
1941 : " background")
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001942 + ")" + " " + mRealRequest + "]";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944 }
1945
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001946 private Receiver getReceiverLocked(ILocationListener listener, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -07001947 String packageName, WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001948 IBinder binder = listener.asBinder();
1949 Receiver receiver = mReceivers.get(binder);
1950 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07001951 receiver = new Receiver(listener, null, pid, uid, packageName, workSource,
1952 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001953 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001954 receiver.getListener().asBinder().linkToDeath(receiver, 0);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001955 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001956 Slog.e(TAG, "linkToDeath failed:", e);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001957 return null;
1958 }
Wen Jingcb3ab222014-03-27 13:42:59 +08001959 mReceivers.put(binder, receiver);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001960 }
1961 return receiver;
1962 }
1963
David Christie82edc9b2013-07-19 11:31:42 -07001964 private Receiver getReceiverLocked(PendingIntent intent, int pid, int uid, String packageName,
David Christie40e57822013-07-30 11:36:48 -07001965 WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001966 Receiver receiver = mReceivers.get(intent);
1967 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07001968 receiver = new Receiver(null, intent, pid, uid, packageName, workSource,
1969 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001970 mReceivers.put(intent, receiver);
1971 }
1972 return receiver;
1973 }
1974
Victoria Lease37425c32012-10-16 16:08:48 -07001975 /**
1976 * Creates a LocationRequest based upon the supplied LocationRequest that to meets resolution
1977 * and consistency requirements.
1978 *
1979 * @param request the LocationRequest from which to create a sanitized version
Victoria Lease37425c32012-10-16 16:08:48 -07001980 * @return a version of request that meets the given resolution and consistency requirements
1981 * @hide
1982 */
gomo48f1a642017-11-10 20:35:46 -08001983 private LocationRequest createSanitizedRequest(LocationRequest request, int resolutionLevel,
1984 boolean callerHasLocationHardwarePermission) {
Victoria Lease37425c32012-10-16 16:08:48 -07001985 LocationRequest sanitizedRequest = new LocationRequest(request);
gomo48f1a642017-11-10 20:35:46 -08001986 if (!callerHasLocationHardwarePermission) {
1987 // allow setting low power mode only for callers with location hardware permission
1988 sanitizedRequest.setLowPowerMode(false);
1989 }
Victoria Lease37425c32012-10-16 16:08:48 -07001990 if (resolutionLevel < RESOLUTION_LEVEL_FINE) {
1991 switch (sanitizedRequest.getQuality()) {
Victoria Lease09016ab2012-09-16 12:33:15 -07001992 case LocationRequest.ACCURACY_FINE:
Victoria Lease37425c32012-10-16 16:08:48 -07001993 sanitizedRequest.setQuality(LocationRequest.ACCURACY_BLOCK);
Victoria Lease09016ab2012-09-16 12:33:15 -07001994 break;
1995 case LocationRequest.POWER_HIGH:
Victoria Lease37425c32012-10-16 16:08:48 -07001996 sanitizedRequest.setQuality(LocationRequest.POWER_LOW);
Victoria Lease09016ab2012-09-16 12:33:15 -07001997 break;
1998 }
1999 // throttle
Victoria Lease37425c32012-10-16 16:08:48 -07002000 if (sanitizedRequest.getInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
2001 sanitizedRequest.setInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07002002 }
Victoria Lease37425c32012-10-16 16:08:48 -07002003 if (sanitizedRequest.getFastestInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
2004 sanitizedRequest.setFastestInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07002005 }
Nick Pelly74fa7ea2012-08-13 19:36:38 -07002006 }
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002007 // make getFastestInterval() the minimum of interval and fastest interval
Victoria Lease37425c32012-10-16 16:08:48 -07002008 if (sanitizedRequest.getFastestInterval() > sanitizedRequest.getInterval()) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002009 request.setFastestInterval(request.getInterval());
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002010 }
Victoria Lease37425c32012-10-16 16:08:48 -07002011 return sanitizedRequest;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002012 }
2013
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002014 private void checkPackageName(String packageName) {
Nick Pellye0fd6932012-07-11 10:26:13 -07002015 if (packageName == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002016 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07002017 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002018 int uid = Binder.getCallingUid();
Nick Pellye0fd6932012-07-11 10:26:13 -07002019 String[] packages = mPackageManager.getPackagesForUid(uid);
2020 if (packages == null) {
2021 throw new SecurityException("invalid UID " + uid);
2022 }
2023 for (String pkg : packages) {
2024 if (packageName.equals(pkg)) return;
2025 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002026 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07002027 }
2028
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002029 private void checkPendingIntent(PendingIntent intent) {
2030 if (intent == null) {
2031 throw new IllegalArgumentException("invalid pending intent: " + intent);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002032 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002033 }
2034
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002035 private Receiver checkListenerOrIntentLocked(ILocationListener listener, PendingIntent intent,
David Christie40e57822013-07-30 11:36:48 -07002036 int pid, int uid, String packageName, WorkSource workSource, boolean hideFromAppOps) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002037 if (intent == null && listener == null) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002038 throw new IllegalArgumentException("need either listener or intent");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002039 } else if (intent != null && listener != null) {
2040 throw new IllegalArgumentException("cannot register both listener and intent");
2041 } else if (intent != null) {
2042 checkPendingIntent(intent);
David Christie40e57822013-07-30 11:36:48 -07002043 return getReceiverLocked(intent, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002044 } else {
David Christie40e57822013-07-30 11:36:48 -07002045 return getReceiverLocked(listener, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002046 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002047 }
2048
Nick Pellye0fd6932012-07-11 10:26:13 -07002049 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002050 public void requestLocationUpdates(LocationRequest request, ILocationListener listener,
2051 PendingIntent intent, String packageName) {
2052 if (request == null) request = DEFAULT_LOCATION_REQUEST;
2053 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002054 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
2055 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
2056 request.getProvider());
David Christie82edc9b2013-07-19 11:31:42 -07002057 WorkSource workSource = request.getWorkSource();
Narayan Kamath32684dd2018-01-08 17:32:51 +00002058 if (workSource != null && !workSource.isEmpty()) {
David Christie40e57822013-07-30 11:36:48 -07002059 checkDeviceStatsAllowed();
2060 }
2061 boolean hideFromAppOps = request.getHideFromAppOps();
2062 if (hideFromAppOps) {
2063 checkUpdateAppOpsAllowed();
David Christie82edc9b2013-07-19 11:31:42 -07002064 }
gomo48f1a642017-11-10 20:35:46 -08002065 boolean callerHasLocationHardwarePermission =
2066 mContext.checkCallingPermission(android.Manifest.permission.LOCATION_HARDWARE)
Maggieaa080f92018-01-04 15:35:11 -08002067 == PERMISSION_GRANTED;
gomo48f1a642017-11-10 20:35:46 -08002068 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel,
2069 callerHasLocationHardwarePermission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002071 final int pid = Binder.getCallingPid();
2072 final int uid = Binder.getCallingUid();
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002073 // providers may use public location API's, need to clear identity
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002074 long identity = Binder.clearCallingIdentity();
2075 try {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002076 // We don't check for MODE_IGNORED here; we will do that when we go to deliver
2077 // a location.
David Christieb870dbf2015-06-22 12:42:53 -07002078 checkLocationAccess(pid, uid, packageName, allowedResolutionLevel);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002079
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002080 synchronized (mLock) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002081 Receiver recevier = checkListenerOrIntentLocked(listener, intent, pid, uid,
David Christie40e57822013-07-30 11:36:48 -07002082 packageName, workSource, hideFromAppOps);
Victoria Lease37425c32012-10-16 16:08:48 -07002083 requestLocationUpdatesLocked(sanitizedRequest, recevier, pid, uid, packageName);
Mike Lockwood2d4d1bf2010-10-18 17:06:26 -04002084 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085 } finally {
2086 Binder.restoreCallingIdentity(identity);
2087 }
2088 }
2089
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002090 private void requestLocationUpdatesLocked(LocationRequest request, Receiver receiver,
2091 int pid, int uid, String packageName) {
2092 // Figure out the provider. Either its explicitly request (legacy use cases), or
2093 // use the fused provider
2094 if (request == null) request = DEFAULT_LOCATION_REQUEST;
2095 String name = request.getProvider();
Victoria Lease09016ab2012-09-16 12:33:15 -07002096 if (name == null) {
2097 throw new IllegalArgumentException("provider name must not be null");
2098 }
Zhentao Sunc5fc9982013-04-17 17:47:53 -07002099
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002100 LocationProviderInterface provider = mProvidersByName.get(name);
2101 if (provider == null) {
Victoria Leaseb30f3832013-10-13 12:15:40 -07002102 throw new IllegalArgumentException("provider doesn't exist: " + name);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002103 }
2104
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002105 UpdateRecord record = new UpdateRecord(name, request, receiver);
gomo48f1a642017-11-10 20:35:46 -08002106 if (D) {
2107 Log.d(TAG, "request " + Integer.toHexString(System.identityHashCode(receiver))
2108 + " " + name + " " + request + " from " + packageName + "(" + uid + " "
2109 + (record.mIsForegroundUid ? "foreground" : "background")
2110 + (isThrottlingExemptLocked(receiver.mIdentity)
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002111 ? " [whitelisted]" : "") + ")");
gomo48f1a642017-11-10 20:35:46 -08002112 }
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002113
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002114 UpdateRecord oldRecord = receiver.mUpdateRecords.put(name, record);
2115 if (oldRecord != null) {
2116 oldRecord.disposeLocked(false);
2117 }
2118
Maggie2a9409e2018-03-21 11:47:28 -07002119 boolean isProviderEnabled = isAllowedByUserSettingsLocked(name, uid, mCurrentUserId);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002120 if (isProviderEnabled) {
2121 applyRequirementsLocked(name);
2122 } else {
2123 // Notify the listener that updates are currently disabled
2124 receiver.callProviderEnabledLocked(name, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002125 }
David Christie0b837452013-07-29 16:02:13 -07002126 // Update the monitoring here just in case multiple location requests were added to the
2127 // same receiver (this request may be high power and the initial might not have been).
2128 receiver.updateMonitoring(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002129 }
2130
Nick Pellye0fd6932012-07-11 10:26:13 -07002131 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002132 public void removeUpdates(ILocationListener listener, PendingIntent intent,
2133 String packageName) {
2134 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002135
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002136 final int pid = Binder.getCallingPid();
2137 final int uid = Binder.getCallingUid();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002138
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002139 synchronized (mLock) {
David Christie82edc9b2013-07-19 11:31:42 -07002140 WorkSource workSource = null;
David Christie40e57822013-07-30 11:36:48 -07002141 boolean hideFromAppOps = false;
2142 Receiver receiver = checkListenerOrIntentLocked(listener, intent, pid, uid,
2143 packageName, workSource, hideFromAppOps);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002144
2145 // providers may use public location API's, need to clear identity
2146 long identity = Binder.clearCallingIdentity();
2147 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002148 removeUpdatesLocked(receiver);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002149 } finally {
2150 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002151 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002152 }
2153 }
2154
2155 private void removeUpdatesLocked(Receiver receiver) {
Dianne Hackborn7ff30112012-11-08 11:12:09 -08002156 if (D) Log.i(TAG, "remove " + Integer.toHexString(System.identityHashCode(receiver)));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002157
2158 if (mReceivers.remove(receiver.mKey) != null && receiver.isListener()) {
2159 receiver.getListener().asBinder().unlinkToDeath(receiver, 0);
2160 synchronized (receiver) {
Victoria Lease0aa28602013-05-29 15:28:26 -07002161 receiver.clearPendingBroadcastsLocked();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002162 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002163 }
2164
Dianne Hackborn1304f4a2013-07-09 18:17:27 -07002165 receiver.updateMonitoring(false);
2166
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002167 // Record which providers were associated with this listener
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002168 HashSet<String> providers = new HashSet<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002169 HashMap<String, UpdateRecord> oldRecords = receiver.mUpdateRecords;
2170 if (oldRecords != null) {
2171 // Call dispose() on the obsolete update records.
2172 for (UpdateRecord record : oldRecords.values()) {
David Christie2ff96af2014-01-30 16:09:37 -08002173 // Update statistics for historical location requests by package/provider
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002174 record.disposeLocked(false);
2175 }
2176 // Accumulate providers
2177 providers.addAll(oldRecords.keySet());
2178 }
2179
2180 // update provider
2181 for (String provider : providers) {
2182 // If provider is already disabled, don't need to do anything
Victoria Lease09eeaec2013-02-05 11:34:13 -08002183 if (!isAllowedByCurrentUserSettingsLocked(provider)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002184 continue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002185 }
2186
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002187 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002188 }
2189 }
2190
Dianne Hackbornc2293022013-02-06 23:14:49 -08002191 private void applyAllProviderRequirementsLocked() {
2192 for (LocationProviderInterface p : mProviders) {
2193 // If provider is already disabled, don't need to do anything
Dianne Hackborn64d41d72013-02-07 00:33:31 -08002194 if (!isAllowedByCurrentUserSettingsLocked(p.getName())) {
Dianne Hackbornc2293022013-02-06 23:14:49 -08002195 continue;
2196 }
2197
2198 applyRequirementsLocked(p.getName());
2199 }
2200 }
2201
Nick Pellye0fd6932012-07-11 10:26:13 -07002202 @Override
Nick Pelly4035f5a2012-08-17 14:43:49 -07002203 public Location getLastLocation(LocationRequest request, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002204 if (D) Log.d(TAG, "getLastLocation: " + request);
2205 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07002206 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly4035f5a2012-08-17 14:43:49 -07002207 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002208 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
2209 request.getProvider());
2210 // no need to sanitize this request, as only the provider name is used
Nick Pelly4035f5a2012-08-17 14:43:49 -07002211
David Christieb870dbf2015-06-22 12:42:53 -07002212 final int pid = Binder.getCallingPid();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002213 final int uid = Binder.getCallingUid();
2214 final long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07002215 try {
2216 if (mBlacklist.isBlacklisted(packageName)) {
gomo48f1a642017-11-10 20:35:46 -08002217 if (D) {
2218 Log.d(TAG, "not returning last loc for blacklisted app: " +
2219 packageName);
2220 }
Victoria Lease09016ab2012-09-16 12:33:15 -07002221 return null;
2222 }
Victoria Leaseb711d572012-10-02 13:14:11 -07002223
David Christieb870dbf2015-06-22 12:42:53 -07002224 if (!reportLocationAccessNoThrow(pid, uid, packageName, allowedResolutionLevel)) {
gomo48f1a642017-11-10 20:35:46 -08002225 if (D) {
2226 Log.d(TAG, "not returning last loc for no op app: " +
2227 packageName);
2228 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002229 return null;
2230 }
2231
Victoria Leaseb711d572012-10-02 13:14:11 -07002232 synchronized (mLock) {
2233 // Figure out the provider. Either its explicitly request (deprecated API's),
2234 // or use the fused provider
2235 String name = request.getProvider();
2236 if (name == null) name = LocationManager.FUSED_PROVIDER;
2237 LocationProviderInterface provider = mProvidersByName.get(name);
2238 if (provider == null) return null;
2239
Maggie2a9409e2018-03-21 11:47:28 -07002240 if (!isAllowedByUserSettingsLocked(name, uid, mCurrentUserId)) return null;
Victoria Leaseb711d572012-10-02 13:14:11 -07002241
David Christie1b9b7b12013-04-15 15:31:11 -07002242 Location location;
2243 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
2244 // Make sure that an app with coarse permissions can't get frequent location
2245 // updates by calling LocationManager.getLastKnownLocation repeatedly.
2246 location = mLastLocationCoarseInterval.get(name);
2247 } else {
2248 location = mLastLocation.get(name);
2249 }
Victoria Leaseb711d572012-10-02 13:14:11 -07002250 if (location == null) {
2251 return null;
2252 }
Victoria Lease37425c32012-10-16 16:08:48 -07002253 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
gomo48f1a642017-11-10 20:35:46 -08002254 Location noGPSLocation = location.getExtraLocation(
2255 Location.EXTRA_NO_GPS_LOCATION);
Victoria Leaseb711d572012-10-02 13:14:11 -07002256 if (noGPSLocation != null) {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08002257 return new Location(mLocationFudger.getOrCreate(noGPSLocation));
Victoria Leaseb711d572012-10-02 13:14:11 -07002258 }
Victoria Lease37425c32012-10-16 16:08:48 -07002259 } else {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08002260 return new Location(location);
Victoria Lease09016ab2012-09-16 12:33:15 -07002261 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002262 }
Victoria Leaseb711d572012-10-02 13:14:11 -07002263 return null;
2264 } finally {
2265 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002266 }
2267 }
2268
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002269 /**
2270 * Provides an interface to inject and set the last location if location is not available
2271 * currently.
2272 *
2273 * This helps in cases where the product (Cars for example) has saved the last known location
2274 * before powering off. This interface lets the client inject the saved location while the GPS
2275 * chipset is getting its first fix, there by improving user experience.
2276 *
2277 * @param location - Location object to inject
2278 * @return true if update was successful, false if not
2279 */
2280 @Override
2281 public boolean injectLocation(Location location) {
2282 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
2283 "Location Hardware permission not granted to inject location");
2284 mContext.enforceCallingPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
2285 "Access Fine Location permission not granted to inject Location");
2286
2287 if (location == null) {
2288 if (D) {
2289 Log.d(TAG, "injectLocation(): called with null location");
2290 }
2291 return false;
2292 }
2293 LocationProviderInterface p = null;
2294 String provider = location.getProvider();
2295 if (provider != null) {
2296 p = mProvidersByName.get(provider);
2297 }
2298 if (p == null) {
2299 if (D) {
2300 Log.d(TAG, "injectLocation(): unknown provider");
2301 }
2302 return false;
2303 }
2304 synchronized (mLock) {
2305 if (!isAllowedByCurrentUserSettingsLocked(provider)) {
2306 if (D) {
2307 Log.d(TAG, "Location disabled in Settings for current user:" + mCurrentUserId);
2308 }
2309 return false;
2310 } else {
2311 // NOTE: If last location is already available, location is not injected. If
2312 // provider's normal source (like a GPS chipset) have already provided an output,
2313 // there is no need to inject this location.
2314 if (mLastLocation.get(provider) == null) {
2315 updateLastLocationLocked(location, provider);
2316 } else {
2317 if (D) {
2318 Log.d(TAG, "injectLocation(): Location exists. Not updating");
2319 }
2320 return false;
2321 }
2322 }
2323 }
2324 return true;
2325 }
2326
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002327 @Override
2328 public void requestGeofence(LocationRequest request, Geofence geofence, PendingIntent intent,
2329 String packageName) {
2330 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07002331 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
2332 checkResolutionLevelIsSufficientForGeofenceUse(allowedResolutionLevel);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002333 checkPendingIntent(intent);
2334 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002335 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
2336 request.getProvider());
gomo48f1a642017-11-10 20:35:46 -08002337 // Require that caller can manage given document
2338 boolean callerHasLocationHardwarePermission =
2339 mContext.checkCallingPermission(android.Manifest.permission.LOCATION_HARDWARE)
Maggieaa080f92018-01-04 15:35:11 -08002340 == PERMISSION_GRANTED;
gomo48f1a642017-11-10 20:35:46 -08002341 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel,
2342 callerHasLocationHardwarePermission);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002343
Victoria Lease37425c32012-10-16 16:08:48 -07002344 if (D) Log.d(TAG, "requestGeofence: " + sanitizedRequest + " " + geofence + " " + intent);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002345
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002346 // geo-fence manager uses the public location API, need to clear identity
2347 int uid = Binder.getCallingUid();
Xiaohui Chena4490622015-09-22 15:29:31 -07002348 // TODO: http://b/23822629
2349 if (UserHandle.getUserId(uid) != UserHandle.USER_SYSTEM) {
Victoria Lease56e675b2012-11-05 19:25:06 -08002350 // temporary measure until geofences work for secondary users
2351 Log.w(TAG, "proximity alerts are currently available only to the primary user");
2352 return;
2353 }
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002354 long identity = Binder.clearCallingIdentity();
2355 try {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002356 mGeofenceManager.addFence(sanitizedRequest, geofence, intent, allowedResolutionLevel,
2357 uid, packageName);
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002358 } finally {
2359 Binder.restoreCallingIdentity(identity);
2360 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002361 }
2362
2363 @Override
2364 public void removeGeofence(Geofence geofence, PendingIntent intent, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002365 checkPendingIntent(intent);
2366 checkPackageName(packageName);
2367
2368 if (D) Log.d(TAG, "removeGeofence: " + geofence + " " + intent);
2369
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002370 // geo-fence manager uses the public location API, need to clear identity
2371 long identity = Binder.clearCallingIdentity();
2372 try {
2373 mGeofenceManager.removeFence(geofence, intent);
2374 } finally {
2375 Binder.restoreCallingIdentity(identity);
2376 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002377 }
2378
2379
2380 @Override
Lifu Tang30f95a72016-01-07 23:20:38 -08002381 public boolean registerGnssStatusCallback(IGnssStatusListener callback, String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002382 if (!hasGnssPermissions(packageName) || mGnssStatusProvider == null) {
Takayuki Hoshib254ab6a2014-10-23 16:46:02 +09002383 return false;
2384 }
2385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002386 try {
Lifu Tang30f95a72016-01-07 23:20:38 -08002387 mGnssStatusProvider.registerGnssStatusCallback(callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002388 } catch (RemoteException e) {
Lifu Tang30f95a72016-01-07 23:20:38 -08002389 Slog.e(TAG, "mGpsStatusProvider.registerGnssStatusCallback failed", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390 return false;
2391 }
2392 return true;
2393 }
2394
Nick Pellye0fd6932012-07-11 10:26:13 -07002395 @Override
Lifu Tang30f95a72016-01-07 23:20:38 -08002396 public void unregisterGnssStatusCallback(IGnssStatusListener callback) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002397 synchronized (mLock) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002398 try {
Lifu Tang30f95a72016-01-07 23:20:38 -08002399 mGnssStatusProvider.unregisterGnssStatusCallback(callback);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002400 } catch (Exception e) {
Lifu Tang30f95a72016-01-07 23:20:38 -08002401 Slog.e(TAG, "mGpsStatusProvider.unregisterGnssStatusCallback failed", e);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002403 }
2404 }
2405
Nick Pellye0fd6932012-07-11 10:26:13 -07002406 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002407 public boolean addGnssMeasurementsListener(
gomo48f1a642017-11-10 20:35:46 -08002408 IGnssMeasurementsListener listener, String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002409 if (!hasGnssPermissions(packageName) || mGnssMeasurementsProvider == null) {
destradaaea8a8a62014-06-23 18:19:03 -07002410 return false;
2411 }
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002412
2413 synchronized (mLock) {
2414 Identity callerIdentity
2415 = new Identity(Binder.getCallingUid(), Binder.getCallingPid(), packageName);
Wyatt Riley11cc7492018-01-17 08:48:27 -08002416 mGnssMeasurementsListeners.put(listener.asBinder(), callerIdentity);
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002417 long identity = Binder.clearCallingIdentity();
2418 try {
2419 if (isThrottlingExemptLocked(callerIdentity)
2420 || isImportanceForeground(
gomo48f1a642017-11-10 20:35:46 -08002421 mActivityManager.getPackageImportance(packageName))) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002422 return mGnssMeasurementsProvider.addListener(listener);
2423 }
2424 } finally {
2425 Binder.restoreCallingIdentity(identity);
2426 }
2427
2428 return true;
2429 }
destradaaea8a8a62014-06-23 18:19:03 -07002430 }
2431
2432 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002433 public void removeGnssMeasurementsListener(IGnssMeasurementsListener listener) {
2434 if (mGnssMeasurementsProvider != null) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002435 synchronized (mLock) {
Wyatt Riley11cc7492018-01-17 08:48:27 -08002436 mGnssMeasurementsListeners.remove(listener.asBinder());
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002437 mGnssMeasurementsProvider.removeListener(listener);
2438 }
Wei Liu5241a4c2015-05-11 14:00:36 -07002439 }
destradaaea8a8a62014-06-23 18:19:03 -07002440 }
2441
2442 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002443 public boolean addGnssNavigationMessageListener(
2444 IGnssNavigationMessageListener listener,
destradaa4b3e3932014-07-21 18:01:47 -07002445 String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002446 if (!hasGnssPermissions(packageName) || mGnssNavigationMessageProvider == null) {
destradaa4b3e3932014-07-21 18:01:47 -07002447 return false;
2448 }
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002449
2450 synchronized (mLock) {
2451 Identity callerIdentity
gomo48f1a642017-11-10 20:35:46 -08002452 = new Identity(Binder.getCallingUid(), Binder.getCallingPid(), packageName);
Wyatt Riley11cc7492018-01-17 08:48:27 -08002453 mGnssNavigationMessageListeners.put(listener.asBinder(), callerIdentity);
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002454 long identity = Binder.clearCallingIdentity();
2455 try {
2456 if (isThrottlingExemptLocked(callerIdentity)
2457 || isImportanceForeground(
gomo48f1a642017-11-10 20:35:46 -08002458 mActivityManager.getPackageImportance(packageName))) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002459 return mGnssNavigationMessageProvider.addListener(listener);
2460 }
2461 } finally {
2462 Binder.restoreCallingIdentity(identity);
2463 }
2464
2465 return true;
2466 }
destradaa4b3e3932014-07-21 18:01:47 -07002467 }
2468
2469 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002470 public void removeGnssNavigationMessageListener(IGnssNavigationMessageListener listener) {
2471 if (mGnssNavigationMessageProvider != null) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002472 synchronized (mLock) {
Wyatt Riley11cc7492018-01-17 08:48:27 -08002473 mGnssNavigationMessageListeners.remove(listener.asBinder());
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002474 mGnssNavigationMessageProvider.removeListener(listener);
2475 }
Wei Liu5241a4c2015-05-11 14:00:36 -07002476 }
destradaa4b3e3932014-07-21 18:01:47 -07002477 }
2478
2479 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480 public boolean sendExtraCommand(String provider, String command, Bundle extras) {
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04002481 if (provider == null) {
2482 // throw NullPointerException to remain compatible with previous implementation
2483 throw new NullPointerException();
2484 }
Victoria Lease37425c32012-10-16 16:08:48 -07002485 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
2486 provider);
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04002487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 // and check for ACCESS_LOCATION_EXTRA_COMMANDS
Mike Lockwoodb7e99222009-07-07 13:18:21 -04002489 if ((mContext.checkCallingOrSelfPermission(ACCESS_LOCATION_EXTRA_COMMANDS)
Maggieaa080f92018-01-04 15:35:11 -08002490 != PERMISSION_GRANTED)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002491 throw new SecurityException("Requires ACCESS_LOCATION_EXTRA_COMMANDS permission");
2492 }
2493
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002494 synchronized (mLock) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002495 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002496 if (p == null) return false;
Nick Pellye0fd6932012-07-11 10:26:13 -07002497
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002498 return p.sendExtraCommand(command, extras);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 }
2500 }
2501
Nick Pellye0fd6932012-07-11 10:26:13 -07002502 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002503 public boolean sendNiResponse(int notifId, int userResponse) {
Mike Lockwood18ad9f62009-08-27 14:01:23 -07002504 if (Binder.getCallingUid() != Process.myUid()) {
2505 throw new SecurityException(
2506 "calling sendNiResponse from outside of the system is not allowed");
2507 }
Danke Xie22d1f9f2009-08-18 18:28:45 -04002508 try {
2509 return mNetInitiatedListener.sendNiResponse(notifId, userResponse);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002510 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002511 Slog.e(TAG, "RemoteException in LocationManagerService.sendNiResponse");
Danke Xie22d1f9f2009-08-18 18:28:45 -04002512 return false;
2513 }
2514 }
2515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 /**
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002517 * @return null if the provider does not exist
Alexey Tarasovf2db9fb2009-09-01 02:37:07 +11002518 * @throws SecurityException if the provider is not allowed to be
gomo48f1a642017-11-10 20:35:46 -08002519 * accessed by the caller
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002520 */
Nick Pellye0fd6932012-07-11 10:26:13 -07002521 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002522 public ProviderProperties getProviderProperties(String provider) {
Laurent Tub7f9d252012-10-16 14:25:00 -07002523 if (mProvidersByName.get(provider) == null) {
David Christie2ff96af2014-01-30 16:09:37 -08002524 return null;
Laurent Tub7f9d252012-10-16 14:25:00 -07002525 }
2526
Victoria Lease37425c32012-10-16 16:08:48 -07002527 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
2528 provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002530 LocationProviderInterface p;
2531 synchronized (mLock) {
2532 p = mProvidersByName.get(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002533 }
2534
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002535 if (p == null) return null;
2536 return p.getProperties();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 }
2538
Jason Monkb71218a2015-06-17 14:44:39 -04002539 /**
2540 * @return null if the provider does not exist
2541 * @throws SecurityException if the provider is not allowed to be
gomo48f1a642017-11-10 20:35:46 -08002542 * accessed by the caller
Jason Monkb71218a2015-06-17 14:44:39 -04002543 */
2544 @Override
2545 public String getNetworkProviderPackage() {
2546 LocationProviderInterface p;
2547 synchronized (mLock) {
2548 if (mProvidersByName.get(LocationManager.NETWORK_PROVIDER) == null) {
2549 return null;
2550 }
2551 p = mProvidersByName.get(LocationManager.NETWORK_PROVIDER);
2552 }
2553
2554 if (p instanceof LocationProviderProxy) {
2555 return ((LocationProviderProxy) p).getConnectedPackageName();
2556 }
2557 return null;
2558 }
2559
Maggieaa080f92018-01-04 15:35:11 -08002560 /**
Maggie2a9409e2018-03-21 11:47:28 -07002561 * Returns the current location enabled/disabled status for a user
2562 *
2563 * @param userId the id of the user
2564 * @return true if location is enabled
2565 */
2566 @Override
2567 public boolean isLocationEnabledForUser(int userId) {
2568 // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
2569 checkInteractAcrossUsersPermission(userId);
2570
2571 long identity = Binder.clearCallingIdentity();
2572 try {
2573 synchronized (mLock) {
2574 final String allowedProviders = Settings.Secure.getStringForUser(
2575 mContext.getContentResolver(),
2576 Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
2577 userId);
2578 if (allowedProviders == null) {
2579 return false;
2580 }
2581 final List<String> providerList = Arrays.asList(allowedProviders.split(","));
2582 for(String provider : mRealProviders.keySet()) {
2583 if (provider.equals(LocationManager.PASSIVE_PROVIDER)
2584 || provider.equals(LocationManager.FUSED_PROVIDER)) {
2585 continue;
2586 }
2587 if (providerList.contains(provider)) {
2588 return true;
2589 }
2590 }
2591 return false;
2592 }
2593 } finally {
2594 Binder.restoreCallingIdentity(identity);
2595 }
2596 }
2597
2598 /**
2599 * Enable or disable location for a user
2600 *
2601 * @param enabled true to enable location, false to disable location
2602 * @param userId the id of the user
2603 */
2604 @Override
2605 public void setLocationEnabledForUser(boolean enabled, int userId) {
2606 mContext.enforceCallingPermission(
2607 android.Manifest.permission.WRITE_SECURE_SETTINGS,
2608 "Requires WRITE_SECURE_SETTINGS permission");
2609
2610 // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
2611 checkInteractAcrossUsersPermission(userId);
2612
2613 long identity = Binder.clearCallingIdentity();
2614 try {
2615 synchronized (mLock) {
2616 final Set<String> allRealProviders = mRealProviders.keySet();
2617 // Update all providers on device plus gps and network provider when disabling
2618 // location
2619 Set<String> allProvidersSet = new ArraySet<>(allRealProviders.size() + 2);
2620 allProvidersSet.addAll(allRealProviders);
2621 // When disabling location, disable gps and network provider that could have been
2622 // enabled by location mode api.
2623 if (enabled == false) {
2624 allProvidersSet.add(LocationManager.GPS_PROVIDER);
2625 allProvidersSet.add(LocationManager.NETWORK_PROVIDER);
2626 }
2627 if (allProvidersSet.isEmpty()) {
2628 return;
2629 }
2630 // to ensure thread safety, we write the provider name with a '+' or '-'
2631 // and let the SettingsProvider handle it rather than reading and modifying
2632 // the list of enabled providers.
2633 final String prefix = enabled ? "+" : "-";
2634 StringBuilder locationProvidersAllowed = new StringBuilder();
2635 for (String provider : allProvidersSet) {
2636 if (provider.equals(LocationManager.PASSIVE_PROVIDER)
2637 || provider.equals(LocationManager.FUSED_PROVIDER)) {
2638 continue;
2639 }
2640 locationProvidersAllowed.append(prefix);
2641 locationProvidersAllowed.append(provider);
2642 locationProvidersAllowed.append(",");
2643 }
2644 // Remove the trailing comma
2645 locationProvidersAllowed.setLength(locationProvidersAllowed.length() - 1);
2646 Settings.Secure.putStringForUser(
2647 mContext.getContentResolver(),
2648 Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
2649 locationProvidersAllowed.toString(),
2650 userId);
2651 }
2652 } finally {
2653 Binder.restoreCallingIdentity(identity);
2654 }
2655 }
2656
2657 /**
2658 * Returns the current enabled/disabled status of a location provider and user
2659 *
2660 * @param provider name of the provider
2661 * @param userId the id of the user
2662 * @return true if the provider exists and is enabled
2663 */
2664 @Override
2665 public boolean isProviderEnabledForUser(String provider, int userId) {
2666 // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
2667 checkInteractAcrossUsersPermission(userId);
2668
2669 // Fused provider is accessed indirectly via criteria rather than the provider-based APIs,
2670 // so we discourage its use
2671 if (LocationManager.FUSED_PROVIDER.equals(provider)) return false;
2672
2673 int uid = Binder.getCallingUid();
2674 synchronized (mLock) {
2675 LocationProviderInterface p = mProvidersByName.get(provider);
2676 return p != null
2677 && isAllowedByUserSettingsLocked(provider, uid, userId);
2678 }
2679 }
2680
2681 /**
2682 * Enable or disable a single location provider.
2683 *
2684 * @param provider name of the provider
2685 * @param enabled true to enable the provider. False to disable the provider
2686 * @param userId the id of the user to set
2687 * @return true if the value was set, false on errors
2688 */
2689 @Override
2690 public boolean setProviderEnabledForUser(String provider, boolean enabled, int userId) {
2691 mContext.enforceCallingPermission(
2692 android.Manifest.permission.WRITE_SECURE_SETTINGS,
2693 "Requires WRITE_SECURE_SETTINGS permission");
2694
2695 // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
2696 checkInteractAcrossUsersPermission(userId);
2697
2698 // Fused provider is accessed indirectly via criteria rather than the provider-based APIs,
2699 // so we discourage its use
2700 if (LocationManager.FUSED_PROVIDER.equals(provider)) return false;
2701
2702 long identity = Binder.clearCallingIdentity();
2703 try {
2704 synchronized (mLock) {
2705 // No such provider exists
2706 if (!mProvidersByName.containsKey(provider)) return false;
2707
2708 // If it is a test provider, do not write to Settings.Secure
2709 if (mMockProviders.containsKey(provider)) {
2710 setTestProviderEnabled(provider, enabled);
2711 return true;
2712 }
2713
2714 // to ensure thread safety, we write the provider name with a '+' or '-'
2715 // and let the SettingsProvider handle it rather than reading and modifying
2716 // the list of enabled providers.
2717 String providerChange = (enabled ? "+" : "-") + provider;
2718 return Settings.Secure.putStringForUser(
2719 mContext.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
2720 providerChange, userId);
2721 }
2722 } finally {
2723 Binder.restoreCallingIdentity(identity);
2724 }
2725 }
2726
2727 /**
Maggieaa080f92018-01-04 15:35:11 -08002728 * Read location provider status from Settings.Secure
2729 *
2730 * @param provider the location provider to query
2731 * @param userId the user id to query
2732 * @return true if the provider is enabled
2733 */
2734 private boolean isLocationProviderEnabledForUser(String provider, int userId) {
2735 long identity = Binder.clearCallingIdentity();
2736 try {
2737 // Use system settings
2738 ContentResolver cr = mContext.getContentResolver();
2739 String allowedProviders = Settings.Secure.getStringForUser(
2740 cr, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
2741 return TextUtils.delimitedStringContains(allowedProviders, ',', provider);
2742 } finally {
2743 Binder.restoreCallingIdentity(identity);
2744 }
2745 }
2746
2747 /**
Maggie2a9409e2018-03-21 11:47:28 -07002748 * Method for checking INTERACT_ACROSS_USERS permission if specified user id is not the same as
2749 * current user id
2750 *
2751 * @param userId the user id to get or set value
2752 */
2753 private void checkInteractAcrossUsersPermission(int userId) {
2754 int uid = Binder.getCallingUid();
2755 if (UserHandle.getUserId(uid) != userId) {
2756 if (ActivityManager.checkComponentPermission(
2757 android.Manifest.permission.INTERACT_ACROSS_USERS, uid, -1, true)
2758 != PERMISSION_GRANTED) {
2759 throw new SecurityException("Requires INTERACT_ACROSS_USERS permission");
2760 }
2761 }
2762 }
2763
2764 /**
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002765 * Returns "true" if the UID belongs to a bound location provider.
2766 *
2767 * @param uid the uid
2768 * @return true if uid belongs to a bound location provider
2769 */
2770 private boolean isUidALocationProvider(int uid) {
2771 if (uid == Process.SYSTEM_UID) {
2772 return true;
2773 }
2774 if (mGeocodeProvider != null) {
David Christie1f141c12014-05-14 15:11:15 -07002775 if (doesUidHavePackage(uid, mGeocodeProvider.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002776 }
2777 for (LocationProviderProxy proxy : mProxyProviders) {
David Christie1f141c12014-05-14 15:11:15 -07002778 if (doesUidHavePackage(uid, proxy.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002779 }
2780 return false;
2781 }
2782
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002783 private void checkCallerIsProvider() {
2784 if (mContext.checkCallingOrSelfPermission(INSTALL_LOCATION_PROVIDER)
Maggieaa080f92018-01-04 15:35:11 -08002785 == PERMISSION_GRANTED) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002786 return;
2787 }
2788
2789 // Previously we only used the INSTALL_LOCATION_PROVIDER
2790 // check. But that is system or signature
2791 // protection level which is not flexible enough for
2792 // providers installed oustide the system image. So
2793 // also allow providers with a UID matching the
2794 // currently bound package name
2795
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002796 if (isUidALocationProvider(Binder.getCallingUid())) {
2797 return;
2798 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002799
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002800 throw new SecurityException("need INSTALL_LOCATION_PROVIDER permission, " +
2801 "or UID of a currently bound location provider");
2802 }
2803
David Christie1f141c12014-05-14 15:11:15 -07002804 /**
2805 * Returns true if the given package belongs to the given uid.
2806 */
2807 private boolean doesUidHavePackage(int uid, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002808 if (packageName == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002809 return false;
2810 }
David Christie1f141c12014-05-14 15:11:15 -07002811 String[] packageNames = mPackageManager.getPackagesForUid(uid);
2812 if (packageNames == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002813 return false;
2814 }
David Christie1f141c12014-05-14 15:11:15 -07002815 for (String name : packageNames) {
2816 if (packageName.equals(name)) {
2817 return true;
2818 }
2819 }
2820 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 }
2822
Nick Pellye0fd6932012-07-11 10:26:13 -07002823 @Override
Mike Lockwooda4903f22010-02-17 06:42:23 -05002824 public void reportLocation(Location location, boolean passive) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002825 checkCallerIsProvider();
Mike Lockwood275555c2009-05-01 11:30:34 -04002826
Nick Pelly2eeeec22012-07-18 13:13:37 -07002827 if (!location.isComplete()) {
2828 Log.w(TAG, "Dropping incomplete location: " + location);
2829 return;
2830 }
2831
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002832 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED, location);
2833 Message m = Message.obtain(mLocationHandler, MSG_LOCATION_CHANGED, location);
Mike Lockwooda4903f22010-02-17 06:42:23 -05002834 m.arg1 = (passive ? 1 : 0);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002835 mLocationHandler.sendMessageAtFrontOfQueue(m);
2836 }
2837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838
Laurent Tu75defb62012-11-01 16:21:52 -07002839 private static boolean shouldBroadcastSafe(
2840 Location loc, Location lastLoc, UpdateRecord record, long now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 // Always broadcast the first update
2842 if (lastLoc == null) {
2843 return true;
2844 }
2845
Nick Pellyf1be6862012-05-15 10:53:42 -07002846 // Check whether sufficient time has passed
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002847 long minTime = record.mRealRequest.getFastestInterval();
David Christie1b9b7b12013-04-15 15:31:11 -07002848 long delta = (loc.getElapsedRealtimeNanos() - lastLoc.getElapsedRealtimeNanos())
2849 / NANOS_PER_MILLI;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002850 if (delta < minTime - MAX_PROVIDER_SCHEDULING_JITTER_MS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002851 return false;
2852 }
2853
2854 // Check whether sufficient distance has been traveled
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002855 double minDistance = record.mRealRequest.getSmallestDisplacement();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002856 if (minDistance > 0.0) {
2857 if (loc.distanceTo(lastLoc) <= minDistance) {
2858 return false;
2859 }
2860 }
2861
Laurent Tu75defb62012-11-01 16:21:52 -07002862 // Check whether sufficient number of udpates is left
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002863 if (record.mRealRequest.getNumUpdates() <= 0) {
Laurent Tu75defb62012-11-01 16:21:52 -07002864 return false;
2865 }
2866
2867 // Check whether the expiry date has passed
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002868 return record.mRealRequest.getExpireAt() >= now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002869 }
2870
Mike Lockwooda4903f22010-02-17 06:42:23 -05002871 private void handleLocationChangedLocked(Location location, boolean passive) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002872 if (D) Log.d(TAG, "incoming location: " + location);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002873 long now = SystemClock.elapsedRealtime();
Mike Lockwooda4903f22010-02-17 06:42:23 -05002874 String provider = (passive ? LocationManager.PASSIVE_PROVIDER : location.getProvider());
Laurent Tu60ec50a2012-10-04 17:00:10 -07002875 // Skip if the provider is unknown.
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002876 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002877 if (p == null) return;
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002878 updateLastLocationLocked(location, provider);
2879 // mLastLocation should have been updated from the updateLastLocationLocked call above.
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002880 Location lastLocation = mLastLocation.get(provider);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002881 if (lastLocation == null) {
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002882 Log.e(TAG, "handleLocationChangedLocked() updateLastLocation failed");
2883 return;
Mike Lockwood4e50b782009-04-03 08:24:43 -07002884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002885
David Christie1b9b7b12013-04-15 15:31:11 -07002886 // Update last known coarse interval location if enough time has passed.
2887 Location lastLocationCoarseInterval = mLastLocationCoarseInterval.get(provider);
2888 if (lastLocationCoarseInterval == null) {
2889 lastLocationCoarseInterval = new Location(location);
2890 mLastLocationCoarseInterval.put(provider, lastLocationCoarseInterval);
2891 }
2892 long timeDiffNanos = location.getElapsedRealtimeNanos()
2893 - lastLocationCoarseInterval.getElapsedRealtimeNanos();
2894 if (timeDiffNanos > LocationFudger.FASTEST_INTERVAL_MS * NANOS_PER_MILLI) {
2895 lastLocationCoarseInterval.set(location);
2896 }
2897 // Don't ever return a coarse location that is more recent than the allowed update
2898 // interval (i.e. don't allow an app to keep registering and unregistering for
2899 // location updates to overcome the minimum interval).
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002900 Location noGPSLocation =
David Christie1b9b7b12013-04-15 15:31:11 -07002901 lastLocationCoarseInterval.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2902
Laurent Tu60ec50a2012-10-04 17:00:10 -07002903 // Skip if there are no UpdateRecords for this provider.
2904 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
2905 if (records == null || records.size() == 0) return;
2906
Victoria Lease09016ab2012-09-16 12:33:15 -07002907 // Fetch coarse location
2908 Location coarseLocation = null;
David Christie1b9b7b12013-04-15 15:31:11 -07002909 if (noGPSLocation != null) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002910 coarseLocation = mLocationFudger.getOrCreate(noGPSLocation);
2911 }
2912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 // Fetch latest status update time
2914 long newStatusUpdateTime = p.getStatusUpdateTime();
2915
David Christie2ff96af2014-01-30 16:09:37 -08002916 // Get latest status
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002917 Bundle extras = new Bundle();
2918 int status = p.getStatus(extras);
2919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002920 ArrayList<Receiver> deadReceivers = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002921 ArrayList<UpdateRecord> deadUpdateRecords = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07002922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002923 // Broadcast location or status to all listeners
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002924 for (UpdateRecord r : records) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002925 Receiver receiver = r.mReceiver;
Mike Lockwood03ca2162010-04-01 08:10:09 -07002926 boolean receiverDead = false;
Nick Pelly4035f5a2012-08-17 14:43:49 -07002927
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002928 int receiverUserId = UserHandle.getUserId(receiver.mIdentity.mUid);
2929 if (!isCurrentProfile(receiverUserId)
2930 && !isUidALocationProvider(receiver.mIdentity.mUid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07002931 if (D) {
Victoria Lease269518e2012-10-29 08:25:39 -07002932 Log.d(TAG, "skipping loc update for background user " + receiverUserId +
Victoria Leaseb711d572012-10-02 13:14:11 -07002933 " (current user: " + mCurrentUserId + ", app: " +
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002934 receiver.mIdentity.mPackageName + ")");
Victoria Leaseb711d572012-10-02 13:14:11 -07002935 }
2936 continue;
2937 }
2938
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002939 if (mBlacklist.isBlacklisted(receiver.mIdentity.mPackageName)) {
gomo48f1a642017-11-10 20:35:46 -08002940 if (D) {
2941 Log.d(TAG, "skipping loc update for blacklisted app: " +
2942 receiver.mIdentity.mPackageName);
2943 }
Nick Pelly4035f5a2012-08-17 14:43:49 -07002944 continue;
2945 }
2946
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002947 if (!reportLocationAccessNoThrow(
2948 receiver.mIdentity.mPid,
2949 receiver.mIdentity.mUid,
2950 receiver.mIdentity.mPackageName,
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002951 receiver.mAllowedResolutionLevel)) {
gomo48f1a642017-11-10 20:35:46 -08002952 if (D) {
2953 Log.d(TAG, "skipping loc update for no op app: " +
2954 receiver.mIdentity.mPackageName);
2955 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002956 continue;
2957 }
2958
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002959 Location notifyLocation;
Victoria Lease37425c32012-10-16 16:08:48 -07002960 if (receiver.mAllowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
2961 notifyLocation = coarseLocation; // use coarse location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002962 } else {
Victoria Lease37425c32012-10-16 16:08:48 -07002963 notifyLocation = lastLocation; // use fine location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002964 }
Victoria Lease09016ab2012-09-16 12:33:15 -07002965 if (notifyLocation != null) {
2966 Location lastLoc = r.mLastFixBroadcast;
Laurent Tu75defb62012-11-01 16:21:52 -07002967 if ((lastLoc == null) || shouldBroadcastSafe(notifyLocation, lastLoc, r, now)) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002968 if (lastLoc == null) {
2969 lastLoc = new Location(notifyLocation);
2970 r.mLastFixBroadcast = lastLoc;
2971 } else {
2972 lastLoc.set(notifyLocation);
2973 }
2974 if (!receiver.callLocationChangedLocked(notifyLocation)) {
2975 Slog.w(TAG, "RemoteException calling onLocationChanged on " + receiver);
2976 receiverDead = true;
2977 }
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002978 r.mRealRequest.decrementNumUpdates();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002979 }
2980 }
2981
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002982 long prevStatusUpdateTime = r.mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002983 if ((newStatusUpdateTime > prevStatusUpdateTime) &&
Victoria Lease09016ab2012-09-16 12:33:15 -07002984 (prevStatusUpdateTime != 0 || status != LocationProvider.AVAILABLE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002985
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002986 r.mLastStatusBroadcast = newStatusUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002987 if (!receiver.callStatusChangedLocked(provider, status, extras)) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07002988 receiverDead = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002989 Slog.w(TAG, "RemoteException calling onStatusChanged on " + receiver);
Mike Lockwood03ca2162010-04-01 08:10:09 -07002990 }
2991 }
2992
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002993 // track expired records
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002994 if (r.mRealRequest.getNumUpdates() <= 0 || r.mRealRequest.getExpireAt() < now) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002995 if (deadUpdateRecords == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002996 deadUpdateRecords = new ArrayList<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002997 }
2998 deadUpdateRecords.add(r);
2999 }
3000 // track dead receivers
3001 if (receiverDead) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07003002 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08003003 deadReceivers = new ArrayList<>();
Mike Lockwood03ca2162010-04-01 08:10:09 -07003004 }
3005 if (!deadReceivers.contains(receiver)) {
3006 deadReceivers.add(receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003007 }
3008 }
3009 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003010
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003011 // remove dead records and receivers outside the loop
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003012 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003013 for (Receiver receiver : deadReceivers) {
3014 removeUpdatesLocked(receiver);
3015 }
3016 }
3017 if (deadUpdateRecords != null) {
3018 for (UpdateRecord r : deadUpdateRecords) {
3019 r.disposeLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003020 }
Victoria Lease8b38b292012-12-04 15:04:43 -08003021 applyRequirementsLocked(provider);
3022 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003023 }
3024
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08003025 /**
3026 * Updates last location with the given location
3027 *
3028 * @param location new location to update
3029 * @param provider Location provider to update for
3030 */
3031 private void updateLastLocationLocked(Location location, String provider) {
3032 Location noGPSLocation = location.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
3033 Location lastNoGPSLocation;
3034 Location lastLocation = mLastLocation.get(provider);
3035 if (lastLocation == null) {
3036 lastLocation = new Location(provider);
3037 mLastLocation.put(provider, lastLocation);
3038 } else {
3039 lastNoGPSLocation = lastLocation.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
3040 if (noGPSLocation == null && lastNoGPSLocation != null) {
3041 // New location has no no-GPS location: adopt last no-GPS location. This is set
3042 // directly into location because we do not want to notify COARSE clients.
3043 location.setExtraLocation(Location.EXTRA_NO_GPS_LOCATION, lastNoGPSLocation);
3044 }
3045 }
3046 lastLocation.set(location);
3047 }
3048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003049 private class LocationWorkerHandler extends Handler {
Victoria Lease5cd731a2012-12-19 15:04:21 -08003050 public LocationWorkerHandler(Looper looper) {
3051 super(looper, null, true);
3052 }
3053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003054 @Override
3055 public void handleMessage(Message msg) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003056 switch (msg.what) {
3057 case MSG_LOCATION_CHANGED:
3058 handleLocationChanged((Location) msg.obj, msg.arg1 == 1);
3059 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003060 }
3061 }
3062 }
3063
Victoria Lease54ca7ae2013-01-08 09:39:50 -08003064 private boolean isMockProvider(String provider) {
3065 synchronized (mLock) {
3066 return mMockProviders.containsKey(provider);
3067 }
3068 }
3069
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003070 private void handleLocationChanged(Location location, boolean passive) {
Victoria Lease54ca7ae2013-01-08 09:39:50 -08003071 // create a working copy of the incoming Location so that the service can modify it without
3072 // disturbing the caller's copy
3073 Location myLocation = new Location(location);
3074 String provider = myLocation.getProvider();
3075
3076 // set "isFromMockProvider" bit if location came from a mock provider. we do not clear this
3077 // bit if location did not come from a mock provider because passive/fused providers can
3078 // forward locations from mock providers, and should not grant them legitimacy in doing so.
3079 if (!myLocation.isFromMockProvider() && isMockProvider(provider)) {
3080 myLocation.setIsFromMockProvider(true);
3081 }
Jeff Sharkey5e613312012-01-30 11:16:20 -08003082
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003083 synchronized (mLock) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08003084 if (isAllowedByCurrentUserSettingsLocked(provider)) {
3085 if (!passive) {
3086 // notify passive provider of the new location
3087 mPassiveProvider.updateLocation(myLocation);
3088 }
Victoria Lease54ca7ae2013-01-08 09:39:50 -08003089 handleLocationChangedLocked(myLocation, passive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003091 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003092 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003093
Mike Lockwoode97ae402010-09-29 15:23:46 -04003094 private final PackageMonitor mPackageMonitor = new PackageMonitor() {
3095 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003096 public void onPackageDisappeared(String packageName, int reason) {
3097 // remove all receivers associated with this package name
3098 synchronized (mLock) {
3099 ArrayList<Receiver> deadReceivers = null;
3100
3101 for (Receiver receiver : mReceivers.values()) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08003102 if (receiver.mIdentity.mPackageName.equals(packageName)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003103 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08003104 deadReceivers = new ArrayList<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003105 }
3106 deadReceivers.add(receiver);
3107 }
3108 }
3109
3110 // perform removal outside of mReceivers loop
3111 if (deadReceivers != null) {
3112 for (Receiver receiver : deadReceivers) {
3113 removeUpdatesLocked(receiver);
3114 }
3115 }
3116 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003117 }
Mike Lockwoode97ae402010-09-29 15:23:46 -04003118 };
3119
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003120 // Geocoder
3121
Nick Pellye0fd6932012-07-11 10:26:13 -07003122 @Override
Mike Lockwoode15735a2010-09-20 17:48:47 -04003123 public boolean geocoderIsPresent() {
Mark Vandevoorde01ac80b2010-05-21 15:43:26 -07003124 return mGeocodeProvider != null;
3125 }
3126
Nick Pellye0fd6932012-07-11 10:26:13 -07003127 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003128 public String getFromLocation(double latitude, double longitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05003129 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04003130 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05003131 return mGeocodeProvider.getFromLocation(latitude, longitude, maxResults,
3132 params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003133 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04003134 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003135 }
3136
Mike Lockwooda55c3212009-04-15 11:10:11 -04003137
Nick Pellye0fd6932012-07-11 10:26:13 -07003138 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003139 public String getFromLocationName(String locationName,
Mike Lockwooda55c3212009-04-15 11:10:11 -04003140 double lowerLeftLatitude, double lowerLeftLongitude,
3141 double upperRightLatitude, double upperRightLongitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05003142 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04003143
3144 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05003145 return mGeocodeProvider.getFromLocationName(locationName, lowerLeftLatitude,
3146 lowerLeftLongitude, upperRightLatitude, upperRightLongitude,
3147 maxResults, params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003148 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04003149 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003150 }
3151
3152 // Mock Providers
3153
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003154 private boolean canCallerAccessMockLocation(String opPackageName) {
3155 return mAppOps.noteOp(AppOpsManager.OP_MOCK_LOCATION, Binder.getCallingUid(),
3156 opPackageName) == AppOpsManager.MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003157 }
3158
Nick Pellye0fd6932012-07-11 10:26:13 -07003159 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003160 public void addTestProvider(String name, ProviderProperties properties, String opPackageName) {
3161 if (!canCallerAccessMockLocation(opPackageName)) {
3162 return;
3163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003164
Mike Lockwooda4903f22010-02-17 06:42:23 -05003165 if (LocationManager.PASSIVE_PROVIDER.equals(name)) {
3166 throw new IllegalArgumentException("Cannot mock the passive location provider");
3167 }
3168
Mike Lockwood86328a92009-10-23 08:38:25 -04003169 long identity = Binder.clearCallingIdentity();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003170 synchronized (mLock) {
Mike Lockwood7566c1d2009-08-25 10:05:18 -07003171 // remove the real provider if we are replacing GPS or network provider
3172 if (LocationManager.GPS_PROVIDER.equals(name)
Nick Pelly1332b532012-08-21 16:25:47 -07003173 || LocationManager.NETWORK_PROVIDER.equals(name)
3174 || LocationManager.FUSED_PROVIDER.equals(name)) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05003175 LocationProviderInterface p = mProvidersByName.get(name);
3176 if (p != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003177 removeProviderLocked(p);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07003178 }
3179 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09003180 addTestProviderLocked(name, properties);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003181 updateProvidersLocked();
3182 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003183 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003184 }
3185
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09003186 private void addTestProviderLocked(String name, ProviderProperties properties) {
3187 if (mProvidersByName.get(name) != null) {
3188 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
3189 }
3190 MockProvider provider = new MockProvider(name, this, properties);
3191 addProviderLocked(provider);
3192 mMockProviders.put(name, provider);
3193 mLastLocation.put(name, null);
3194 mLastLocationCoarseInterval.put(name, null);
3195 }
3196
Nick Pellye0fd6932012-07-11 10:26:13 -07003197 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003198 public void removeTestProvider(String provider, String opPackageName) {
3199 if (!canCallerAccessMockLocation(opPackageName)) {
3200 return;
3201 }
3202
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003203 synchronized (mLock) {
Tom O'Neill07ee5d12014-03-03 17:48:35 -08003204
3205 // These methods can't be called after removing the test provider, so first make sure
Tom O'Neillfe6d3c52014-03-04 08:26:17 -08003206 // we don't leave anything dangling.
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003207 clearTestProviderEnabled(provider, opPackageName);
3208 clearTestProviderLocation(provider, opPackageName);
3209 clearTestProviderStatus(provider, opPackageName);
Tom O'Neill07ee5d12014-03-03 17:48:35 -08003210
You Kima6d0b6f2012-10-28 03:58:44 +09003211 MockProvider mockProvider = mMockProviders.remove(provider);
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003212 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003213 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3214 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003215 long identity = Binder.clearCallingIdentity();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003216 removeProviderLocked(mProvidersByName.get(provider));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003217
3218 // reinstate real provider if available
3219 LocationProviderInterface realProvider = mRealProviders.get(provider);
3220 if (realProvider != null) {
3221 addProviderLocked(realProvider);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07003222 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003223 mLastLocation.put(provider, null);
David Christie1b9b7b12013-04-15 15:31:11 -07003224 mLastLocationCoarseInterval.put(provider, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003225 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04003226 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003227 }
3228 }
3229
Nick Pellye0fd6932012-07-11 10:26:13 -07003230 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003231 public void setTestProviderLocation(String provider, Location loc, String opPackageName) {
3232 if (!canCallerAccessMockLocation(opPackageName)) {
3233 return;
3234 }
3235
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003236 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003237 MockProvider mockProvider = mMockProviders.get(provider);
3238 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003239 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3240 }
Tom O'Neilla206a0f2016-12-15 10:26:28 -08003241
3242 // Ensure that the location is marked as being mock. There's some logic to do this in
3243 // handleLocationChanged(), but it fails if loc has the wrong provider (bug 33091107).
3244 Location mock = new Location(loc);
3245 mock.setIsFromMockProvider(true);
3246
3247 if (!TextUtils.isEmpty(loc.getProvider()) && !provider.equals(loc.getProvider())) {
3248 // The location has an explicit provider that is different from the mock provider
3249 // name. The caller may be trying to fool us via bug 33091107.
3250 EventLog.writeEvent(0x534e4554, "33091107", Binder.getCallingUid(),
3251 provider + "!=" + loc.getProvider());
3252 }
3253
Mike Lockwood95427cd2009-05-07 13:27:54 -04003254 // clear calling identity so INSTALL_LOCATION_PROVIDER permission is not required
3255 long identity = Binder.clearCallingIdentity();
Tom O'Neilla206a0f2016-12-15 10:26:28 -08003256 mockProvider.setLocation(mock);
Mike Lockwood95427cd2009-05-07 13:27:54 -04003257 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003258 }
3259 }
3260
Nick Pellye0fd6932012-07-11 10:26:13 -07003261 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003262 public void clearTestProviderLocation(String provider, String opPackageName) {
3263 if (!canCallerAccessMockLocation(opPackageName)) {
3264 return;
3265 }
3266
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003267 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003268 MockProvider mockProvider = mMockProviders.get(provider);
3269 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003270 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3271 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003272 mockProvider.clearLocation();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003273 }
3274 }
3275
Nick Pellye0fd6932012-07-11 10:26:13 -07003276 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003277 public void setTestProviderEnabled(String provider, boolean enabled, String opPackageName) {
3278 if (!canCallerAccessMockLocation(opPackageName)) {
3279 return;
3280 }
Maggie2a9409e2018-03-21 11:47:28 -07003281 setTestProviderEnabled(provider, enabled);
3282 }
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003283
Maggie2a9409e2018-03-21 11:47:28 -07003284 /** Enable or disable a test location provider. */
3285 private void setTestProviderEnabled(String provider, boolean enabled) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003286 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003287 MockProvider mockProvider = mMockProviders.get(provider);
3288 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3290 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003291 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003292 if (enabled) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003293 mockProvider.enable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003294 mEnabledProviders.add(provider);
3295 mDisabledProviders.remove(provider);
3296 } else {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003297 mockProvider.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003298 mEnabledProviders.remove(provider);
3299 mDisabledProviders.add(provider);
3300 }
3301 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04003302 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003303 }
3304 }
3305
Nick Pellye0fd6932012-07-11 10:26:13 -07003306 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003307 public void clearTestProviderEnabled(String provider, String opPackageName) {
3308 if (!canCallerAccessMockLocation(opPackageName)) {
3309 return;
3310 }
3311
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003312 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003313 MockProvider mockProvider = mMockProviders.get(provider);
3314 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003315 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3316 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003317 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003318 mEnabledProviders.remove(provider);
3319 mDisabledProviders.remove(provider);
3320 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04003321 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003322 }
3323 }
3324
Nick Pellye0fd6932012-07-11 10:26:13 -07003325 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003326 public void setTestProviderStatus(String provider, int status, Bundle extras, long updateTime,
3327 String opPackageName) {
3328 if (!canCallerAccessMockLocation(opPackageName)) {
3329 return;
3330 }
3331
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003332 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003333 MockProvider mockProvider = mMockProviders.get(provider);
3334 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003335 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3336 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003337 mockProvider.setStatus(status, extras, updateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003338 }
3339 }
3340
Nick Pellye0fd6932012-07-11 10:26:13 -07003341 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003342 public void clearTestProviderStatus(String provider, String opPackageName) {
3343 if (!canCallerAccessMockLocation(opPackageName)) {
3344 return;
3345 }
3346
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003347 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003348 MockProvider mockProvider = mMockProviders.get(provider);
3349 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003350 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3351 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003352 mockProvider.clearStatus();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003353 }
3354 }
3355
3356 private void log(String log) {
3357 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003358 Slog.d(TAG, log);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003359 }
3360 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003361
3362 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003364 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Nick Pellye0fd6932012-07-11 10:26:13 -07003365
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003366 synchronized (mLock) {
Siddharth Raybb608c82017-03-16 11:33:34 -07003367 if (args.length > 0 && args[0].equals("--gnssmetrics")) {
3368 if (mGnssMetricsProvider != null) {
3369 pw.append(mGnssMetricsProvider.getGnssMetricsAsProtoString());
3370 }
3371 return;
3372 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003373 pw.println("Current Location Manager state:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003374 pw.println(" Location Listeners:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003375 for (Receiver receiver : mReceivers.values()) {
3376 pw.println(" " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003377 }
David Christie2ff96af2014-01-30 16:09:37 -08003378 pw.println(" Active Records by Provider:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003379 for (Map.Entry<String, ArrayList<UpdateRecord>> entry : mRecordsByProvider.entrySet()) {
3380 pw.println(" " + entry.getKey() + ":");
3381 for (UpdateRecord record : entry.getValue()) {
3382 pw.println(" " + record);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003383 }
3384 }
Wyatt Riley11cc7492018-01-17 08:48:27 -08003385 pw.println(" Active GnssMeasurement Listeners:");
3386 for (Identity identity : mGnssMeasurementsListeners.values()) {
3387 pw.println(" " + identity.mPid + " " + identity.mUid + " "
3388 + identity.mPackageName + ": " + isThrottlingExemptLocked(identity));
3389 }
3390 pw.println(" Active GnssNavigationMessage Listeners:");
3391 for (Identity identity : mGnssNavigationMessageListeners.values()) {
3392 pw.println(" " + identity.mPid + " " + identity.mUid + " "
3393 + identity.mPackageName + ": " + isThrottlingExemptLocked(identity));
3394 }
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08003395 pw.println(" Overlay Provider Packages:");
3396 for (LocationProviderInterface provider : mProviders) {
3397 if (provider instanceof LocationProviderProxy) {
3398 pw.println(" " + provider.getName() + ": "
3399 + ((LocationProviderProxy) provider).getConnectedPackageName());
3400 }
3401 }
David Christie2ff96af2014-01-30 16:09:37 -08003402 pw.println(" Historical Records by Provider:");
3403 for (Map.Entry<PackageProviderKey, PackageStatistics> entry
3404 : mRequestStatistics.statistics.entrySet()) {
3405 PackageProviderKey key = entry.getKey();
3406 PackageStatistics stats = entry.getValue();
3407 pw.println(" " + key.packageName + ": " + key.providerName + ": " + stats);
3408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003409 pw.println(" Last Known Locations:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003410 for (Map.Entry<String, Location> entry : mLastLocation.entrySet()) {
3411 String provider = entry.getKey();
3412 Location location = entry.getValue();
3413 pw.println(" " + provider + ": " + location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003414 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003415
David Christie1b9b7b12013-04-15 15:31:11 -07003416 pw.println(" Last Known Locations Coarse Intervals:");
3417 for (Map.Entry<String, Location> entry : mLastLocationCoarseInterval.entrySet()) {
3418 String provider = entry.getKey();
3419 Location location = entry.getValue();
3420 pw.println(" " + provider + ": " + location);
3421 }
3422
Nick Pellye0fd6932012-07-11 10:26:13 -07003423 mGeofenceManager.dump(pw);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003424
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003425 if (mEnabledProviders.size() > 0) {
3426 pw.println(" Enabled Providers:");
3427 for (String i : mEnabledProviders) {
3428 pw.println(" " + i);
3429 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003431 }
3432 if (mDisabledProviders.size() > 0) {
3433 pw.println(" Disabled Providers:");
3434 for (String i : mDisabledProviders) {
3435 pw.println(" " + i);
3436 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003437 }
Nick Pelly4035f5a2012-08-17 14:43:49 -07003438 pw.append(" ");
3439 mBlacklist.dump(pw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003440 if (mMockProviders.size() > 0) {
3441 pw.println(" Mock Providers:");
3442 for (Map.Entry<String, MockProvider> i : mMockProviders.entrySet()) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003443 i.getValue().dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003444 }
3445 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003446
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08003447 if (!mBackgroundThrottlePackageWhitelist.isEmpty()) {
3448 pw.println(" Throttling Whitelisted Packages:");
3449 for (String packageName : mBackgroundThrottlePackageWhitelist) {
3450 pw.println(" " + packageName);
3451 }
3452 }
3453
Nick Pelly74fa7ea2012-08-13 19:36:38 -07003454 pw.append(" fudger: ");
gomo48f1a642017-11-10 20:35:46 -08003455 mLocationFudger.dump(fd, pw, args);
Nick Pelly74fa7ea2012-08-13 19:36:38 -07003456
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003457 if (args.length > 0 && "short".equals(args[0])) {
3458 return;
3459 }
gomo48f1a642017-11-10 20:35:46 -08003460 for (LocationProviderInterface provider : mProviders) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003461 pw.print(provider.getName() + " Internal State");
3462 if (provider instanceof LocationProviderProxy) {
3463 LocationProviderProxy proxy = (LocationProviderProxy) provider;
3464 pw.print(" (" + proxy.getConnectedPackageName() + ")");
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06003465 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003466 pw.println(":");
3467 provider.dump(fd, pw, args);
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06003468 }
Wyatt Rileycf879db2017-01-12 13:57:38 -08003469 if (mGnssBatchingInProgress) {
3470 pw.println(" GNSS batching in progress");
3471 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003472 }
3473 }
3474}