blob: fb5fba0d097e539dcd25f6927cc3ca52bd905584 [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,
Victoria Lease37425c32012-10-16 16:08:48 -0700963 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700964 // call this after broadcasting so we do not increment
965 // if we throw an exeption.
966 incrementPendingBroadcastsLocked();
967 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 } catch (PendingIntent.CanceledException e) {
969 return false;
970 }
971 }
972 return true;
973 }
974
975 public boolean callLocationChangedLocked(Location location) {
976 if (mListener != null) {
977 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700978 synchronized (this) {
979 // synchronize to ensure incrementPendingBroadcastsLocked()
980 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c5406a2012-11-29 16:18:01 -0800981 mListener.onLocationChanged(new Location(location));
Nick Pellye0fd6932012-07-11 10:26:13 -0700982 // call this after broadcasting so we do not increment
983 // if we throw an exeption.
984 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 } catch (RemoteException e) {
987 return false;
988 }
989 } else {
990 Intent locationChanged = new Intent();
gomo48f1a642017-11-10 20:35:46 -0800991 locationChanged.putExtra(LocationManager.KEY_LOCATION_CHANGED,
992 new Location(location));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700994 synchronized (this) {
995 // synchronize to ensure incrementPendingBroadcastsLocked()
996 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700997 mPendingIntent.send(mContext, 0, locationChanged, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700998 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700999 // call this after broadcasting so we do not increment
1000 // if we throw an exeption.
1001 incrementPendingBroadcastsLocked();
1002 }
1003 } catch (PendingIntent.CanceledException e) {
1004 return false;
1005 }
1006 }
1007 return true;
1008 }
1009
1010 public boolean callProviderEnabledLocked(String provider, boolean enabled) {
David Christie15b31912013-08-13 15:54:32 -07001011 // First update AppOp monitoring.
1012 // An app may get/lose location access as providers are enabled/disabled.
1013 updateMonitoring(true);
1014
Mike Lockwood48f17512009-04-23 09:12:08 -07001015 if (mListener != null) {
1016 try {
1017 synchronized (this) {
1018 // synchronize to ensure incrementPendingBroadcastsLocked()
1019 // is called before decrementPendingBroadcasts()
1020 if (enabled) {
1021 mListener.onProviderEnabled(provider);
1022 } else {
1023 mListener.onProviderDisabled(provider);
1024 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001025 // call this after broadcasting so we do not increment
1026 // if we throw an exeption.
1027 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001028 }
1029 } catch (RemoteException e) {
1030 return false;
1031 }
1032 } else {
1033 Intent providerIntent = new Intent();
1034 providerIntent.putExtra(LocationManager.KEY_PROVIDER_ENABLED, enabled);
1035 try {
1036 synchronized (this) {
1037 // synchronize to ensure incrementPendingBroadcastsLocked()
1038 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001039 mPendingIntent.send(mContext, 0, providerIntent, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -07001040 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -07001041 // call this after broadcasting so we do not increment
1042 // if we throw an exeption.
1043 incrementPendingBroadcastsLocked();
1044 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 } catch (PendingIntent.CanceledException e) {
1046 return false;
1047 }
1048 }
1049 return true;
1050 }
1051
Nick Pellyf1be6862012-05-15 10:53:42 -07001052 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 public void binderDied() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001054 if (D) Log.d(TAG, "Location listener died");
1055
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001056 synchronized (mLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 removeUpdatesLocked(this);
1058 }
Mike Lockwood48f17512009-04-23 09:12:08 -07001059 synchronized (this) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001060 clearPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001061 }
1062 }
1063
Nick Pellye0fd6932012-07-11 10:26:13 -07001064 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -07001065 public void onSendFinished(PendingIntent pendingIntent, Intent intent,
1066 int resultCode, String resultData, Bundle resultExtras) {
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001067 synchronized (this) {
1068 decrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001069 }
1070 }
1071
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001072 // this must be called while synchronized by caller in a synchronized block
1073 // containing the sending of the broadcaset
1074 private void incrementPendingBroadcastsLocked() {
1075 if (mPendingBroadcasts++ == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001076 mWakeLock.acquire();
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001077 }
1078 }
1079
1080 private void decrementPendingBroadcastsLocked() {
1081 if (--mPendingBroadcasts == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001082 if (mWakeLock.isHeld()) {
1083 mWakeLock.release();
1084 }
1085 }
1086 }
1087
1088 public void clearPendingBroadcastsLocked() {
1089 if (mPendingBroadcasts > 0) {
1090 mPendingBroadcasts = 0;
1091 if (mWakeLock.isHeld()) {
1092 mWakeLock.release();
1093 }
Mike Lockwood48f17512009-04-23 09:12:08 -07001094 }
1095 }
1096 }
1097
Nick Pellye0fd6932012-07-11 10:26:13 -07001098 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -07001099 public void locationCallbackFinished(ILocationListener listener) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001100 //Do not use getReceiverLocked here as that will add the ILocationListener to
Joshua Bartel080b61b2009-10-05 12:44:46 -04001101 //the receiver list if it is not found. If it is not found then the
1102 //LocationListener was removed when it had a pending broadcast and should
1103 //not be added back.
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001104 synchronized (mLock) {
1105 IBinder binder = listener.asBinder();
1106 Receiver receiver = mReceivers.get(binder);
1107 if (receiver != null) {
1108 synchronized (receiver) {
1109 // so wakelock calls will succeed
1110 long identity = Binder.clearCallingIdentity();
1111 receiver.decrementPendingBroadcastsLocked();
1112 Binder.restoreCallingIdentity(identity);
David Christie2ff96af2014-01-30 16:09:37 -08001113 }
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001114 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 }
1116 }
1117
Lifu Tang82f893d2016-01-21 18:15:33 -08001118 /**
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001119 * Returns the year of the GNSS hardware.
Lifu Tang82f893d2016-01-21 18:15:33 -08001120 */
1121 @Override
Lifu Tang9363b942016-02-16 18:07:00 -08001122 public int getGnssYearOfHardware() {
Wyatt Rileycf879db2017-01-12 13:57:38 -08001123 if (mGnssSystemInfoProvider != null) {
Lifu Tang9363b942016-02-16 18:07:00 -08001124 return mGnssSystemInfoProvider.getGnssYearOfHardware();
Lifu Tang82f893d2016-01-21 18:15:33 -08001125 } else {
1126 return 0;
1127 }
1128 }
1129
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001130
1131 /**
1132 * Returns the model name of the GNSS hardware.
1133 */
1134 @Override
Wyatt Riley49097c02018-03-15 09:14:43 -07001135 @Nullable
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001136 public String getGnssHardwareModelName() {
1137 if (mGnssSystemInfoProvider != null) {
1138 return mGnssSystemInfoProvider.getGnssHardwareModelName();
1139 } else {
Wyatt Riley49097c02018-03-15 09:14:43 -07001140 return null;
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001141 }
1142 }
1143
Wyatt Rileycf879db2017-01-12 13:57:38 -08001144 /**
1145 * Runs some checks for GNSS (FINE) level permissions, used by several methods which directly
1146 * (try to) access GNSS information at this layer.
1147 */
1148 private boolean hasGnssPermissions(String packageName) {
1149 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1150 checkResolutionLevelIsSufficientForProviderUse(
1151 allowedResolutionLevel,
1152 LocationManager.GPS_PROVIDER);
1153
1154 int pid = Binder.getCallingPid();
1155 int uid = Binder.getCallingUid();
1156 long identity = Binder.clearCallingIdentity();
1157 boolean hasLocationAccess;
1158 try {
1159 hasLocationAccess = checkLocationAccess(pid, uid, packageName, allowedResolutionLevel);
1160 } finally {
1161 Binder.restoreCallingIdentity(identity);
1162 }
1163
1164 return hasLocationAccess;
1165 }
1166
1167 /**
1168 * Returns the GNSS batching size, if available.
1169 */
1170 @Override
1171 public int getGnssBatchSize(String packageName) {
1172 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1173 "Location Hardware permission not granted to access hardware batching");
1174
1175 if (hasGnssPermissions(packageName) && mGnssBatchingProvider != null) {
1176 return mGnssBatchingProvider.getSize();
1177 } else {
1178 return 0;
1179 }
1180 }
1181
1182 /**
1183 * Adds a callback for GNSS Batching events, if permissions allow, which are transported
1184 * to potentially multiple listeners by the BatchedLocationCallbackTransport above this.
1185 */
1186 @Override
1187 public boolean addGnssBatchingCallback(IBatchedLocationCallback callback, String packageName) {
1188 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1189 "Location Hardware permission not granted to access hardware batching");
1190
1191 if (!hasGnssPermissions(packageName) || mGnssBatchingProvider == null) {
1192 return false;
1193 }
1194
1195 mGnssBatchingCallback = callback;
1196 mGnssBatchingDeathCallback = new LinkedCallback(callback);
1197 try {
1198 callback.asBinder().linkToDeath(mGnssBatchingDeathCallback, 0 /* flags */);
1199 } catch (RemoteException e) {
1200 // if the remote process registering the listener is already dead, just swallow the
1201 // exception and return
1202 Log.e(TAG, "Remote listener already died.", e);
1203 return false;
1204 }
1205
1206 return true;
1207 }
1208
1209 private class LinkedCallback implements IBinder.DeathRecipient {
1210 private final IBatchedLocationCallback mCallback;
1211
1212 public LinkedCallback(@NonNull IBatchedLocationCallback callback) {
1213 mCallback = callback;
1214 }
1215
1216 @NonNull
1217 public IBatchedLocationCallback getUnderlyingListener() {
1218 return mCallback;
1219 }
1220
1221 @Override
1222 public void binderDied() {
1223 Log.d(TAG, "Remote Batching Callback died: " + mCallback);
1224 stopGnssBatch();
1225 removeGnssBatchingCallback();
1226 }
1227 }
1228
1229 /**
1230 * Removes callback for GNSS batching
1231 */
1232 @Override
1233 public void removeGnssBatchingCallback() {
1234 try {
1235 mGnssBatchingCallback.asBinder().unlinkToDeath(mGnssBatchingDeathCallback,
1236 0 /* flags */);
1237 } catch (NoSuchElementException e) {
1238 // if the death callback isn't connected (it should be...), log error, swallow the
1239 // exception and return
1240 Log.e(TAG, "Couldn't unlink death callback.", e);
1241 }
1242 mGnssBatchingCallback = null;
1243 mGnssBatchingDeathCallback = null;
1244 }
1245
1246
1247 /**
1248 * Starts GNSS batching, if available.
1249 */
1250 @Override
1251 public boolean startGnssBatch(long periodNanos, boolean wakeOnFifoFull, String packageName) {
1252 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1253 "Location Hardware permission not granted to access hardware batching");
1254
1255 if (!hasGnssPermissions(packageName) || mGnssBatchingProvider == null) {
1256 return false;
1257 }
1258
1259 if (mGnssBatchingInProgress) {
1260 // Current design does not expect multiple starts to be called repeatedly
1261 Log.e(TAG, "startGnssBatch unexpectedly called w/o stopping prior batch");
1262 // Try to clean up anyway, and continue
1263 stopGnssBatch();
1264 }
1265
1266 mGnssBatchingInProgress = true;
1267 return mGnssBatchingProvider.start(periodNanos, wakeOnFifoFull);
1268 }
1269
1270 /**
1271 * Flushes a GNSS batch in progress
1272 */
1273 @Override
1274 public void flushGnssBatch(String packageName) {
1275 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1276 "Location Hardware permission not granted to access hardware batching");
1277
1278 if (!hasGnssPermissions(packageName)) {
1279 Log.e(TAG, "flushGnssBatch called without GNSS permissions");
1280 return;
1281 }
1282
1283 if (!mGnssBatchingInProgress) {
1284 Log.w(TAG, "flushGnssBatch called with no batch in progress");
1285 }
1286
1287 if (mGnssBatchingProvider != null) {
gomo48f1a642017-11-10 20:35:46 -08001288 mGnssBatchingProvider.flush();
Wyatt Rileycf879db2017-01-12 13:57:38 -08001289 }
1290 }
1291
1292 /**
1293 * Stops GNSS batching
1294 */
1295 @Override
1296 public boolean stopGnssBatch() {
1297 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1298 "Location Hardware permission not granted to access hardware batching");
1299
1300 if (mGnssBatchingProvider != null) {
1301 mGnssBatchingInProgress = false;
1302 return mGnssBatchingProvider.stop();
gomo48f1a642017-11-10 20:35:46 -08001303 } else {
Wyatt Rileycf879db2017-01-12 13:57:38 -08001304 return false;
1305 }
1306 }
1307
1308 @Override
1309 public void reportLocationBatch(List<Location> locations) {
1310 checkCallerIsProvider();
1311
1312 // Currently used only for GNSS locations - update permissions check if changed
1313 if (isAllowedByCurrentUserSettingsLocked(LocationManager.GPS_PROVIDER)) {
1314 if (mGnssBatchingCallback == null) {
1315 Slog.e(TAG, "reportLocationBatch() called without active Callback");
1316 return;
1317 }
1318 try {
1319 mGnssBatchingCallback.onLocationBatch(locations);
1320 } catch (RemoteException e) {
1321 Slog.e(TAG, "mGnssBatchingCallback.onLocationBatch failed", e);
1322 }
1323 } else {
1324 Slog.w(TAG, "reportLocationBatch() called without user permission, locations blocked");
1325 }
1326 }
1327
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001328 private void addProviderLocked(LocationProviderInterface provider) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001329 mProviders.add(provider);
1330 mProvidersByName.put(provider.getName(), provider);
1331 }
1332
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001333 private void removeProviderLocked(LocationProviderInterface provider) {
1334 provider.disable();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001335 mProviders.remove(provider);
1336 mProvidersByName.remove(provider.getName());
1337 }
1338
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001339 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -08001340 * Returns "true" if access to the specified location provider is allowed by the current
1341 * user's settings. Access to all location providers is forbidden to non-location-provider
1342 * processes belonging to background users.
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001343 *
1344 * @param provider the name of the location provider
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001345 */
Victoria Lease09eeaec2013-02-05 11:34:13 -08001346 private boolean isAllowedByCurrentUserSettingsLocked(String provider) {
Maggie2a9409e2018-03-21 11:47:28 -07001347 return isAllowedByUserSettingsLockedForUser(provider, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 }
1349
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001350 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -08001351 * Returns "true" if access to the specified location provider is allowed by the specified
1352 * user's settings. Access to all location providers is forbidden to non-location-provider
1353 * processes belonging to background users.
1354 *
1355 * @param provider the name of the location provider
Maggie2a9409e2018-03-21 11:47:28 -07001356 * @param userId the user id to query
Victoria Lease09eeaec2013-02-05 11:34:13 -08001357 */
Maggie2a9409e2018-03-21 11:47:28 -07001358 private boolean isAllowedByUserSettingsLockedForUser(String provider, int userId) {
1359 if (mEnabledProviders.contains(provider)) {
1360 return true;
1361 }
1362 if (mDisabledProviders.contains(provider)) {
1363 return false;
1364 }
1365 return isLocationProviderEnabledForUser(provider, userId);
1366 }
1367
1368
1369 /**
1370 * Returns "true" if access to the specified location provider is allowed by the specified
1371 * user's settings. Access to all location providers is forbidden to non-location-provider
1372 * processes belonging to background users.
1373 *
1374 * @param provider the name of the location provider
1375 * @param uid the requestor's UID
1376 * @param userId the user id to query
1377 */
1378 private boolean isAllowedByUserSettingsLocked(String provider, int uid, int userId) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001379 if (!isCurrentProfile(UserHandle.getUserId(uid)) && !isUidALocationProvider(uid)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08001380 return false;
1381 }
Maggie2a9409e2018-03-21 11:47:28 -07001382 return isAllowedByUserSettingsLockedForUser(provider, userId);
Victoria Lease09eeaec2013-02-05 11:34:13 -08001383 }
1384
1385 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001386 * Returns the permission string associated with the specified resolution level.
1387 *
1388 * @param resolutionLevel the resolution level
1389 * @return the permission string
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001390 */
Victoria Lease37425c32012-10-16 16:08:48 -07001391 private String getResolutionPermission(int resolutionLevel) {
1392 switch (resolutionLevel) {
1393 case RESOLUTION_LEVEL_FINE:
1394 return android.Manifest.permission.ACCESS_FINE_LOCATION;
1395 case RESOLUTION_LEVEL_COARSE:
1396 return android.Manifest.permission.ACCESS_COARSE_LOCATION;
1397 default:
1398 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 }
Victoria Leaseda479c52012-10-15 15:24:16 -07001400 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001401
Victoria Leaseda479c52012-10-15 15:24:16 -07001402 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001403 * Returns the resolution level allowed to the given PID/UID pair.
1404 *
1405 * @param pid the PID
1406 * @param uid the UID
1407 * @return resolution level allowed to the pid/uid pair
Victoria Leaseda479c52012-10-15 15:24:16 -07001408 */
Victoria Lease37425c32012-10-16 16:08:48 -07001409 private int getAllowedResolutionLevel(int pid, int uid) {
1410 if (mContext.checkPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
Maggieaa080f92018-01-04 15:35:11 -08001411 pid, uid) == PERMISSION_GRANTED) {
Victoria Lease37425c32012-10-16 16:08:48 -07001412 return RESOLUTION_LEVEL_FINE;
1413 } else if (mContext.checkPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION,
Maggieaa080f92018-01-04 15:35:11 -08001414 pid, uid) == PERMISSION_GRANTED) {
Victoria Lease37425c32012-10-16 16:08:48 -07001415 return RESOLUTION_LEVEL_COARSE;
1416 } else {
1417 return RESOLUTION_LEVEL_NONE;
Victoria Leaseda479c52012-10-15 15:24:16 -07001418 }
Victoria Lease4fab68b2012-09-13 13:20:59 -07001419 }
1420
1421 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001422 * Returns the resolution level allowed to the caller
1423 *
1424 * @return resolution level allowed to caller
Victoria Lease4fab68b2012-09-13 13:20:59 -07001425 */
Victoria Lease37425c32012-10-16 16:08:48 -07001426 private int getCallerAllowedResolutionLevel() {
1427 return getAllowedResolutionLevel(Binder.getCallingPid(), Binder.getCallingUid());
1428 }
1429
1430 /**
1431 * Throw SecurityException if specified resolution level is insufficient to use geofences.
1432 *
1433 * @param allowedResolutionLevel resolution level allowed to caller
1434 */
1435 private void checkResolutionLevelIsSufficientForGeofenceUse(int allowedResolutionLevel) {
1436 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
Victoria Lease4fab68b2012-09-13 13:20:59 -07001437 throw new SecurityException("Geofence usage requires ACCESS_FINE_LOCATION permission");
1438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 }
1440
Victoria Lease37425c32012-10-16 16:08:48 -07001441 /**
1442 * Return the minimum resolution level required to use the specified location provider.
1443 *
1444 * @param provider the name of the location provider
1445 * @return minimum resolution level required for provider
1446 */
1447 private int getMinimumResolutionLevelForProviderUse(String provider) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001448 if (LocationManager.GPS_PROVIDER.equals(provider) ||
1449 LocationManager.PASSIVE_PROVIDER.equals(provider)) {
1450 // gps and passive providers require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001451 return RESOLUTION_LEVEL_FINE;
Victoria Lease8dbb6342012-09-21 16:55:53 -07001452 } else if (LocationManager.NETWORK_PROVIDER.equals(provider) ||
1453 LocationManager.FUSED_PROVIDER.equals(provider)) {
1454 // network and fused providers are ok with COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001455 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001456 } else {
1457 // mock providers
1458 LocationProviderInterface lp = mMockProviders.get(provider);
1459 if (lp != null) {
1460 ProviderProperties properties = lp.getProperties();
1461 if (properties != null) {
1462 if (properties.mRequiresSatellite) {
1463 // provider requiring satellites require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001464 return RESOLUTION_LEVEL_FINE;
Laurent Tu941221c2012-10-04 14:21:52 -07001465 } else if (properties.mRequiresNetwork || properties.mRequiresCell) {
1466 // provider requiring network and or cell require COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001467 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001468 }
1469 }
1470 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001471 }
Victoria Lease37425c32012-10-16 16:08:48 -07001472 return RESOLUTION_LEVEL_FINE; // if in doubt, require FINE
Victoria Leaseda479c52012-10-15 15:24:16 -07001473 }
1474
Victoria Lease37425c32012-10-16 16:08:48 -07001475 /**
1476 * Throw SecurityException if specified resolution level is insufficient to use the named
1477 * location provider.
1478 *
1479 * @param allowedResolutionLevel resolution level allowed to caller
gomo48f1a642017-11-10 20:35:46 -08001480 * @param providerName the name of the location provider
Victoria Lease37425c32012-10-16 16:08:48 -07001481 */
1482 private void checkResolutionLevelIsSufficientForProviderUse(int allowedResolutionLevel,
1483 String providerName) {
1484 int requiredResolutionLevel = getMinimumResolutionLevelForProviderUse(providerName);
1485 if (allowedResolutionLevel < requiredResolutionLevel) {
1486 switch (requiredResolutionLevel) {
1487 case RESOLUTION_LEVEL_FINE:
1488 throw new SecurityException("\"" + providerName + "\" location provider " +
1489 "requires ACCESS_FINE_LOCATION permission.");
1490 case RESOLUTION_LEVEL_COARSE:
1491 throw new SecurityException("\"" + providerName + "\" location provider " +
1492 "requires ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission.");
1493 default:
1494 throw new SecurityException("Insufficient permission for \"" + providerName +
1495 "\" location provider.");
Victoria Leaseda479c52012-10-15 15:24:16 -07001496 }
1497 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001498 }
1499
David Christie82edc9b2013-07-19 11:31:42 -07001500 /**
1501 * Throw SecurityException if WorkSource use is not allowed (i.e. can't blame other packages
1502 * for battery).
1503 */
David Christie40e57822013-07-30 11:36:48 -07001504 private void checkDeviceStatsAllowed() {
David Christie82edc9b2013-07-19 11:31:42 -07001505 mContext.enforceCallingOrSelfPermission(
1506 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
1507 }
1508
David Christie40e57822013-07-30 11:36:48 -07001509 private void checkUpdateAppOpsAllowed() {
1510 mContext.enforceCallingOrSelfPermission(
1511 android.Manifest.permission.UPDATE_APP_OPS_STATS, null);
1512 }
1513
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001514 public static int resolutionLevelToOp(int allowedResolutionLevel) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001515 if (allowedResolutionLevel != RESOLUTION_LEVEL_NONE) {
1516 if (allowedResolutionLevel == RESOLUTION_LEVEL_COARSE) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001517 return AppOpsManager.OP_COARSE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001518 } else {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001519 return AppOpsManager.OP_FINE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001520 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001521 }
1522 return -1;
1523 }
1524
David Christieb870dbf2015-06-22 12:42:53 -07001525 boolean reportLocationAccessNoThrow(
1526 int pid, int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001527 int op = resolutionLevelToOp(allowedResolutionLevel);
1528 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001529 if (mAppOps.noteOpNoThrow(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1530 return false;
1531 }
1532 }
David Christieb870dbf2015-06-22 12:42:53 -07001533
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001534 return getAllowedResolutionLevel(pid, uid) >= allowedResolutionLevel;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001535 }
1536
David Christieb870dbf2015-06-22 12:42:53 -07001537 boolean checkLocationAccess(int pid, int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001538 int op = resolutionLevelToOp(allowedResolutionLevel);
1539 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001540 if (mAppOps.checkOp(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1541 return false;
1542 }
1543 }
David Christieb870dbf2015-06-22 12:42:53 -07001544
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001545 return getAllowedResolutionLevel(pid, uid) >= allowedResolutionLevel;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001546 }
1547
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001548 /**
Maggie91e630c2018-01-24 17:31:46 -08001549 * Returns all providers by name, including passive and the ones that are not permitted to
1550 * be accessed by the calling activity or are currently disabled, but excluding fused.
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001551 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001552 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 public List<String> getAllProviders() {
Maggie91e630c2018-01-24 17:31:46 -08001554 ArrayList<String> out;
1555 synchronized (mLock) {
1556 out = new ArrayList<>(mProviders.size());
1557 for (LocationProviderInterface provider : mProviders) {
1558 String name = provider.getName();
1559 if (LocationManager.FUSED_PROVIDER.equals(name)) {
1560 continue;
1561 }
1562 out.add(name);
1563 }
1564 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001565 if (D) Log.d(TAG, "getAllProviders()=" + out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566 return out;
1567 }
1568
Mike Lockwood03ca2162010-04-01 08:10:09 -07001569 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001570 * Return all providers by name, that match criteria and are optionally
1571 * enabled.
1572 * Can return passive provider, but never returns fused provider.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001573 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001574 @Override
1575 public List<String> getProviders(Criteria criteria, boolean enabledOnly) {
Victoria Lease37425c32012-10-16 16:08:48 -07001576 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001577 ArrayList<String> out;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001578 int uid = Binder.getCallingUid();
Victoria Lease269518e2012-10-29 08:25:39 -07001579 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001580 try {
1581 synchronized (mLock) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001582 out = new ArrayList<>(mProviders.size());
Victoria Leaseb711d572012-10-02 13:14:11 -07001583 for (LocationProviderInterface provider : mProviders) {
1584 String name = provider.getName();
1585 if (LocationManager.FUSED_PROVIDER.equals(name)) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001586 continue;
1587 }
Victoria Lease37425c32012-10-16 16:08:48 -07001588 if (allowedResolutionLevel >= getMinimumResolutionLevelForProviderUse(name)) {
Maggie2a9409e2018-03-21 11:47:28 -07001589 if (enabledOnly
1590 && !isAllowedByUserSettingsLocked(name, uid, mCurrentUserId)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001591 continue;
1592 }
1593 if (criteria != null && !LocationProvider.propertiesMeetCriteria(
1594 name, provider.getProperties(), criteria)) {
1595 continue;
1596 }
1597 out.add(name);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001598 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001599 }
Mike Lockwood03ca2162010-04-01 08:10:09 -07001600 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001601 } finally {
1602 Binder.restoreCallingIdentity(identity);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001603 }
1604
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001605 if (D) Log.d(TAG, "getProviders()=" + out);
1606 return out;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001607 }
1608
1609 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001610 * Return the name of the best provider given a Criteria object.
1611 * This method has been deprecated from the public API,
Victoria Lease8dbb6342012-09-21 16:55:53 -07001612 * and the whole LocationProvider (including #meetsCriteria)
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001613 * has been deprecated as well. So this method now uses
1614 * some simplified logic.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001615 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001616 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001617 public String getBestProvider(Criteria criteria, boolean enabledOnly) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001618 String result = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001619
1620 List<String> providers = getProviders(criteria, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001621 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001622 result = pickBest(providers);
1623 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1624 return result;
1625 }
1626 providers = getProviders(null, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001627 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001628 result = pickBest(providers);
1629 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1630 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001631 }
1632
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001633 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001634 return null;
1635 }
1636
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001637 private String pickBest(List<String> providers) {
Victoria Lease1925e292012-09-24 17:00:18 -07001638 if (providers.contains(LocationManager.GPS_PROVIDER)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001639 return LocationManager.GPS_PROVIDER;
Victoria Lease1925e292012-09-24 17:00:18 -07001640 } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
1641 return LocationManager.NETWORK_PROVIDER;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001642 } else {
1643 return providers.get(0);
1644 }
1645 }
1646
Nick Pellye0fd6932012-07-11 10:26:13 -07001647 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001648 public boolean providerMeetsCriteria(String provider, Criteria criteria) {
1649 LocationProviderInterface p = mProvidersByName.get(provider);
1650 if (p == null) {
1651 throw new IllegalArgumentException("provider=" + provider);
1652 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001653
1654 boolean result = LocationProvider.propertiesMeetCriteria(
1655 p.getName(), p.getProperties(), criteria);
1656 if (D) Log.d(TAG, "providerMeetsCriteria(" + provider + ", " + criteria + ")=" + result);
1657 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001658 }
1659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 private void updateProvidersLocked() {
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001661 boolean changesMade = false;
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001662 for (int i = mProviders.size() - 1; i >= 0; i--) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001663 LocationProviderInterface p = mProviders.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 boolean isEnabled = p.isEnabled();
1665 String name = p.getName();
Victoria Lease09eeaec2013-02-05 11:34:13 -08001666 boolean shouldBeEnabled = isAllowedByCurrentUserSettingsLocked(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 if (isEnabled && !shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001668 updateProviderListenersLocked(name, false);
David Christieb084fef2013-12-18 14:33:57 -08001669 // If any provider has been disabled, clear all last locations for all providers.
1670 // This is to be on the safe side in case a provider has location derived from
1671 // this disabled provider.
1672 mLastLocation.clear();
1673 mLastLocationCoarseInterval.clear();
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001674 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 } else if (!isEnabled && shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001676 updateProviderListenersLocked(name, true);
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001677 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 }
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001679 }
1680 if (changesMade) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001681 mContext.sendBroadcastAsUser(new Intent(LocationManager.PROVIDERS_CHANGED_ACTION),
1682 UserHandle.ALL);
Tom O'Neill40a86c22013-09-03 18:05:13 -07001683 mContext.sendBroadcastAsUser(new Intent(LocationManager.MODE_CHANGED_ACTION),
1684 UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 }
1686 }
1687
Amith Yamasanib27528d2014-06-05 15:02:10 -07001688 private void updateProviderListenersLocked(String provider, boolean enabled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 int listeners = 0;
1690
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001691 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001692 if (p == null) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693
1694 ArrayList<Receiver> deadReceivers = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07001695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1697 if (records != null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001698 for (UpdateRecord record : records) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001699 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mIdentity.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001700 // Sends a notification message to the receiver
1701 if (!record.mReceiver.callProviderEnabledLocked(provider, enabled)) {
1702 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001703 deadReceivers = new ArrayList<>();
Victoria Leaseb711d572012-10-02 13:14:11 -07001704 }
1705 deadReceivers.add(record.mReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001707 listeners++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 }
1710 }
1711
1712 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001713 for (int i = deadReceivers.size() - 1; i >= 0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 removeUpdatesLocked(deadReceivers.get(i));
1715 }
1716 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 if (enabled) {
1719 p.enable();
1720 if (listeners > 0) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001721 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 }
1723 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 p.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 }
1727
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001728 private void applyRequirementsLocked(String provider) {
1729 LocationProviderInterface p = mProvidersByName.get(provider);
1730 if (p == null) return;
1731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001733 WorkSource worksource = new WorkSource();
1734 ProviderRequest providerRequest = new ProviderRequest();
1735
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001736 ContentResolver resolver = mContext.getContentResolver();
1737 long backgroundThrottleInterval = Settings.Global.getLong(
1738 resolver,
1739 Settings.Global.LOCATION_BACKGROUND_THROTTLE_INTERVAL_MS,
1740 DEFAULT_BACKGROUND_THROTTLE_INTERVAL_MS);
gomo48f1a642017-11-10 20:35:46 -08001741 // initialize the low power mode to true and set to false if any of the records requires
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001742
gomo48f1a642017-11-10 20:35:46 -08001743 providerRequest.lowPowerMode = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001744 if (records != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001745 for (UpdateRecord record : records) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001746 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mIdentity.mUid))) {
David Christieb870dbf2015-06-22 12:42:53 -07001747 if (checkLocationAccess(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001748 record.mReceiver.mIdentity.mPid,
1749 record.mReceiver.mIdentity.mUid,
1750 record.mReceiver.mIdentity.mPackageName,
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001751 record.mReceiver.mAllowedResolutionLevel)) {
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001752 LocationRequest locationRequest = record.mRealRequest;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001753 long interval = locationRequest.getInterval();
1754
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001755 if (!isThrottlingExemptLocked(record.mReceiver.mIdentity)) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001756 if (!record.mIsForegroundUid) {
1757 interval = Math.max(interval, backgroundThrottleInterval);
1758 }
1759 if (interval != locationRequest.getInterval()) {
1760 locationRequest = new LocationRequest(locationRequest);
1761 locationRequest.setInterval(interval);
1762 }
1763 }
1764
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001765 record.mRequest = locationRequest;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001766 providerRequest.locationRequests.add(locationRequest);
gomo48f1a642017-11-10 20:35:46 -08001767 if (!locationRequest.isLowPowerMode()) {
1768 providerRequest.lowPowerMode = false;
1769 }
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001770 if (interval < providerRequest.interval) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001771 providerRequest.reportLocation = true;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001772 providerRequest.interval = interval;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001773 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001774 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001775 }
1776 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001777
1778 if (providerRequest.reportLocation) {
1779 // calculate who to blame for power
1780 // This is somewhat arbitrary. We pick a threshold interval
1781 // that is slightly higher that the minimum interval, and
1782 // spread the blame across all applications with a request
1783 // under that threshold.
1784 long thresholdInterval = (providerRequest.interval + 1000) * 3 / 2;
1785 for (UpdateRecord record : records) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001786 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mIdentity.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001787 LocationRequest locationRequest = record.mRequest;
Svet Ganove998c732016-06-10 00:12:38 -07001788
1789 // Don't assign battery blame for update records whose
1790 // client has no permission to receive location data.
1791 if (!providerRequest.locationRequests.contains(locationRequest)) {
1792 continue;
1793 }
1794
Victoria Leaseb711d572012-10-02 13:14:11 -07001795 if (locationRequest.getInterval() <= thresholdInterval) {
David Christiee55c9682013-08-22 10:10:34 -07001796 if (record.mReceiver.mWorkSource != null
Narayan Kamath32684dd2018-01-08 17:32:51 +00001797 && isValidWorkSource(record.mReceiver.mWorkSource)) {
David Christie82edc9b2013-07-19 11:31:42 -07001798 worksource.add(record.mReceiver.mWorkSource);
1799 } else {
Narayan Kamath32684dd2018-01-08 17:32:51 +00001800 // Assign blame to caller if there's no WorkSource associated with
1801 // the request or if it's invalid.
David Christie82edc9b2013-07-19 11:31:42 -07001802 worksource.add(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001803 record.mReceiver.mIdentity.mUid,
1804 record.mReceiver.mIdentity.mPackageName);
David Christie82edc9b2013-07-19 11:31:42 -07001805 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001806 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001807 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 }
1810 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001811
1812 if (D) Log.d(TAG, "provider request: " + provider + " " + providerRequest);
1813 p.setRequest(providerRequest, worksource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 }
1815
Narayan Kamath32684dd2018-01-08 17:32:51 +00001816 /**
1817 * Whether a given {@code WorkSource} associated with a Location request is valid.
1818 */
1819 private static boolean isValidWorkSource(WorkSource workSource) {
1820 if (workSource.size() > 0) {
1821 // If the WorkSource has one or more non-chained UIDs, make sure they're accompanied
1822 // by tags.
1823 return workSource.getName(0) != null;
1824 } else {
1825 // For now, make sure callers have supplied an attribution tag for use with
1826 // AppOpsManager. This might be relaxed in the future.
1827 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
1828 return workChains != null && !workChains.isEmpty() &&
1829 workChains.get(0).getAttributionTag() != null;
1830 }
1831 }
1832
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001833 @Override
1834 public String[] getBackgroundThrottlingWhitelist() {
1835 synchronized (mLock) {
1836 return mBackgroundThrottlePackageWhitelist.toArray(
gomo48f1a642017-11-10 20:35:46 -08001837 new String[mBackgroundThrottlePackageWhitelist.size()]);
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001838 }
1839 }
1840
1841 private void updateBackgroundThrottlingWhitelistLocked() {
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001842 String setting = Settings.Global.getString(
gomo48f1a642017-11-10 20:35:46 -08001843 mContext.getContentResolver(),
1844 Settings.Global.LOCATION_BACKGROUND_THROTTLE_PACKAGE_WHITELIST);
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001845 if (setting == null) {
1846 setting = "";
1847 }
1848
1849 mBackgroundThrottlePackageWhitelist.clear();
1850 mBackgroundThrottlePackageWhitelist.addAll(
gomo48f1a642017-11-10 20:35:46 -08001851 SystemConfig.getInstance().getAllowUnthrottledLocation());
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001852 mBackgroundThrottlePackageWhitelist.addAll(
gomo48f1a642017-11-10 20:35:46 -08001853 Arrays.asList(setting.split(",")));
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001854 }
1855
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001856 private boolean isThrottlingExemptLocked(Identity identity) {
1857 if (identity.mUid == Process.SYSTEM_UID) {
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001858 return true;
1859 }
1860
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001861 if (mBackgroundThrottlePackageWhitelist.contains(identity.mPackageName)) {
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001862 return true;
1863 }
1864
1865 for (LocationProviderProxy provider : mProxyProviders) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001866 if (identity.mPackageName.equals(provider.getConnectedPackageName())) {
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001867 return true;
1868 }
1869 }
1870
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001871 return false;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001872 }
1873
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001874 private class UpdateRecord {
1875 final String mProvider;
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001876 final LocationRequest mRealRequest; // original request from client
1877 LocationRequest mRequest; // possibly throttled version of the request
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 final Receiver mReceiver;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001879 boolean mIsForegroundUid;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001880 Location mLastFixBroadcast;
1881 long mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882
1883 /**
1884 * Note: must be constructed with lock held.
1885 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001886 UpdateRecord(String provider, LocationRequest request, Receiver receiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 mProvider = provider;
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001888 mRealRequest = request;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001889 mRequest = request;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 mReceiver = receiver;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001891 mIsForegroundUid = isImportanceForeground(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001892 mActivityManager.getPackageImportance(mReceiver.mIdentity.mPackageName));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893
1894 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1895 if (records == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001896 records = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001897 mRecordsByProvider.put(provider, records);
1898 }
1899 if (!records.contains(this)) {
1900 records.add(this);
1901 }
David Christie2ff96af2014-01-30 16:09:37 -08001902
1903 // Update statistics for historical location requests by package/provider
1904 mRequestStatistics.startRequesting(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001905 mReceiver.mIdentity.mPackageName, provider, request.getInterval());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 }
1907
1908 /**
David Christie2ff96af2014-01-30 16:09:37 -08001909 * Method to be called when a record will no longer be used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001911 void disposeLocked(boolean removeReceiver) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001912 mRequestStatistics.stopRequesting(mReceiver.mIdentity.mPackageName, mProvider);
David Christie2ff96af2014-01-30 16:09:37 -08001913
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001914 // remove from mRecordsByProvider
1915 ArrayList<UpdateRecord> globalRecords = mRecordsByProvider.get(this.mProvider);
1916 if (globalRecords != null) {
1917 globalRecords.remove(this);
1918 }
1919
1920 if (!removeReceiver) return; // the caller will handle the rest
1921
1922 // remove from Receiver#mUpdateRecords
1923 HashMap<String, UpdateRecord> receiverRecords = mReceiver.mUpdateRecords;
1924 if (receiverRecords != null) {
1925 receiverRecords.remove(this.mProvider);
1926
1927 // and also remove the Receiver if it has no more update records
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001928 if (receiverRecords.size() == 0) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001929 removeUpdatesLocked(mReceiver);
1930 }
Mike Lockwood3a76fd62009-09-01 07:26:56 -04001931 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 }
1933
1934 @Override
1935 public String toString() {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001936 return "UpdateRecord[" + mProvider + " " + mReceiver.mIdentity.mPackageName
gomo48f1a642017-11-10 20:35:46 -08001937 + "(" + mReceiver.mIdentity.mUid + (mIsForegroundUid ? " foreground"
1938 : " background")
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001939 + ")" + " " + mRealRequest + "]";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 }
1942
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001943 private Receiver getReceiverLocked(ILocationListener listener, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -07001944 String packageName, WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001945 IBinder binder = listener.asBinder();
1946 Receiver receiver = mReceivers.get(binder);
1947 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07001948 receiver = new Receiver(listener, null, pid, uid, packageName, workSource,
1949 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001950 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001951 receiver.getListener().asBinder().linkToDeath(receiver, 0);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001952 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001953 Slog.e(TAG, "linkToDeath failed:", e);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001954 return null;
1955 }
Wen Jingcb3ab222014-03-27 13:42:59 +08001956 mReceivers.put(binder, receiver);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001957 }
1958 return receiver;
1959 }
1960
David Christie82edc9b2013-07-19 11:31:42 -07001961 private Receiver getReceiverLocked(PendingIntent intent, int pid, int uid, String packageName,
David Christie40e57822013-07-30 11:36:48 -07001962 WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001963 Receiver receiver = mReceivers.get(intent);
1964 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07001965 receiver = new Receiver(null, intent, pid, uid, packageName, workSource,
1966 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001967 mReceivers.put(intent, receiver);
1968 }
1969 return receiver;
1970 }
1971
Victoria Lease37425c32012-10-16 16:08:48 -07001972 /**
1973 * Creates a LocationRequest based upon the supplied LocationRequest that to meets resolution
1974 * and consistency requirements.
1975 *
1976 * @param request the LocationRequest from which to create a sanitized version
Victoria Lease37425c32012-10-16 16:08:48 -07001977 * @return a version of request that meets the given resolution and consistency requirements
1978 * @hide
1979 */
gomo48f1a642017-11-10 20:35:46 -08001980 private LocationRequest createSanitizedRequest(LocationRequest request, int resolutionLevel,
1981 boolean callerHasLocationHardwarePermission) {
Victoria Lease37425c32012-10-16 16:08:48 -07001982 LocationRequest sanitizedRequest = new LocationRequest(request);
gomo48f1a642017-11-10 20:35:46 -08001983 if (!callerHasLocationHardwarePermission) {
1984 // allow setting low power mode only for callers with location hardware permission
1985 sanitizedRequest.setLowPowerMode(false);
1986 }
Victoria Lease37425c32012-10-16 16:08:48 -07001987 if (resolutionLevel < RESOLUTION_LEVEL_FINE) {
1988 switch (sanitizedRequest.getQuality()) {
Victoria Lease09016ab2012-09-16 12:33:15 -07001989 case LocationRequest.ACCURACY_FINE:
Victoria Lease37425c32012-10-16 16:08:48 -07001990 sanitizedRequest.setQuality(LocationRequest.ACCURACY_BLOCK);
Victoria Lease09016ab2012-09-16 12:33:15 -07001991 break;
1992 case LocationRequest.POWER_HIGH:
Victoria Lease37425c32012-10-16 16:08:48 -07001993 sanitizedRequest.setQuality(LocationRequest.POWER_LOW);
Victoria Lease09016ab2012-09-16 12:33:15 -07001994 break;
1995 }
1996 // throttle
Victoria Lease37425c32012-10-16 16:08:48 -07001997 if (sanitizedRequest.getInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
1998 sanitizedRequest.setInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07001999 }
Victoria Lease37425c32012-10-16 16:08:48 -07002000 if (sanitizedRequest.getFastestInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
2001 sanitizedRequest.setFastestInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07002002 }
Nick Pelly74fa7ea2012-08-13 19:36:38 -07002003 }
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002004 // make getFastestInterval() the minimum of interval and fastest interval
Victoria Lease37425c32012-10-16 16:08:48 -07002005 if (sanitizedRequest.getFastestInterval() > sanitizedRequest.getInterval()) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002006 request.setFastestInterval(request.getInterval());
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002007 }
Victoria Lease37425c32012-10-16 16:08:48 -07002008 return sanitizedRequest;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002009 }
2010
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002011 private void checkPackageName(String packageName) {
Nick Pellye0fd6932012-07-11 10:26:13 -07002012 if (packageName == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002013 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07002014 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002015 int uid = Binder.getCallingUid();
Nick Pellye0fd6932012-07-11 10:26:13 -07002016 String[] packages = mPackageManager.getPackagesForUid(uid);
2017 if (packages == null) {
2018 throw new SecurityException("invalid UID " + uid);
2019 }
2020 for (String pkg : packages) {
2021 if (packageName.equals(pkg)) return;
2022 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002023 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07002024 }
2025
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002026 private void checkPendingIntent(PendingIntent intent) {
2027 if (intent == null) {
2028 throw new IllegalArgumentException("invalid pending intent: " + intent);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002029 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002030 }
2031
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002032 private Receiver checkListenerOrIntentLocked(ILocationListener listener, PendingIntent intent,
David Christie40e57822013-07-30 11:36:48 -07002033 int pid, int uid, String packageName, WorkSource workSource, boolean hideFromAppOps) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002034 if (intent == null && listener == null) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002035 throw new IllegalArgumentException("need either listener or intent");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002036 } else if (intent != null && listener != null) {
2037 throw new IllegalArgumentException("cannot register both listener and intent");
2038 } else if (intent != null) {
2039 checkPendingIntent(intent);
David Christie40e57822013-07-30 11:36:48 -07002040 return getReceiverLocked(intent, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002041 } else {
David Christie40e57822013-07-30 11:36:48 -07002042 return getReceiverLocked(listener, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002043 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002044 }
2045
Nick Pellye0fd6932012-07-11 10:26:13 -07002046 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002047 public void requestLocationUpdates(LocationRequest request, ILocationListener listener,
2048 PendingIntent intent, String packageName) {
2049 if (request == null) request = DEFAULT_LOCATION_REQUEST;
2050 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002051 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
2052 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
2053 request.getProvider());
David Christie82edc9b2013-07-19 11:31:42 -07002054 WorkSource workSource = request.getWorkSource();
Narayan Kamath32684dd2018-01-08 17:32:51 +00002055 if (workSource != null && !workSource.isEmpty()) {
David Christie40e57822013-07-30 11:36:48 -07002056 checkDeviceStatsAllowed();
2057 }
2058 boolean hideFromAppOps = request.getHideFromAppOps();
2059 if (hideFromAppOps) {
2060 checkUpdateAppOpsAllowed();
David Christie82edc9b2013-07-19 11:31:42 -07002061 }
gomo48f1a642017-11-10 20:35:46 -08002062 boolean callerHasLocationHardwarePermission =
2063 mContext.checkCallingPermission(android.Manifest.permission.LOCATION_HARDWARE)
Maggieaa080f92018-01-04 15:35:11 -08002064 == PERMISSION_GRANTED;
gomo48f1a642017-11-10 20:35:46 -08002065 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel,
2066 callerHasLocationHardwarePermission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002067
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002068 final int pid = Binder.getCallingPid();
2069 final int uid = Binder.getCallingUid();
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002070 // providers may use public location API's, need to clear identity
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 long identity = Binder.clearCallingIdentity();
2072 try {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002073 // We don't check for MODE_IGNORED here; we will do that when we go to deliver
2074 // a location.
David Christieb870dbf2015-06-22 12:42:53 -07002075 checkLocationAccess(pid, uid, packageName, allowedResolutionLevel);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002076
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002077 synchronized (mLock) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002078 Receiver recevier = checkListenerOrIntentLocked(listener, intent, pid, uid,
David Christie40e57822013-07-30 11:36:48 -07002079 packageName, workSource, hideFromAppOps);
Victoria Lease37425c32012-10-16 16:08:48 -07002080 requestLocationUpdatesLocked(sanitizedRequest, recevier, pid, uid, packageName);
Mike Lockwood2d4d1bf2010-10-18 17:06:26 -04002081 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002082 } finally {
2083 Binder.restoreCallingIdentity(identity);
2084 }
2085 }
2086
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002087 private void requestLocationUpdatesLocked(LocationRequest request, Receiver receiver,
2088 int pid, int uid, String packageName) {
2089 // Figure out the provider. Either its explicitly request (legacy use cases), or
2090 // use the fused provider
2091 if (request == null) request = DEFAULT_LOCATION_REQUEST;
2092 String name = request.getProvider();
Victoria Lease09016ab2012-09-16 12:33:15 -07002093 if (name == null) {
2094 throw new IllegalArgumentException("provider name must not be null");
2095 }
Zhentao Sunc5fc9982013-04-17 17:47:53 -07002096
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002097 LocationProviderInterface provider = mProvidersByName.get(name);
2098 if (provider == null) {
Victoria Leaseb30f3832013-10-13 12:15:40 -07002099 throw new IllegalArgumentException("provider doesn't exist: " + name);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002100 }
2101
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002102 UpdateRecord record = new UpdateRecord(name, request, receiver);
gomo48f1a642017-11-10 20:35:46 -08002103 if (D) {
2104 Log.d(TAG, "request " + Integer.toHexString(System.identityHashCode(receiver))
2105 + " " + name + " " + request + " from " + packageName + "(" + uid + " "
2106 + (record.mIsForegroundUid ? "foreground" : "background")
2107 + (isThrottlingExemptLocked(receiver.mIdentity)
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002108 ? " [whitelisted]" : "") + ")");
gomo48f1a642017-11-10 20:35:46 -08002109 }
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002110
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002111 UpdateRecord oldRecord = receiver.mUpdateRecords.put(name, record);
2112 if (oldRecord != null) {
2113 oldRecord.disposeLocked(false);
2114 }
2115
Maggie2a9409e2018-03-21 11:47:28 -07002116 boolean isProviderEnabled = isAllowedByUserSettingsLocked(name, uid, mCurrentUserId);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002117 if (isProviderEnabled) {
2118 applyRequirementsLocked(name);
2119 } else {
2120 // Notify the listener that updates are currently disabled
2121 receiver.callProviderEnabledLocked(name, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002122 }
David Christie0b837452013-07-29 16:02:13 -07002123 // Update the monitoring here just in case multiple location requests were added to the
2124 // same receiver (this request may be high power and the initial might not have been).
2125 receiver.updateMonitoring(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 }
2127
Nick Pellye0fd6932012-07-11 10:26:13 -07002128 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002129 public void removeUpdates(ILocationListener listener, PendingIntent intent,
2130 String packageName) {
2131 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002132
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002133 final int pid = Binder.getCallingPid();
2134 final int uid = Binder.getCallingUid();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002135
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002136 synchronized (mLock) {
David Christie82edc9b2013-07-19 11:31:42 -07002137 WorkSource workSource = null;
David Christie40e57822013-07-30 11:36:48 -07002138 boolean hideFromAppOps = false;
2139 Receiver receiver = checkListenerOrIntentLocked(listener, intent, pid, uid,
2140 packageName, workSource, hideFromAppOps);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002141
2142 // providers may use public location API's, need to clear identity
2143 long identity = Binder.clearCallingIdentity();
2144 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002145 removeUpdatesLocked(receiver);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002146 } finally {
2147 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002149 }
2150 }
2151
2152 private void removeUpdatesLocked(Receiver receiver) {
Dianne Hackborn7ff30112012-11-08 11:12:09 -08002153 if (D) Log.i(TAG, "remove " + Integer.toHexString(System.identityHashCode(receiver)));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002154
2155 if (mReceivers.remove(receiver.mKey) != null && receiver.isListener()) {
2156 receiver.getListener().asBinder().unlinkToDeath(receiver, 0);
2157 synchronized (receiver) {
Victoria Lease0aa28602013-05-29 15:28:26 -07002158 receiver.clearPendingBroadcastsLocked();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002160 }
2161
Dianne Hackborn1304f4a2013-07-09 18:17:27 -07002162 receiver.updateMonitoring(false);
2163
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002164 // Record which providers were associated with this listener
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002165 HashSet<String> providers = new HashSet<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002166 HashMap<String, UpdateRecord> oldRecords = receiver.mUpdateRecords;
2167 if (oldRecords != null) {
2168 // Call dispose() on the obsolete update records.
2169 for (UpdateRecord record : oldRecords.values()) {
David Christie2ff96af2014-01-30 16:09:37 -08002170 // Update statistics for historical location requests by package/provider
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002171 record.disposeLocked(false);
2172 }
2173 // Accumulate providers
2174 providers.addAll(oldRecords.keySet());
2175 }
2176
2177 // update provider
2178 for (String provider : providers) {
2179 // If provider is already disabled, don't need to do anything
Victoria Lease09eeaec2013-02-05 11:34:13 -08002180 if (!isAllowedByCurrentUserSettingsLocked(provider)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002181 continue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002182 }
2183
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002184 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002185 }
2186 }
2187
Dianne Hackbornc2293022013-02-06 23:14:49 -08002188 private void applyAllProviderRequirementsLocked() {
2189 for (LocationProviderInterface p : mProviders) {
2190 // If provider is already disabled, don't need to do anything
Dianne Hackborn64d41d72013-02-07 00:33:31 -08002191 if (!isAllowedByCurrentUserSettingsLocked(p.getName())) {
Dianne Hackbornc2293022013-02-06 23:14:49 -08002192 continue;
2193 }
2194
2195 applyRequirementsLocked(p.getName());
2196 }
2197 }
2198
Nick Pellye0fd6932012-07-11 10:26:13 -07002199 @Override
Nick Pelly4035f5a2012-08-17 14:43:49 -07002200 public Location getLastLocation(LocationRequest request, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002201 if (D) Log.d(TAG, "getLastLocation: " + request);
2202 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07002203 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly4035f5a2012-08-17 14:43:49 -07002204 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002205 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
2206 request.getProvider());
2207 // no need to sanitize this request, as only the provider name is used
Nick Pelly4035f5a2012-08-17 14:43:49 -07002208
David Christieb870dbf2015-06-22 12:42:53 -07002209 final int pid = Binder.getCallingPid();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002210 final int uid = Binder.getCallingUid();
2211 final long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07002212 try {
2213 if (mBlacklist.isBlacklisted(packageName)) {
gomo48f1a642017-11-10 20:35:46 -08002214 if (D) {
2215 Log.d(TAG, "not returning last loc for blacklisted app: " +
2216 packageName);
2217 }
Victoria Lease09016ab2012-09-16 12:33:15 -07002218 return null;
2219 }
Victoria Leaseb711d572012-10-02 13:14:11 -07002220
David Christieb870dbf2015-06-22 12:42:53 -07002221 if (!reportLocationAccessNoThrow(pid, uid, packageName, allowedResolutionLevel)) {
gomo48f1a642017-11-10 20:35:46 -08002222 if (D) {
2223 Log.d(TAG, "not returning last loc for no op app: " +
2224 packageName);
2225 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002226 return null;
2227 }
2228
Victoria Leaseb711d572012-10-02 13:14:11 -07002229 synchronized (mLock) {
2230 // Figure out the provider. Either its explicitly request (deprecated API's),
2231 // or use the fused provider
2232 String name = request.getProvider();
2233 if (name == null) name = LocationManager.FUSED_PROVIDER;
2234 LocationProviderInterface provider = mProvidersByName.get(name);
2235 if (provider == null) return null;
2236
Maggie2a9409e2018-03-21 11:47:28 -07002237 if (!isAllowedByUserSettingsLocked(name, uid, mCurrentUserId)) return null;
Victoria Leaseb711d572012-10-02 13:14:11 -07002238
David Christie1b9b7b12013-04-15 15:31:11 -07002239 Location location;
2240 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
2241 // Make sure that an app with coarse permissions can't get frequent location
2242 // updates by calling LocationManager.getLastKnownLocation repeatedly.
2243 location = mLastLocationCoarseInterval.get(name);
2244 } else {
2245 location = mLastLocation.get(name);
2246 }
Victoria Leaseb711d572012-10-02 13:14:11 -07002247 if (location == null) {
2248 return null;
2249 }
Victoria Lease37425c32012-10-16 16:08:48 -07002250 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
gomo48f1a642017-11-10 20:35:46 -08002251 Location noGPSLocation = location.getExtraLocation(
2252 Location.EXTRA_NO_GPS_LOCATION);
Victoria Leaseb711d572012-10-02 13:14:11 -07002253 if (noGPSLocation != null) {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08002254 return new Location(mLocationFudger.getOrCreate(noGPSLocation));
Victoria Leaseb711d572012-10-02 13:14:11 -07002255 }
Victoria Lease37425c32012-10-16 16:08:48 -07002256 } else {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08002257 return new Location(location);
Victoria Lease09016ab2012-09-16 12:33:15 -07002258 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002259 }
Victoria Leaseb711d572012-10-02 13:14:11 -07002260 return null;
2261 } finally {
2262 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002263 }
2264 }
2265
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002266 /**
2267 * Provides an interface to inject and set the last location if location is not available
2268 * currently.
2269 *
2270 * This helps in cases where the product (Cars for example) has saved the last known location
2271 * before powering off. This interface lets the client inject the saved location while the GPS
2272 * chipset is getting its first fix, there by improving user experience.
2273 *
2274 * @param location - Location object to inject
2275 * @return true if update was successful, false if not
2276 */
2277 @Override
2278 public boolean injectLocation(Location location) {
2279 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
2280 "Location Hardware permission not granted to inject location");
2281 mContext.enforceCallingPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
2282 "Access Fine Location permission not granted to inject Location");
2283
2284 if (location == null) {
2285 if (D) {
2286 Log.d(TAG, "injectLocation(): called with null location");
2287 }
2288 return false;
2289 }
2290 LocationProviderInterface p = null;
2291 String provider = location.getProvider();
2292 if (provider != null) {
2293 p = mProvidersByName.get(provider);
2294 }
2295 if (p == null) {
2296 if (D) {
2297 Log.d(TAG, "injectLocation(): unknown provider");
2298 }
2299 return false;
2300 }
2301 synchronized (mLock) {
2302 if (!isAllowedByCurrentUserSettingsLocked(provider)) {
2303 if (D) {
2304 Log.d(TAG, "Location disabled in Settings for current user:" + mCurrentUserId);
2305 }
2306 return false;
2307 } else {
2308 // NOTE: If last location is already available, location is not injected. If
2309 // provider's normal source (like a GPS chipset) have already provided an output,
2310 // there is no need to inject this location.
2311 if (mLastLocation.get(provider) == null) {
2312 updateLastLocationLocked(location, provider);
2313 } else {
2314 if (D) {
2315 Log.d(TAG, "injectLocation(): Location exists. Not updating");
2316 }
2317 return false;
2318 }
2319 }
2320 }
2321 return true;
2322 }
2323
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002324 @Override
2325 public void requestGeofence(LocationRequest request, Geofence geofence, PendingIntent intent,
2326 String packageName) {
2327 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07002328 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
2329 checkResolutionLevelIsSufficientForGeofenceUse(allowedResolutionLevel);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002330 checkPendingIntent(intent);
2331 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002332 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
2333 request.getProvider());
gomo48f1a642017-11-10 20:35:46 -08002334 // Require that caller can manage given document
2335 boolean callerHasLocationHardwarePermission =
2336 mContext.checkCallingPermission(android.Manifest.permission.LOCATION_HARDWARE)
Maggieaa080f92018-01-04 15:35:11 -08002337 == PERMISSION_GRANTED;
gomo48f1a642017-11-10 20:35:46 -08002338 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel,
2339 callerHasLocationHardwarePermission);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002340
Victoria Lease37425c32012-10-16 16:08:48 -07002341 if (D) Log.d(TAG, "requestGeofence: " + sanitizedRequest + " " + geofence + " " + intent);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002342
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002343 // geo-fence manager uses the public location API, need to clear identity
2344 int uid = Binder.getCallingUid();
Xiaohui Chena4490622015-09-22 15:29:31 -07002345 // TODO: http://b/23822629
2346 if (UserHandle.getUserId(uid) != UserHandle.USER_SYSTEM) {
Victoria Lease56e675b2012-11-05 19:25:06 -08002347 // temporary measure until geofences work for secondary users
2348 Log.w(TAG, "proximity alerts are currently available only to the primary user");
2349 return;
2350 }
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002351 long identity = Binder.clearCallingIdentity();
2352 try {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002353 mGeofenceManager.addFence(sanitizedRequest, geofence, intent, allowedResolutionLevel,
2354 uid, packageName);
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002355 } finally {
2356 Binder.restoreCallingIdentity(identity);
2357 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002358 }
2359
2360 @Override
2361 public void removeGeofence(Geofence geofence, PendingIntent intent, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002362 checkPendingIntent(intent);
2363 checkPackageName(packageName);
2364
2365 if (D) Log.d(TAG, "removeGeofence: " + geofence + " " + intent);
2366
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002367 // geo-fence manager uses the public location API, need to clear identity
2368 long identity = Binder.clearCallingIdentity();
2369 try {
2370 mGeofenceManager.removeFence(geofence, intent);
2371 } finally {
2372 Binder.restoreCallingIdentity(identity);
2373 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002374 }
2375
2376
2377 @Override
Lifu Tang30f95a72016-01-07 23:20:38 -08002378 public boolean registerGnssStatusCallback(IGnssStatusListener callback, String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002379 if (!hasGnssPermissions(packageName) || mGnssStatusProvider == null) {
Takayuki Hoshib254ab6a2014-10-23 16:46:02 +09002380 return false;
2381 }
2382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002383 try {
Lifu Tang30f95a72016-01-07 23:20:38 -08002384 mGnssStatusProvider.registerGnssStatusCallback(callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002385 } catch (RemoteException e) {
Lifu Tang30f95a72016-01-07 23:20:38 -08002386 Slog.e(TAG, "mGpsStatusProvider.registerGnssStatusCallback failed", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002387 return false;
2388 }
2389 return true;
2390 }
2391
Nick Pellye0fd6932012-07-11 10:26:13 -07002392 @Override
Lifu Tang30f95a72016-01-07 23:20:38 -08002393 public void unregisterGnssStatusCallback(IGnssStatusListener callback) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002394 synchronized (mLock) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002395 try {
Lifu Tang30f95a72016-01-07 23:20:38 -08002396 mGnssStatusProvider.unregisterGnssStatusCallback(callback);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002397 } catch (Exception e) {
Lifu Tang30f95a72016-01-07 23:20:38 -08002398 Slog.e(TAG, "mGpsStatusProvider.unregisterGnssStatusCallback failed", e);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002399 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002400 }
2401 }
2402
Nick Pellye0fd6932012-07-11 10:26:13 -07002403 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002404 public boolean addGnssMeasurementsListener(
gomo48f1a642017-11-10 20:35:46 -08002405 IGnssMeasurementsListener listener, String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002406 if (!hasGnssPermissions(packageName) || mGnssMeasurementsProvider == null) {
destradaaea8a8a62014-06-23 18:19:03 -07002407 return false;
2408 }
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002409
2410 synchronized (mLock) {
2411 Identity callerIdentity
2412 = new Identity(Binder.getCallingUid(), Binder.getCallingPid(), packageName);
Wyatt Riley11cc7492018-01-17 08:48:27 -08002413 mGnssMeasurementsListeners.put(listener.asBinder(), callerIdentity);
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002414 long identity = Binder.clearCallingIdentity();
2415 try {
2416 if (isThrottlingExemptLocked(callerIdentity)
2417 || isImportanceForeground(
gomo48f1a642017-11-10 20:35:46 -08002418 mActivityManager.getPackageImportance(packageName))) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002419 return mGnssMeasurementsProvider.addListener(listener);
2420 }
2421 } finally {
2422 Binder.restoreCallingIdentity(identity);
2423 }
2424
2425 return true;
2426 }
destradaaea8a8a62014-06-23 18:19:03 -07002427 }
2428
2429 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002430 public void removeGnssMeasurementsListener(IGnssMeasurementsListener listener) {
2431 if (mGnssMeasurementsProvider != null) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002432 synchronized (mLock) {
Wyatt Riley11cc7492018-01-17 08:48:27 -08002433 mGnssMeasurementsListeners.remove(listener.asBinder());
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002434 mGnssMeasurementsProvider.removeListener(listener);
2435 }
Wei Liu5241a4c2015-05-11 14:00:36 -07002436 }
destradaaea8a8a62014-06-23 18:19:03 -07002437 }
2438
2439 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002440 public boolean addGnssNavigationMessageListener(
2441 IGnssNavigationMessageListener listener,
destradaa4b3e3932014-07-21 18:01:47 -07002442 String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002443 if (!hasGnssPermissions(packageName) || mGnssNavigationMessageProvider == null) {
destradaa4b3e3932014-07-21 18:01:47 -07002444 return false;
2445 }
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002446
2447 synchronized (mLock) {
2448 Identity callerIdentity
gomo48f1a642017-11-10 20:35:46 -08002449 = new Identity(Binder.getCallingUid(), Binder.getCallingPid(), packageName);
Wyatt Riley11cc7492018-01-17 08:48:27 -08002450 mGnssNavigationMessageListeners.put(listener.asBinder(), callerIdentity);
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002451 long identity = Binder.clearCallingIdentity();
2452 try {
2453 if (isThrottlingExemptLocked(callerIdentity)
2454 || isImportanceForeground(
gomo48f1a642017-11-10 20:35:46 -08002455 mActivityManager.getPackageImportance(packageName))) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002456 return mGnssNavigationMessageProvider.addListener(listener);
2457 }
2458 } finally {
2459 Binder.restoreCallingIdentity(identity);
2460 }
2461
2462 return true;
2463 }
destradaa4b3e3932014-07-21 18:01:47 -07002464 }
2465
2466 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002467 public void removeGnssNavigationMessageListener(IGnssNavigationMessageListener listener) {
2468 if (mGnssNavigationMessageProvider != null) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002469 synchronized (mLock) {
Wyatt Riley11cc7492018-01-17 08:48:27 -08002470 mGnssNavigationMessageListeners.remove(listener.asBinder());
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002471 mGnssNavigationMessageProvider.removeListener(listener);
2472 }
Wei Liu5241a4c2015-05-11 14:00:36 -07002473 }
destradaa4b3e3932014-07-21 18:01:47 -07002474 }
2475
2476 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002477 public boolean sendExtraCommand(String provider, String command, Bundle extras) {
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04002478 if (provider == null) {
2479 // throw NullPointerException to remain compatible with previous implementation
2480 throw new NullPointerException();
2481 }
Victoria Lease37425c32012-10-16 16:08:48 -07002482 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
2483 provider);
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04002484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002485 // and check for ACCESS_LOCATION_EXTRA_COMMANDS
Mike Lockwoodb7e99222009-07-07 13:18:21 -04002486 if ((mContext.checkCallingOrSelfPermission(ACCESS_LOCATION_EXTRA_COMMANDS)
Maggieaa080f92018-01-04 15:35:11 -08002487 != PERMISSION_GRANTED)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 throw new SecurityException("Requires ACCESS_LOCATION_EXTRA_COMMANDS permission");
2489 }
2490
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002491 synchronized (mLock) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002492 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002493 if (p == null) return false;
Nick Pellye0fd6932012-07-11 10:26:13 -07002494
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002495 return p.sendExtraCommand(command, extras);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002496 }
2497 }
2498
Nick Pellye0fd6932012-07-11 10:26:13 -07002499 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002500 public boolean sendNiResponse(int notifId, int userResponse) {
Mike Lockwood18ad9f62009-08-27 14:01:23 -07002501 if (Binder.getCallingUid() != Process.myUid()) {
2502 throw new SecurityException(
2503 "calling sendNiResponse from outside of the system is not allowed");
2504 }
Danke Xie22d1f9f2009-08-18 18:28:45 -04002505 try {
2506 return mNetInitiatedListener.sendNiResponse(notifId, userResponse);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002507 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002508 Slog.e(TAG, "RemoteException in LocationManagerService.sendNiResponse");
Danke Xie22d1f9f2009-08-18 18:28:45 -04002509 return false;
2510 }
2511 }
2512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002513 /**
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002514 * @return null if the provider does not exist
Alexey Tarasovf2db9fb2009-09-01 02:37:07 +11002515 * @throws SecurityException if the provider is not allowed to be
gomo48f1a642017-11-10 20:35:46 -08002516 * accessed by the caller
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517 */
Nick Pellye0fd6932012-07-11 10:26:13 -07002518 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002519 public ProviderProperties getProviderProperties(String provider) {
Laurent Tub7f9d252012-10-16 14:25:00 -07002520 if (mProvidersByName.get(provider) == null) {
David Christie2ff96af2014-01-30 16:09:37 -08002521 return null;
Laurent Tub7f9d252012-10-16 14:25:00 -07002522 }
2523
Victoria Lease37425c32012-10-16 16:08:48 -07002524 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
2525 provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002526
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002527 LocationProviderInterface p;
2528 synchronized (mLock) {
2529 p = mProvidersByName.get(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002530 }
2531
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002532 if (p == null) return null;
2533 return p.getProperties();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 }
2535
Jason Monkb71218a2015-06-17 14:44:39 -04002536 /**
2537 * @return null if the provider does not exist
2538 * @throws SecurityException if the provider is not allowed to be
gomo48f1a642017-11-10 20:35:46 -08002539 * accessed by the caller
Jason Monkb71218a2015-06-17 14:44:39 -04002540 */
2541 @Override
2542 public String getNetworkProviderPackage() {
2543 LocationProviderInterface p;
2544 synchronized (mLock) {
2545 if (mProvidersByName.get(LocationManager.NETWORK_PROVIDER) == null) {
2546 return null;
2547 }
2548 p = mProvidersByName.get(LocationManager.NETWORK_PROVIDER);
2549 }
2550
2551 if (p instanceof LocationProviderProxy) {
2552 return ((LocationProviderProxy) p).getConnectedPackageName();
2553 }
2554 return null;
2555 }
2556
Maggieaa080f92018-01-04 15:35:11 -08002557 /**
Maggie2a9409e2018-03-21 11:47:28 -07002558 * Returns the current location enabled/disabled status for a user
2559 *
2560 * @param userId the id of the user
2561 * @return true if location is enabled
2562 */
2563 @Override
2564 public boolean isLocationEnabledForUser(int userId) {
2565 // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
2566 checkInteractAcrossUsersPermission(userId);
2567
2568 long identity = Binder.clearCallingIdentity();
2569 try {
2570 synchronized (mLock) {
2571 final String allowedProviders = Settings.Secure.getStringForUser(
2572 mContext.getContentResolver(),
2573 Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
2574 userId);
2575 if (allowedProviders == null) {
2576 return false;
2577 }
2578 final List<String> providerList = Arrays.asList(allowedProviders.split(","));
2579 for(String provider : mRealProviders.keySet()) {
2580 if (provider.equals(LocationManager.PASSIVE_PROVIDER)
2581 || provider.equals(LocationManager.FUSED_PROVIDER)) {
2582 continue;
2583 }
2584 if (providerList.contains(provider)) {
2585 return true;
2586 }
2587 }
2588 return false;
2589 }
2590 } finally {
2591 Binder.restoreCallingIdentity(identity);
2592 }
2593 }
2594
2595 /**
2596 * Enable or disable location for a user
2597 *
2598 * @param enabled true to enable location, false to disable location
2599 * @param userId the id of the user
2600 */
2601 @Override
2602 public void setLocationEnabledForUser(boolean enabled, int userId) {
2603 mContext.enforceCallingPermission(
2604 android.Manifest.permission.WRITE_SECURE_SETTINGS,
2605 "Requires WRITE_SECURE_SETTINGS permission");
2606
2607 // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
2608 checkInteractAcrossUsersPermission(userId);
2609
2610 long identity = Binder.clearCallingIdentity();
2611 try {
2612 synchronized (mLock) {
2613 final Set<String> allRealProviders = mRealProviders.keySet();
2614 // Update all providers on device plus gps and network provider when disabling
2615 // location
2616 Set<String> allProvidersSet = new ArraySet<>(allRealProviders.size() + 2);
2617 allProvidersSet.addAll(allRealProviders);
2618 // When disabling location, disable gps and network provider that could have been
2619 // enabled by location mode api.
2620 if (enabled == false) {
2621 allProvidersSet.add(LocationManager.GPS_PROVIDER);
2622 allProvidersSet.add(LocationManager.NETWORK_PROVIDER);
2623 }
2624 if (allProvidersSet.isEmpty()) {
2625 return;
2626 }
2627 // to ensure thread safety, we write the provider name with a '+' or '-'
2628 // and let the SettingsProvider handle it rather than reading and modifying
2629 // the list of enabled providers.
2630 final String prefix = enabled ? "+" : "-";
2631 StringBuilder locationProvidersAllowed = new StringBuilder();
2632 for (String provider : allProvidersSet) {
2633 if (provider.equals(LocationManager.PASSIVE_PROVIDER)
2634 || provider.equals(LocationManager.FUSED_PROVIDER)) {
2635 continue;
2636 }
2637 locationProvidersAllowed.append(prefix);
2638 locationProvidersAllowed.append(provider);
2639 locationProvidersAllowed.append(",");
2640 }
2641 // Remove the trailing comma
2642 locationProvidersAllowed.setLength(locationProvidersAllowed.length() - 1);
2643 Settings.Secure.putStringForUser(
2644 mContext.getContentResolver(),
2645 Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
2646 locationProvidersAllowed.toString(),
2647 userId);
2648 }
2649 } finally {
2650 Binder.restoreCallingIdentity(identity);
2651 }
2652 }
2653
2654 /**
2655 * Returns the current enabled/disabled status of a location provider and user
2656 *
2657 * @param provider name of the provider
2658 * @param userId the id of the user
2659 * @return true if the provider exists and is enabled
2660 */
2661 @Override
2662 public boolean isProviderEnabledForUser(String provider, int userId) {
2663 // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
2664 checkInteractAcrossUsersPermission(userId);
2665
2666 // Fused provider is accessed indirectly via criteria rather than the provider-based APIs,
2667 // so we discourage its use
2668 if (LocationManager.FUSED_PROVIDER.equals(provider)) return false;
2669
2670 int uid = Binder.getCallingUid();
2671 synchronized (mLock) {
2672 LocationProviderInterface p = mProvidersByName.get(provider);
2673 return p != null
2674 && isAllowedByUserSettingsLocked(provider, uid, userId);
2675 }
2676 }
2677
2678 /**
2679 * Enable or disable a single location provider.
2680 *
2681 * @param provider name of the provider
2682 * @param enabled true to enable the provider. False to disable the provider
2683 * @param userId the id of the user to set
2684 * @return true if the value was set, false on errors
2685 */
2686 @Override
2687 public boolean setProviderEnabledForUser(String provider, boolean enabled, int userId) {
2688 mContext.enforceCallingPermission(
2689 android.Manifest.permission.WRITE_SECURE_SETTINGS,
2690 "Requires WRITE_SECURE_SETTINGS permission");
2691
2692 // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
2693 checkInteractAcrossUsersPermission(userId);
2694
2695 // Fused provider is accessed indirectly via criteria rather than the provider-based APIs,
2696 // so we discourage its use
2697 if (LocationManager.FUSED_PROVIDER.equals(provider)) return false;
2698
2699 long identity = Binder.clearCallingIdentity();
2700 try {
2701 synchronized (mLock) {
2702 // No such provider exists
2703 if (!mProvidersByName.containsKey(provider)) return false;
2704
2705 // If it is a test provider, do not write to Settings.Secure
2706 if (mMockProviders.containsKey(provider)) {
2707 setTestProviderEnabled(provider, enabled);
2708 return true;
2709 }
2710
2711 // to ensure thread safety, we write the provider name with a '+' or '-'
2712 // and let the SettingsProvider handle it rather than reading and modifying
2713 // the list of enabled providers.
2714 String providerChange = (enabled ? "+" : "-") + provider;
2715 return Settings.Secure.putStringForUser(
2716 mContext.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
2717 providerChange, userId);
2718 }
2719 } finally {
2720 Binder.restoreCallingIdentity(identity);
2721 }
2722 }
2723
2724 /**
Maggieaa080f92018-01-04 15:35:11 -08002725 * Read location provider status from Settings.Secure
2726 *
2727 * @param provider the location provider to query
2728 * @param userId the user id to query
2729 * @return true if the provider is enabled
2730 */
2731 private boolean isLocationProviderEnabledForUser(String provider, int userId) {
2732 long identity = Binder.clearCallingIdentity();
2733 try {
2734 // Use system settings
2735 ContentResolver cr = mContext.getContentResolver();
2736 String allowedProviders = Settings.Secure.getStringForUser(
2737 cr, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
2738 return TextUtils.delimitedStringContains(allowedProviders, ',', provider);
2739 } finally {
2740 Binder.restoreCallingIdentity(identity);
2741 }
2742 }
2743
2744 /**
Maggie2a9409e2018-03-21 11:47:28 -07002745 * Method for checking INTERACT_ACROSS_USERS permission if specified user id is not the same as
2746 * current user id
2747 *
2748 * @param userId the user id to get or set value
2749 */
2750 private void checkInteractAcrossUsersPermission(int userId) {
2751 int uid = Binder.getCallingUid();
2752 if (UserHandle.getUserId(uid) != userId) {
2753 if (ActivityManager.checkComponentPermission(
2754 android.Manifest.permission.INTERACT_ACROSS_USERS, uid, -1, true)
2755 != PERMISSION_GRANTED) {
2756 throw new SecurityException("Requires INTERACT_ACROSS_USERS permission");
2757 }
2758 }
2759 }
2760
2761 /**
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002762 * Returns "true" if the UID belongs to a bound location provider.
2763 *
2764 * @param uid the uid
2765 * @return true if uid belongs to a bound location provider
2766 */
2767 private boolean isUidALocationProvider(int uid) {
2768 if (uid == Process.SYSTEM_UID) {
2769 return true;
2770 }
2771 if (mGeocodeProvider != null) {
David Christie1f141c12014-05-14 15:11:15 -07002772 if (doesUidHavePackage(uid, mGeocodeProvider.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002773 }
2774 for (LocationProviderProxy proxy : mProxyProviders) {
David Christie1f141c12014-05-14 15:11:15 -07002775 if (doesUidHavePackage(uid, proxy.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002776 }
2777 return false;
2778 }
2779
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002780 private void checkCallerIsProvider() {
2781 if (mContext.checkCallingOrSelfPermission(INSTALL_LOCATION_PROVIDER)
Maggieaa080f92018-01-04 15:35:11 -08002782 == PERMISSION_GRANTED) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002783 return;
2784 }
2785
2786 // Previously we only used the INSTALL_LOCATION_PROVIDER
2787 // check. But that is system or signature
2788 // protection level which is not flexible enough for
2789 // providers installed oustide the system image. So
2790 // also allow providers with a UID matching the
2791 // currently bound package name
2792
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002793 if (isUidALocationProvider(Binder.getCallingUid())) {
2794 return;
2795 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002796
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002797 throw new SecurityException("need INSTALL_LOCATION_PROVIDER permission, " +
2798 "or UID of a currently bound location provider");
2799 }
2800
David Christie1f141c12014-05-14 15:11:15 -07002801 /**
2802 * Returns true if the given package belongs to the given uid.
2803 */
2804 private boolean doesUidHavePackage(int uid, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002805 if (packageName == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002806 return false;
2807 }
David Christie1f141c12014-05-14 15:11:15 -07002808 String[] packageNames = mPackageManager.getPackagesForUid(uid);
2809 if (packageNames == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002810 return false;
2811 }
David Christie1f141c12014-05-14 15:11:15 -07002812 for (String name : packageNames) {
2813 if (packageName.equals(name)) {
2814 return true;
2815 }
2816 }
2817 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818 }
2819
Nick Pellye0fd6932012-07-11 10:26:13 -07002820 @Override
Mike Lockwooda4903f22010-02-17 06:42:23 -05002821 public void reportLocation(Location location, boolean passive) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002822 checkCallerIsProvider();
Mike Lockwood275555c2009-05-01 11:30:34 -04002823
Nick Pelly2eeeec22012-07-18 13:13:37 -07002824 if (!location.isComplete()) {
2825 Log.w(TAG, "Dropping incomplete location: " + location);
2826 return;
2827 }
2828
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002829 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED, location);
2830 Message m = Message.obtain(mLocationHandler, MSG_LOCATION_CHANGED, location);
Mike Lockwooda4903f22010-02-17 06:42:23 -05002831 m.arg1 = (passive ? 1 : 0);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002832 mLocationHandler.sendMessageAtFrontOfQueue(m);
2833 }
2834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835
Laurent Tu75defb62012-11-01 16:21:52 -07002836 private static boolean shouldBroadcastSafe(
2837 Location loc, Location lastLoc, UpdateRecord record, long now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838 // Always broadcast the first update
2839 if (lastLoc == null) {
2840 return true;
2841 }
2842
Nick Pellyf1be6862012-05-15 10:53:42 -07002843 // Check whether sufficient time has passed
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002844 long minTime = record.mRealRequest.getFastestInterval();
David Christie1b9b7b12013-04-15 15:31:11 -07002845 long delta = (loc.getElapsedRealtimeNanos() - lastLoc.getElapsedRealtimeNanos())
2846 / NANOS_PER_MILLI;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002847 if (delta < minTime - MAX_PROVIDER_SCHEDULING_JITTER_MS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 return false;
2849 }
2850
2851 // Check whether sufficient distance has been traveled
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002852 double minDistance = record.mRealRequest.getSmallestDisplacement();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 if (minDistance > 0.0) {
2854 if (loc.distanceTo(lastLoc) <= minDistance) {
2855 return false;
2856 }
2857 }
2858
Laurent Tu75defb62012-11-01 16:21:52 -07002859 // Check whether sufficient number of udpates is left
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002860 if (record.mRealRequest.getNumUpdates() <= 0) {
Laurent Tu75defb62012-11-01 16:21:52 -07002861 return false;
2862 }
2863
2864 // Check whether the expiry date has passed
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002865 return record.mRealRequest.getExpireAt() >= now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002866 }
2867
Mike Lockwooda4903f22010-02-17 06:42:23 -05002868 private void handleLocationChangedLocked(Location location, boolean passive) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002869 if (D) Log.d(TAG, "incoming location: " + location);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002870 long now = SystemClock.elapsedRealtime();
Mike Lockwooda4903f22010-02-17 06:42:23 -05002871 String provider = (passive ? LocationManager.PASSIVE_PROVIDER : location.getProvider());
Laurent Tu60ec50a2012-10-04 17:00:10 -07002872 // Skip if the provider is unknown.
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002873 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002874 if (p == null) return;
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002875 updateLastLocationLocked(location, provider);
2876 // mLastLocation should have been updated from the updateLastLocationLocked call above.
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002877 Location lastLocation = mLastLocation.get(provider);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002878 if (lastLocation == null) {
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002879 Log.e(TAG, "handleLocationChangedLocked() updateLastLocation failed");
2880 return;
Mike Lockwood4e50b782009-04-03 08:24:43 -07002881 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882
David Christie1b9b7b12013-04-15 15:31:11 -07002883 // Update last known coarse interval location if enough time has passed.
2884 Location lastLocationCoarseInterval = mLastLocationCoarseInterval.get(provider);
2885 if (lastLocationCoarseInterval == null) {
2886 lastLocationCoarseInterval = new Location(location);
2887 mLastLocationCoarseInterval.put(provider, lastLocationCoarseInterval);
2888 }
2889 long timeDiffNanos = location.getElapsedRealtimeNanos()
2890 - lastLocationCoarseInterval.getElapsedRealtimeNanos();
2891 if (timeDiffNanos > LocationFudger.FASTEST_INTERVAL_MS * NANOS_PER_MILLI) {
2892 lastLocationCoarseInterval.set(location);
2893 }
2894 // Don't ever return a coarse location that is more recent than the allowed update
2895 // interval (i.e. don't allow an app to keep registering and unregistering for
2896 // location updates to overcome the minimum interval).
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002897 Location noGPSLocation =
David Christie1b9b7b12013-04-15 15:31:11 -07002898 lastLocationCoarseInterval.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2899
Laurent Tu60ec50a2012-10-04 17:00:10 -07002900 // Skip if there are no UpdateRecords for this provider.
2901 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
2902 if (records == null || records.size() == 0) return;
2903
Victoria Lease09016ab2012-09-16 12:33:15 -07002904 // Fetch coarse location
2905 Location coarseLocation = null;
David Christie1b9b7b12013-04-15 15:31:11 -07002906 if (noGPSLocation != null) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002907 coarseLocation = mLocationFudger.getOrCreate(noGPSLocation);
2908 }
2909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002910 // Fetch latest status update time
2911 long newStatusUpdateTime = p.getStatusUpdateTime();
2912
David Christie2ff96af2014-01-30 16:09:37 -08002913 // Get latest status
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002914 Bundle extras = new Bundle();
2915 int status = p.getStatus(extras);
2916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002917 ArrayList<Receiver> deadReceivers = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002918 ArrayList<UpdateRecord> deadUpdateRecords = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07002919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002920 // Broadcast location or status to all listeners
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002921 for (UpdateRecord r : records) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002922 Receiver receiver = r.mReceiver;
Mike Lockwood03ca2162010-04-01 08:10:09 -07002923 boolean receiverDead = false;
Nick Pelly4035f5a2012-08-17 14:43:49 -07002924
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002925 int receiverUserId = UserHandle.getUserId(receiver.mIdentity.mUid);
2926 if (!isCurrentProfile(receiverUserId)
2927 && !isUidALocationProvider(receiver.mIdentity.mUid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07002928 if (D) {
Victoria Lease269518e2012-10-29 08:25:39 -07002929 Log.d(TAG, "skipping loc update for background user " + receiverUserId +
Victoria Leaseb711d572012-10-02 13:14:11 -07002930 " (current user: " + mCurrentUserId + ", app: " +
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002931 receiver.mIdentity.mPackageName + ")");
Victoria Leaseb711d572012-10-02 13:14:11 -07002932 }
2933 continue;
2934 }
2935
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002936 if (mBlacklist.isBlacklisted(receiver.mIdentity.mPackageName)) {
gomo48f1a642017-11-10 20:35:46 -08002937 if (D) {
2938 Log.d(TAG, "skipping loc update for blacklisted app: " +
2939 receiver.mIdentity.mPackageName);
2940 }
Nick Pelly4035f5a2012-08-17 14:43:49 -07002941 continue;
2942 }
2943
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002944 if (!reportLocationAccessNoThrow(
2945 receiver.mIdentity.mPid,
2946 receiver.mIdentity.mUid,
2947 receiver.mIdentity.mPackageName,
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002948 receiver.mAllowedResolutionLevel)) {
gomo48f1a642017-11-10 20:35:46 -08002949 if (D) {
2950 Log.d(TAG, "skipping loc update for no op app: " +
2951 receiver.mIdentity.mPackageName);
2952 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002953 continue;
2954 }
2955
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002956 Location notifyLocation;
Victoria Lease37425c32012-10-16 16:08:48 -07002957 if (receiver.mAllowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
2958 notifyLocation = coarseLocation; // use coarse location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002959 } else {
Victoria Lease37425c32012-10-16 16:08:48 -07002960 notifyLocation = lastLocation; // use fine location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002961 }
Victoria Lease09016ab2012-09-16 12:33:15 -07002962 if (notifyLocation != null) {
2963 Location lastLoc = r.mLastFixBroadcast;
Laurent Tu75defb62012-11-01 16:21:52 -07002964 if ((lastLoc == null) || shouldBroadcastSafe(notifyLocation, lastLoc, r, now)) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002965 if (lastLoc == null) {
2966 lastLoc = new Location(notifyLocation);
2967 r.mLastFixBroadcast = lastLoc;
2968 } else {
2969 lastLoc.set(notifyLocation);
2970 }
2971 if (!receiver.callLocationChangedLocked(notifyLocation)) {
2972 Slog.w(TAG, "RemoteException calling onLocationChanged on " + receiver);
2973 receiverDead = true;
2974 }
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002975 r.mRealRequest.decrementNumUpdates();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002976 }
2977 }
2978
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002979 long prevStatusUpdateTime = r.mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002980 if ((newStatusUpdateTime > prevStatusUpdateTime) &&
Victoria Lease09016ab2012-09-16 12:33:15 -07002981 (prevStatusUpdateTime != 0 || status != LocationProvider.AVAILABLE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002982
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002983 r.mLastStatusBroadcast = newStatusUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002984 if (!receiver.callStatusChangedLocked(provider, status, extras)) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07002985 receiverDead = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002986 Slog.w(TAG, "RemoteException calling onStatusChanged on " + receiver);
Mike Lockwood03ca2162010-04-01 08:10:09 -07002987 }
2988 }
2989
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002990 // track expired records
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002991 if (r.mRealRequest.getNumUpdates() <= 0 || r.mRealRequest.getExpireAt() < now) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002992 if (deadUpdateRecords == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002993 deadUpdateRecords = new ArrayList<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002994 }
2995 deadUpdateRecords.add(r);
2996 }
2997 // track dead receivers
2998 if (receiverDead) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07002999 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08003000 deadReceivers = new ArrayList<>();
Mike Lockwood03ca2162010-04-01 08:10:09 -07003001 }
3002 if (!deadReceivers.contains(receiver)) {
3003 deadReceivers.add(receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003004 }
3005 }
3006 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003007
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003008 // remove dead records and receivers outside the loop
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003009 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003010 for (Receiver receiver : deadReceivers) {
3011 removeUpdatesLocked(receiver);
3012 }
3013 }
3014 if (deadUpdateRecords != null) {
3015 for (UpdateRecord r : deadUpdateRecords) {
3016 r.disposeLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003017 }
Victoria Lease8b38b292012-12-04 15:04:43 -08003018 applyRequirementsLocked(provider);
3019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003020 }
3021
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08003022 /**
3023 * Updates last location with the given location
3024 *
3025 * @param location new location to update
3026 * @param provider Location provider to update for
3027 */
3028 private void updateLastLocationLocked(Location location, String provider) {
3029 Location noGPSLocation = location.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
3030 Location lastNoGPSLocation;
3031 Location lastLocation = mLastLocation.get(provider);
3032 if (lastLocation == null) {
3033 lastLocation = new Location(provider);
3034 mLastLocation.put(provider, lastLocation);
3035 } else {
3036 lastNoGPSLocation = lastLocation.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
3037 if (noGPSLocation == null && lastNoGPSLocation != null) {
3038 // New location has no no-GPS location: adopt last no-GPS location. This is set
3039 // directly into location because we do not want to notify COARSE clients.
3040 location.setExtraLocation(Location.EXTRA_NO_GPS_LOCATION, lastNoGPSLocation);
3041 }
3042 }
3043 lastLocation.set(location);
3044 }
3045
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003046 private class LocationWorkerHandler extends Handler {
Victoria Lease5cd731a2012-12-19 15:04:21 -08003047 public LocationWorkerHandler(Looper looper) {
3048 super(looper, null, true);
3049 }
3050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003051 @Override
3052 public void handleMessage(Message msg) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003053 switch (msg.what) {
3054 case MSG_LOCATION_CHANGED:
3055 handleLocationChanged((Location) msg.obj, msg.arg1 == 1);
3056 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057 }
3058 }
3059 }
3060
Victoria Lease54ca7ae2013-01-08 09:39:50 -08003061 private boolean isMockProvider(String provider) {
3062 synchronized (mLock) {
3063 return mMockProviders.containsKey(provider);
3064 }
3065 }
3066
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003067 private void handleLocationChanged(Location location, boolean passive) {
Victoria Lease54ca7ae2013-01-08 09:39:50 -08003068 // create a working copy of the incoming Location so that the service can modify it without
3069 // disturbing the caller's copy
3070 Location myLocation = new Location(location);
3071 String provider = myLocation.getProvider();
3072
3073 // set "isFromMockProvider" bit if location came from a mock provider. we do not clear this
3074 // bit if location did not come from a mock provider because passive/fused providers can
3075 // forward locations from mock providers, and should not grant them legitimacy in doing so.
3076 if (!myLocation.isFromMockProvider() && isMockProvider(provider)) {
3077 myLocation.setIsFromMockProvider(true);
3078 }
Jeff Sharkey5e613312012-01-30 11:16:20 -08003079
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003080 synchronized (mLock) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08003081 if (isAllowedByCurrentUserSettingsLocked(provider)) {
3082 if (!passive) {
3083 // notify passive provider of the new location
3084 mPassiveProvider.updateLocation(myLocation);
3085 }
Victoria Lease54ca7ae2013-01-08 09:39:50 -08003086 handleLocationChangedLocked(myLocation, passive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003087 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003088 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003090
Mike Lockwoode97ae402010-09-29 15:23:46 -04003091 private final PackageMonitor mPackageMonitor = new PackageMonitor() {
3092 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003093 public void onPackageDisappeared(String packageName, int reason) {
3094 // remove all receivers associated with this package name
3095 synchronized (mLock) {
3096 ArrayList<Receiver> deadReceivers = null;
3097
3098 for (Receiver receiver : mReceivers.values()) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08003099 if (receiver.mIdentity.mPackageName.equals(packageName)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003100 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08003101 deadReceivers = new ArrayList<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003102 }
3103 deadReceivers.add(receiver);
3104 }
3105 }
3106
3107 // perform removal outside of mReceivers loop
3108 if (deadReceivers != null) {
3109 for (Receiver receiver : deadReceivers) {
3110 removeUpdatesLocked(receiver);
3111 }
3112 }
3113 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003114 }
Mike Lockwoode97ae402010-09-29 15:23:46 -04003115 };
3116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003117 // Geocoder
3118
Nick Pellye0fd6932012-07-11 10:26:13 -07003119 @Override
Mike Lockwoode15735a2010-09-20 17:48:47 -04003120 public boolean geocoderIsPresent() {
Mark Vandevoorde01ac80b2010-05-21 15:43:26 -07003121 return mGeocodeProvider != null;
3122 }
3123
Nick Pellye0fd6932012-07-11 10:26:13 -07003124 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003125 public String getFromLocation(double latitude, double longitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05003126 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04003127 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05003128 return mGeocodeProvider.getFromLocation(latitude, longitude, maxResults,
3129 params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003130 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04003131 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003132 }
3133
Mike Lockwooda55c3212009-04-15 11:10:11 -04003134
Nick Pellye0fd6932012-07-11 10:26:13 -07003135 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136 public String getFromLocationName(String locationName,
Mike Lockwooda55c3212009-04-15 11:10:11 -04003137 double lowerLeftLatitude, double lowerLeftLongitude,
3138 double upperRightLatitude, double upperRightLongitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05003139 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04003140
3141 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05003142 return mGeocodeProvider.getFromLocationName(locationName, lowerLeftLatitude,
3143 lowerLeftLongitude, upperRightLatitude, upperRightLongitude,
3144 maxResults, params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003145 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04003146 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003147 }
3148
3149 // Mock Providers
3150
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003151 private boolean canCallerAccessMockLocation(String opPackageName) {
3152 return mAppOps.noteOp(AppOpsManager.OP_MOCK_LOCATION, Binder.getCallingUid(),
3153 opPackageName) == AppOpsManager.MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003154 }
3155
Nick Pellye0fd6932012-07-11 10:26:13 -07003156 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003157 public void addTestProvider(String name, ProviderProperties properties, String opPackageName) {
3158 if (!canCallerAccessMockLocation(opPackageName)) {
3159 return;
3160 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003161
Mike Lockwooda4903f22010-02-17 06:42:23 -05003162 if (LocationManager.PASSIVE_PROVIDER.equals(name)) {
3163 throw new IllegalArgumentException("Cannot mock the passive location provider");
3164 }
3165
Mike Lockwood86328a92009-10-23 08:38:25 -04003166 long identity = Binder.clearCallingIdentity();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003167 synchronized (mLock) {
Mike Lockwood7566c1d2009-08-25 10:05:18 -07003168 // remove the real provider if we are replacing GPS or network provider
3169 if (LocationManager.GPS_PROVIDER.equals(name)
Nick Pelly1332b532012-08-21 16:25:47 -07003170 || LocationManager.NETWORK_PROVIDER.equals(name)
3171 || LocationManager.FUSED_PROVIDER.equals(name)) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05003172 LocationProviderInterface p = mProvidersByName.get(name);
3173 if (p != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003174 removeProviderLocked(p);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07003175 }
3176 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09003177 addTestProviderLocked(name, properties);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003178 updateProvidersLocked();
3179 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003180 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003181 }
3182
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09003183 private void addTestProviderLocked(String name, ProviderProperties properties) {
3184 if (mProvidersByName.get(name) != null) {
3185 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
3186 }
3187 MockProvider provider = new MockProvider(name, this, properties);
3188 addProviderLocked(provider);
3189 mMockProviders.put(name, provider);
3190 mLastLocation.put(name, null);
3191 mLastLocationCoarseInterval.put(name, null);
3192 }
3193
Nick Pellye0fd6932012-07-11 10:26:13 -07003194 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003195 public void removeTestProvider(String provider, String opPackageName) {
3196 if (!canCallerAccessMockLocation(opPackageName)) {
3197 return;
3198 }
3199
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003200 synchronized (mLock) {
Tom O'Neill07ee5d12014-03-03 17:48:35 -08003201
3202 // These methods can't be called after removing the test provider, so first make sure
Tom O'Neillfe6d3c52014-03-04 08:26:17 -08003203 // we don't leave anything dangling.
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003204 clearTestProviderEnabled(provider, opPackageName);
3205 clearTestProviderLocation(provider, opPackageName);
3206 clearTestProviderStatus(provider, opPackageName);
Tom O'Neill07ee5d12014-03-03 17:48:35 -08003207
You Kima6d0b6f2012-10-28 03:58:44 +09003208 MockProvider mockProvider = mMockProviders.remove(provider);
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003209 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3211 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003212 long identity = Binder.clearCallingIdentity();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003213 removeProviderLocked(mProvidersByName.get(provider));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003214
3215 // reinstate real provider if available
3216 LocationProviderInterface realProvider = mRealProviders.get(provider);
3217 if (realProvider != null) {
3218 addProviderLocked(realProvider);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07003219 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003220 mLastLocation.put(provider, null);
David Christie1b9b7b12013-04-15 15:31:11 -07003221 mLastLocationCoarseInterval.put(provider, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003222 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04003223 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003224 }
3225 }
3226
Nick Pellye0fd6932012-07-11 10:26:13 -07003227 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003228 public void setTestProviderLocation(String provider, Location loc, String opPackageName) {
3229 if (!canCallerAccessMockLocation(opPackageName)) {
3230 return;
3231 }
3232
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003233 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003234 MockProvider mockProvider = mMockProviders.get(provider);
3235 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003236 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3237 }
Tom O'Neilla206a0f2016-12-15 10:26:28 -08003238
3239 // Ensure that the location is marked as being mock. There's some logic to do this in
3240 // handleLocationChanged(), but it fails if loc has the wrong provider (bug 33091107).
3241 Location mock = new Location(loc);
3242 mock.setIsFromMockProvider(true);
3243
3244 if (!TextUtils.isEmpty(loc.getProvider()) && !provider.equals(loc.getProvider())) {
3245 // The location has an explicit provider that is different from the mock provider
3246 // name. The caller may be trying to fool us via bug 33091107.
3247 EventLog.writeEvent(0x534e4554, "33091107", Binder.getCallingUid(),
3248 provider + "!=" + loc.getProvider());
3249 }
3250
Mike Lockwood95427cd2009-05-07 13:27:54 -04003251 // clear calling identity so INSTALL_LOCATION_PROVIDER permission is not required
3252 long identity = Binder.clearCallingIdentity();
Tom O'Neilla206a0f2016-12-15 10:26:28 -08003253 mockProvider.setLocation(mock);
Mike Lockwood95427cd2009-05-07 13:27:54 -04003254 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003255 }
3256 }
3257
Nick Pellye0fd6932012-07-11 10:26:13 -07003258 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003259 public void clearTestProviderLocation(String provider, String opPackageName) {
3260 if (!canCallerAccessMockLocation(opPackageName)) {
3261 return;
3262 }
3263
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003264 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003265 MockProvider mockProvider = mMockProviders.get(provider);
3266 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003267 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3268 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003269 mockProvider.clearLocation();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003270 }
3271 }
3272
Nick Pellye0fd6932012-07-11 10:26:13 -07003273 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003274 public void setTestProviderEnabled(String provider, boolean enabled, String opPackageName) {
3275 if (!canCallerAccessMockLocation(opPackageName)) {
3276 return;
3277 }
Maggie2a9409e2018-03-21 11:47:28 -07003278 setTestProviderEnabled(provider, enabled);
3279 }
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003280
Maggie2a9409e2018-03-21 11:47:28 -07003281 /** Enable or disable a test location provider. */
3282 private void setTestProviderEnabled(String provider, boolean enabled) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003283 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003284 MockProvider mockProvider = mMockProviders.get(provider);
3285 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003286 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3287 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003288 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289 if (enabled) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003290 mockProvider.enable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003291 mEnabledProviders.add(provider);
3292 mDisabledProviders.remove(provider);
3293 } else {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003294 mockProvider.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003295 mEnabledProviders.remove(provider);
3296 mDisabledProviders.add(provider);
3297 }
3298 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04003299 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300 }
3301 }
3302
Nick Pellye0fd6932012-07-11 10:26:13 -07003303 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003304 public void clearTestProviderEnabled(String provider, String opPackageName) {
3305 if (!canCallerAccessMockLocation(opPackageName)) {
3306 return;
3307 }
3308
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003309 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003310 MockProvider mockProvider = mMockProviders.get(provider);
3311 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3313 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003314 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003315 mEnabledProviders.remove(provider);
3316 mDisabledProviders.remove(provider);
3317 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04003318 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003319 }
3320 }
3321
Nick Pellye0fd6932012-07-11 10:26:13 -07003322 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003323 public void setTestProviderStatus(String provider, int status, Bundle extras, long updateTime,
3324 String opPackageName) {
3325 if (!canCallerAccessMockLocation(opPackageName)) {
3326 return;
3327 }
3328
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003329 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003330 MockProvider mockProvider = mMockProviders.get(provider);
3331 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003332 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3333 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003334 mockProvider.setStatus(status, extras, updateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003335 }
3336 }
3337
Nick Pellye0fd6932012-07-11 10:26:13 -07003338 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003339 public void clearTestProviderStatus(String provider, String opPackageName) {
3340 if (!canCallerAccessMockLocation(opPackageName)) {
3341 return;
3342 }
3343
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003344 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003345 MockProvider mockProvider = mMockProviders.get(provider);
3346 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003347 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3348 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003349 mockProvider.clearStatus();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003350 }
3351 }
3352
3353 private void log(String log) {
3354 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003355 Slog.d(TAG, log);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003356 }
3357 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003358
3359 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003360 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003361 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Nick Pellye0fd6932012-07-11 10:26:13 -07003362
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003363 synchronized (mLock) {
Siddharth Raybb608c82017-03-16 11:33:34 -07003364 if (args.length > 0 && args[0].equals("--gnssmetrics")) {
3365 if (mGnssMetricsProvider != null) {
3366 pw.append(mGnssMetricsProvider.getGnssMetricsAsProtoString());
3367 }
3368 return;
3369 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003370 pw.println("Current Location Manager state:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003371 pw.println(" Location Listeners:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003372 for (Receiver receiver : mReceivers.values()) {
3373 pw.println(" " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003374 }
David Christie2ff96af2014-01-30 16:09:37 -08003375 pw.println(" Active Records by Provider:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003376 for (Map.Entry<String, ArrayList<UpdateRecord>> entry : mRecordsByProvider.entrySet()) {
3377 pw.println(" " + entry.getKey() + ":");
3378 for (UpdateRecord record : entry.getValue()) {
3379 pw.println(" " + record);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003380 }
3381 }
Wyatt Riley11cc7492018-01-17 08:48:27 -08003382 pw.println(" Active GnssMeasurement Listeners:");
3383 for (Identity identity : mGnssMeasurementsListeners.values()) {
3384 pw.println(" " + identity.mPid + " " + identity.mUid + " "
3385 + identity.mPackageName + ": " + isThrottlingExemptLocked(identity));
3386 }
3387 pw.println(" Active GnssNavigationMessage Listeners:");
3388 for (Identity identity : mGnssNavigationMessageListeners.values()) {
3389 pw.println(" " + identity.mPid + " " + identity.mUid + " "
3390 + identity.mPackageName + ": " + isThrottlingExemptLocked(identity));
3391 }
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08003392 pw.println(" Overlay Provider Packages:");
3393 for (LocationProviderInterface provider : mProviders) {
3394 if (provider instanceof LocationProviderProxy) {
3395 pw.println(" " + provider.getName() + ": "
3396 + ((LocationProviderProxy) provider).getConnectedPackageName());
3397 }
3398 }
David Christie2ff96af2014-01-30 16:09:37 -08003399 pw.println(" Historical Records by Provider:");
3400 for (Map.Entry<PackageProviderKey, PackageStatistics> entry
3401 : mRequestStatistics.statistics.entrySet()) {
3402 PackageProviderKey key = entry.getKey();
3403 PackageStatistics stats = entry.getValue();
3404 pw.println(" " + key.packageName + ": " + key.providerName + ": " + stats);
3405 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003406 pw.println(" Last Known Locations:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003407 for (Map.Entry<String, Location> entry : mLastLocation.entrySet()) {
3408 String provider = entry.getKey();
3409 Location location = entry.getValue();
3410 pw.println(" " + provider + ": " + location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003411 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003412
David Christie1b9b7b12013-04-15 15:31:11 -07003413 pw.println(" Last Known Locations Coarse Intervals:");
3414 for (Map.Entry<String, Location> entry : mLastLocationCoarseInterval.entrySet()) {
3415 String provider = entry.getKey();
3416 Location location = entry.getValue();
3417 pw.println(" " + provider + ": " + location);
3418 }
3419
Nick Pellye0fd6932012-07-11 10:26:13 -07003420 mGeofenceManager.dump(pw);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003422 if (mEnabledProviders.size() > 0) {
3423 pw.println(" Enabled Providers:");
3424 for (String i : mEnabledProviders) {
3425 pw.println(" " + i);
3426 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003428 }
3429 if (mDisabledProviders.size() > 0) {
3430 pw.println(" Disabled Providers:");
3431 for (String i : mDisabledProviders) {
3432 pw.println(" " + i);
3433 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003434 }
Nick Pelly4035f5a2012-08-17 14:43:49 -07003435 pw.append(" ");
3436 mBlacklist.dump(pw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003437 if (mMockProviders.size() > 0) {
3438 pw.println(" Mock Providers:");
3439 for (Map.Entry<String, MockProvider> i : mMockProviders.entrySet()) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003440 i.getValue().dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003441 }
3442 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003443
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08003444 if (!mBackgroundThrottlePackageWhitelist.isEmpty()) {
3445 pw.println(" Throttling Whitelisted Packages:");
3446 for (String packageName : mBackgroundThrottlePackageWhitelist) {
3447 pw.println(" " + packageName);
3448 }
3449 }
3450
Nick Pelly74fa7ea2012-08-13 19:36:38 -07003451 pw.append(" fudger: ");
gomo48f1a642017-11-10 20:35:46 -08003452 mLocationFudger.dump(fd, pw, args);
Nick Pelly74fa7ea2012-08-13 19:36:38 -07003453
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003454 if (args.length > 0 && "short".equals(args[0])) {
3455 return;
3456 }
gomo48f1a642017-11-10 20:35:46 -08003457 for (LocationProviderInterface provider : mProviders) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003458 pw.print(provider.getName() + " Internal State");
3459 if (provider instanceof LocationProviderProxy) {
3460 LocationProviderProxy proxy = (LocationProviderProxy) provider;
3461 pw.print(" (" + proxy.getConnectedPackageName() + ")");
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06003462 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003463 pw.println(":");
3464 provider.dump(fd, pw, args);
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06003465 }
Wyatt Rileycf879db2017-01-12 13:57:38 -08003466 if (mGnssBatchingInProgress) {
3467 pw.println(" GNSS batching in progress");
3468 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003469 }
3470 }
3471}