blob: e803c9ad7ed32f75ccefc9d39514410307bb643a [file] [log] [blame]
Mathias Agopianfc328812010-07-14 23:41:37 -07001/*
2 * Copyright (C) 2010 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 */
Brian Stack793f4642019-04-18 17:21:34 -070016#include <android/content/pm/IPackageManagerNative.h>
Mike Ma24743862020-01-29 00:36:55 -080017#include <android/util/ProtoOutputStream.h>
18#include <frameworks/base/core/proto/android/service/sensor_service.proto.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080019#include <binder/ActivityManager.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070020#include <binder/BinderService.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070021#include <binder/IServiceManager.h>
Mathias Agopian1cb13462011-06-27 16:05:52 -070022#include <binder/PermissionCache.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080023#include <binder/PermissionController.h>
Peng Xue36e3472016-11-03 11:57:10 -070024#include <cutils/ashmem.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080025#include <cutils/misc.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070026#include <cutils/properties.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070027#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070028#include <hardware_legacy/power.h>
Brian Duddie0eb46242018-02-15 15:02:29 -080029#include <log/log.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070030#include <openssl/digest.h>
31#include <openssl/hmac.h>
32#include <openssl/rand.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070033#include <sensor/SensorEventQueue.h>
Michael Groover5e1f60b2018-12-04 22:34:29 -080034#include <sensorprivacy/SensorPrivacyManager.h>
Peng Xudd5c5cb2017-03-16 17:39:43 -070035#include <utils/SystemClock.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070036
Mathias Agopian787ac1b2012-09-18 18:49:18 -070037#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070038#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080039#include "GravitySensor.h"
40#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070041#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080042#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070043#include "SensorFusion.h"
Peng Xu755c4512016-04-07 23:15:14 -070044#include "SensorInterface.h"
Peng Xueb4d6282015-12-10 18:02:41 -080045
Mathias Agopian984826c2011-05-17 22:54:42 -070046#include "SensorService.h"
Peng Xue36e3472016-11-03 11:57:10 -070047#include "SensorDirectConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080048#include "SensorEventAckReceiver.h"
Peng Xu6a2d3a02015-12-21 12:00:23 -080049#include "SensorEventConnection.h"
Peng Xueb4d6282015-12-10 18:02:41 -080050#include "SensorRecord.h"
51#include "SensorRegistrationInfo.h"
Peng Xueb4d6282015-12-10 18:02:41 -080052
Brian Stack51498e62018-10-03 10:52:21 -070053#include <ctime>
Peng Xueb4d6282015-12-10 18:02:41 -080054#include <inttypes.h>
55#include <math.h>
Peng Xu98d30f62016-08-01 18:12:11 -070056#include <sched.h>
Peng Xueb4d6282015-12-10 18:02:41 -080057#include <stdint.h>
Peng Xueb4d6282015-12-10 18:02:41 -080058#include <sys/socket.h>
Greg Kaiser53ca2e02016-06-21 16:11:14 -070059#include <sys/stat.h>
60#include <sys/types.h>
61#include <unistd.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070062
Svet Ganove752a5c2018-01-15 17:14:20 -080063#include <private/android_filesystem_config.h>
64
Mathias Agopianfc328812010-07-14 23:41:37 -070065namespace android {
66// ---------------------------------------------------------------------------
67
Mathias Agopian33015422011-05-27 18:18:13 -070068/*
69 * Notes:
70 *
71 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070072 * - run mag sensor from time to time to force calibration
73 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
74 *
75 */
76
Aravind Akella8ef3c892015-07-10 11:24:28 -070077const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
Greg Kaiser53ca2e02016-06-21 16:11:14 -070078uint8_t SensorService::sHmacGlobalKey[128] = {};
79bool SensorService::sHmacGlobalKeyIsValid = false;
Brian Stack793f4642019-04-18 17:21:34 -070080std::map<String16, int> SensorService::sPackageTargetVersion;
81Mutex SensorService::sPackageTargetVersionLock;
82AppOpsManager SensorService::sAppOpsManager;
Greg Kaiser53ca2e02016-06-21 16:11:14 -070083
84#define SENSOR_SERVICE_DIR "/data/system/sensor_service"
85#define SENSOR_SERVICE_HMAC_KEY_FILE SENSOR_SERVICE_DIR "/hmac_key"
Peng Xu98d30f62016-08-01 18:12:11 -070086#define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
Greg Kaiser53ca2e02016-06-21 16:11:14 -070087
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070088// Permissions.
Peng Xudd5c5cb2017-03-16 17:39:43 -070089static const String16 sDumpPermission("android.permission.DUMP");
90static const String16 sLocationHardwarePermission("android.permission.LOCATION_HARDWARE");
Svet Ganove752a5c2018-01-15 17:14:20 -080091static const String16 sManageSensorsPermission("android.permission.MANAGE_SENSORS");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070092
Mathias Agopianfc328812010-07-14 23:41:37 -070093SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -070094 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
Peng Xu47e96012016-03-28 17:55:56 -070095 mWakeLockAcquired(false) {
Jaekyun Seok2d7e3512018-03-28 19:12:11 +090096 mUidPolicy = new UidPolicy(this);
Michael Groover5e1f60b2018-12-04 22:34:29 -080097 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
Mathias Agopianfc328812010-07-14 23:41:37 -070098}
99
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700100bool SensorService::initializeHmacKey() {
101 int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
102 if (fd != -1) {
103 int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
104 close(fd);
105 if (result == sizeof(sHmacGlobalKey)) {
106 return true;
107 }
108 ALOGW("Unable to read HMAC key; generating new one.");
109 }
110
111 if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
112 ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
113 return false;
114 }
115
116 // We need to make sure this is only readable to us.
117 bool wroteKey = false;
118 mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
119 fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
120 S_IRUSR|S_IWUSR);
121 if (fd != -1) {
122 int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
123 close(fd);
124 wroteKey = (result == sizeof(sHmacGlobalKey));
125 }
126 if (wroteKey) {
127 ALOGI("Generated new HMAC key.");
128 } else {
129 ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
130 "after reboot.");
131 }
132 // Even if we failed to write the key we return true, because we did
133 // initialize the HMAC key.
134 return true;
135}
136
Peng Xu98d30f62016-08-01 18:12:11 -0700137// Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
138void SensorService::enableSchedFifoMode() {
139 struct sched_param param = {0};
140 param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
141 if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param) != 0) {
142 ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
143 }
144}
145
Peng Xu47e96012016-03-28 17:55:56 -0700146void SensorService::onFirstRef() {
Steve Blocka5512372011-12-20 16:23:08 +0000147 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -0800148 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700149
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700150 sHmacGlobalKeyIsValid = initializeHmacKey();
151
Mathias Agopianf001c922010-11-11 17:58:51 -0800152 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800153 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700154 ssize_t count = dev.getSensorList(&list);
155 if (count > 0) {
156 ssize_t orientationIndex = -1;
Aravind Akellaf5047892015-07-20 17:29:33 -0700157 bool hasGyro = false, hasAccel = false, hasMag = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700158 uint32_t virtualSensorsNeeds =
159 (1<<SENSOR_TYPE_GRAVITY) |
160 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -0700161 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
162 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
163 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700164
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700165 for (ssize_t i=0 ; i<count ; i++) {
Peng Xuf66684a2015-07-23 11:41:53 -0700166 bool useThisSensor=true;
167
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700168 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700169 case SENSOR_TYPE_ACCELEROMETER:
170 hasAccel = true;
171 break;
172 case SENSOR_TYPE_MAGNETIC_FIELD:
173 hasMag = true;
174 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700175 case SENSOR_TYPE_ORIENTATION:
176 orientationIndex = i;
177 break;
178 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700179 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700180 hasGyro = true;
181 break;
182 case SENSOR_TYPE_GRAVITY:
183 case SENSOR_TYPE_LINEAR_ACCELERATION:
184 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700185 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
186 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
187 if (IGNORE_HARDWARE_FUSION) {
188 useThisSensor = false;
189 } else {
190 virtualSensorsNeeds &= ~(1<<list[i].type);
191 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700192 break;
193 }
Peng Xuf66684a2015-07-23 11:41:53 -0700194 if (useThisSensor) {
195 registerSensor( new HardwareSensor(list[i]) );
196 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700197 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700198
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700199 // it's safe to instantiate the SensorFusion object here
200 // (it wants to be instantiated after h/w sensors have been
201 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700202 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700203
Aravind Akellaf5047892015-07-20 17:29:33 -0700204 if (hasGyro && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700205 // Add Android virtual sensors if they're not already
206 // available in the HAL
Peng Xu0cc8f802016-04-05 23:46:03 -0700207 bool needRotationVector =
208 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700209
Peng Xu0cc8f802016-04-05 23:46:03 -0700210 registerSensor(new RotationVectorSensor(), !needRotationVector, true);
211 registerSensor(new OrientationSensor(), !needRotationVector, true);
Mathias Agopian03193062013-05-10 19:32:39 -0700212
Peng Xu0cc8f802016-04-05 23:46:03 -0700213 bool needLinearAcceleration =
214 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700215
Peng Xu0cc8f802016-04-05 23:46:03 -0700216 registerSensor(new LinearAccelerationSensor(list, count),
217 !needLinearAcceleration, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700218
Peng Xu0cc8f802016-04-05 23:46:03 -0700219 // virtual debugging sensors are not for user
Peng Xu755c4512016-04-07 23:15:14 -0700220 registerSensor( new CorrectedGyroSensor(list, count), true, true);
221 registerSensor( new GyroDriftSensor(), true, true);
Mathias Agopian33264862012-06-28 19:46:54 -0700222 }
223
Peng Xuf66684a2015-07-23 11:41:53 -0700224 if (hasAccel && hasGyro) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700225 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
226 registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700227
Peng Xu0cc8f802016-04-05 23:46:03 -0700228 bool needGameRotationVector =
229 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
230 registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700231 }
232
233 if (hasAccel && hasMag) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700234 bool needGeoMagRotationVector =
235 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
236 registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700237 }
238
Aravind Akella5466c3d2014-08-22 16:11:10 -0700239 // Check if the device really supports batching by looking at the FIFO event
240 // counts for each sensor.
241 bool batchingSupported = false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700242 mSensors.forEachSensor(
243 [&batchingSupported] (const Sensor& s) -> bool {
244 if (s.getFifoMaxEventCount() > 0) {
245 batchingSupported = true;
246 }
247 return !batchingSupported;
248 });
Aravind Akella5466c3d2014-08-22 16:11:10 -0700249
250 if (batchingSupported) {
251 // Increase socket buffer size to a max of 100 KB for batching capabilities.
252 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
253 } else {
254 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
255 }
256
257 // Compare the socketBufferSize value against the system limits and limit
258 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700259 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
260 char line[128];
Yi Kong8f313e32018-07-17 14:13:29 -0700261 if (fp != nullptr && fgets(line, sizeof(line), fp) != nullptr) {
Aravind Akella4c8b9512013-09-05 17:03:38 -0700262 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700263 size_t maxSystemSocketBufferSize;
264 sscanf(line, "%zu", &maxSystemSocketBufferSize);
265 if (mSocketBufferSize > maxSystemSocketBufferSize) {
266 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700267 }
268 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700269 if (fp) {
270 fclose(fp);
271 }
272
Aravind Akella9a844cf2014-02-11 18:58:52 -0800273 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700274 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700275 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
276 mSensorEventBuffer = new sensors_event_t[minBufferSize];
277 mSensorEventScratch = new sensors_event_t[minBufferSize];
Peng Xueb059472016-08-12 16:39:44 -0700278 mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700279 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700280
Aravind Akella18d6d512015-06-18 14:18:28 -0700281 mNextSensorRegIndex = 0;
282 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
283 mLastNSensorRegistrations.push();
284 }
285
286 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700287 mAckReceiver = new SensorEventAckReceiver(this);
288 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700289 run("SensorService", PRIORITY_URGENT_DISPLAY);
Peng Xu98d30f62016-08-01 18:12:11 -0700290
291 // priority can only be changed after run
292 enableSchedFifoMode();
Svet Ganove752a5c2018-01-15 17:14:20 -0800293
294 // Start watching UID changes to apply policy.
Svet Ganove752a5c2018-01-15 17:14:20 -0800295 mUidPolicy->registerSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800296
297 // Start watching sensor privacy changes
298 mSensorPrivacyPolicy->registerSelf();
Svet Ganove752a5c2018-01-15 17:14:20 -0800299 }
300 }
301}
302
303void SensorService::setSensorAccess(uid_t uid, bool hasAccess) {
Brian Duddie967ce172019-06-10 11:08:27 -0700304 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
305 for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
306 if (conn->getUid() == uid) {
307 conn->setSensorAccess(hasAccess);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700308 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700309 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700310}
311
Peng Xu0cc8f802016-04-05 23:46:03 -0700312const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
313 int handle = s->getSensor().getHandle();
Peng Xu6a2d3a02015-12-21 12:00:23 -0800314 int type = s->getSensor().getType();
Peng Xu0cc8f802016-04-05 23:46:03 -0700315 if (mSensors.add(handle, s, isDebug, isVirtual)){
Brian Stack4baa5be2018-09-18 14:03:13 -0700316 mRecentEvent.emplace(handle, new SensorServiceUtil::RecentEventLogger(type));
Peng Xu0cc8f802016-04-05 23:46:03 -0700317 return s->getSensor();
318 } else {
319 return mSensors.getNonSensor();
320 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800321}
322
Peng Xu6a2d3a02015-12-21 12:00:23 -0800323const Sensor& SensorService::registerDynamicSensorLocked(SensorInterface* s, bool isDebug) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700324 return registerSensor(s, isDebug);
Peng Xu2576cb62016-01-20 00:22:09 -0800325}
326
Peng Xu6a2d3a02015-12-21 12:00:23 -0800327bool SensorService::unregisterDynamicSensorLocked(int handle) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700328 bool ret = mSensors.remove(handle);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800329
330 const auto i = mRecentEvent.find(handle);
331 if (i != mRecentEvent.end()) {
332 delete i->second;
333 mRecentEvent.erase(i);
Peng Xu2576cb62016-01-20 00:22:09 -0800334 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700335 return ret;
Peng Xu2576cb62016-01-20 00:22:09 -0800336}
337
Peng Xu0cc8f802016-04-05 23:46:03 -0700338const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
339 return registerSensor(s, isDebug, true);
Mathias Agopianfc328812010-07-14 23:41:37 -0700340}
341
Peng Xu47e96012016-03-28 17:55:56 -0700342SensorService::~SensorService() {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800343 for (auto && entry : mRecentEvent) {
344 delete entry.second;
345 }
Svet Ganove752a5c2018-01-15 17:14:20 -0800346 mUidPolicy->unregisterSelf();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800347 mSensorPrivacyPolicy->unregisterSelf();
Peng Xu47e96012016-03-28 17:55:56 -0700348}
349
350status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700351 String8 result;
Peng Xudd5c5cb2017-03-16 17:39:43 -0700352 if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800353 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700354 IPCThreadState::self()->getCallingPid(),
355 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700356 } else {
Peng Xufba3c112016-09-08 12:36:59 -0700357 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
Aravind Akella841a5922015-06-29 12:37:48 -0700358 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800359 return INVALID_OPERATION;
360 }
Brian Duddie967ce172019-06-10 11:08:27 -0700361 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akella4949c502015-02-11 15:54:35 -0800362 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700363 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700364 // If already in restricted mode. Ignore.
365 if (mCurrentOperatingMode == RESTRICTED) {
366 return status_t(NO_ERROR);
367 }
368 // If in any mode other than normal, ignore.
369 if (mCurrentOperatingMode != NORMAL) {
370 return INVALID_OPERATION;
371 }
Peng Xue36e3472016-11-03 11:57:10 -0700372
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700373 mCurrentOperatingMode = RESTRICTED;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800374 // temporarily stop all sensor direct report and disable sensors
Brian Duddie967ce172019-06-10 11:08:27 -0700375 disableAllSensorsLocked(&connLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700376 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700377 return status_t(NO_ERROR);
378 } else if (args.size() == 1 && args[0] == String16("enable")) {
379 // If currently in restricted mode, reset back to NORMAL mode else ignore.
380 if (mCurrentOperatingMode == RESTRICTED) {
381 mCurrentOperatingMode = NORMAL;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800382 // enable sensors and recover all sensor direct report
Brian Duddie967ce172019-06-10 11:08:27 -0700383 enableAllSensorsLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -0700384 }
Aravind Akella841a5922015-06-29 12:37:48 -0700385 if (mCurrentOperatingMode == DATA_INJECTION) {
386 resetToNormalModeLocked();
387 }
388 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700389 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700390 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
391 if (mCurrentOperatingMode == NORMAL) {
392 dev.disableAllSensors();
393 status_t err = dev.setMode(DATA_INJECTION);
394 if (err == NO_ERROR) {
395 mCurrentOperatingMode = DATA_INJECTION;
396 } else {
397 // Re-enable sensors.
398 dev.enableAllSensors();
399 }
400 mWhiteListedPackage.setTo(String8(args[1]));
401 return NO_ERROR;
402 } else if (mCurrentOperatingMode == DATA_INJECTION) {
403 // Already in DATA_INJECTION mode. Treat this as a no_op.
404 return NO_ERROR;
405 } else {
406 // Transition to data injection mode supported only from NORMAL mode.
407 return INVALID_OPERATION;
408 }
Mike Ma24743862020-01-29 00:36:55 -0800409 } else if (args.size() == 1 && args[0] == String16("--proto")) {
410 return dumpProtoLocked(fd, &connLock);
Peng Xu0cc8f802016-04-05 23:46:03 -0700411 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700412 result.append("No Sensors on the device\n");
Ashutosh Joshi53e5aa92017-07-19 09:52:57 -0700413 result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
Aravind Akella444f2672015-05-07 12:40:52 -0700414 } else {
415 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700416 //
Brian Stack51498e62018-10-03 10:52:21 -0700417 timespec curTime;
418 clock_gettime(CLOCK_REALTIME, &curTime);
419 struct tm* timeinfo = localtime(&(curTime.tv_sec));
420 result.appendFormat("Captured at: %02d:%02d:%02d.%03d\n", timeinfo->tm_hour,
421 timeinfo->tm_min, timeinfo->tm_sec, (int)ns2ms(curTime.tv_nsec));
Peng Xu6a2d3a02015-12-21 12:00:23 -0800422 result.append("Sensor Device:\n");
423 result.append(SensorDevice::getInstance().dump().c_str());
424
425 result.append("Sensor List:\n");
Peng Xu0cc8f802016-04-05 23:46:03 -0700426 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700427
Peng Xu6a2d3a02015-12-21 12:00:23 -0800428 result.append("Fusion States:\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700429 SensorFusion::getInstance().dump(result);
Aravind Akella444f2672015-05-07 12:40:52 -0700430
Peng Xu0cc8f802016-04-05 23:46:03 -0700431 result.append("Recent Sensor events:\n");
Peng Xu6a2d3a02015-12-21 12:00:23 -0800432 for (auto&& i : mRecentEvent) {
433 sp<SensorInterface> s = mSensors.getInterface(i.first);
Peng Xufba3c112016-09-08 12:36:59 -0700434 if (!i.second->isEmpty()) {
435 if (privileged || s->getSensor().getRequiredPermission().isEmpty()) {
436 i.second->setFormat("normal");
437 } else {
438 i.second->setFormat("mask_data");
439 }
Peng Xu6a2d3a02015-12-21 12:00:23 -0800440 // if there is events and sensor does not need special permission.
441 result.appendFormat("%s: ", s->getSensor().getName().string());
442 result.append(i.second->dump().c_str());
443 }
444 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700445
Aravind Akella444f2672015-05-07 12:40:52 -0700446 result.append("Active sensors:\n");
Brian Stackbce04d72019-03-21 10:54:10 -0700447 SensorDevice& dev = SensorDevice::getInstance();
Aravind Akella444f2672015-05-07 12:40:52 -0700448 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
449 int handle = mActiveSensors.keyAt(i);
Brian Stackbce04d72019-03-21 10:54:10 -0700450 if (dev.isSensorActive(handle)) {
451 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
452 getSensorName(handle).string(),
453 handle,
454 mActiveSensors.valueAt(i)->getNumConnections());
455 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700456 }
457
Andreas Gamped4036b62015-07-28 13:49:04 -0700458 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700459 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700460 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
461 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700462 result.appendFormat("Mode :");
463 switch(mCurrentOperatingMode) {
464 case NORMAL:
465 result.appendFormat(" NORMAL\n");
466 break;
467 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700468 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700469 break;
470 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700471 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700472 }
Michael Groover5e1f60b2018-12-04 22:34:29 -0800473 result.appendFormat("Sensor Privacy: %s\n",
474 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
Aravind Akella0e025c52014-06-03 19:19:57 -0700475
Brian Duddie967ce172019-06-10 11:08:27 -0700476 const auto& activeConnections = connLock.getActiveConnections();
477 result.appendFormat("%zd active connections\n", activeConnections.size());
478 for (size_t i=0 ; i < activeConnections.size() ; i++) {
479 result.appendFormat("Connection Number: %zu \n", i);
480 activeConnections[i]->dump(result);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700481 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700482
Brian Duddie967ce172019-06-10 11:08:27 -0700483 const auto& directConnections = connLock.getDirectConnections();
484 result.appendFormat("%zd direct connections\n", directConnections.size());
485 for (size_t i = 0 ; i < directConnections.size() ; i++) {
486 result.appendFormat("Direct connection %zu:\n", i);
487 directConnections[i]->dump(result);
Peng Xue36e3472016-11-03 11:57:10 -0700488 }
489
Aravind Akella18d6d512015-06-18 14:18:28 -0700490 result.appendFormat("Previous Registrations:\n");
491 // Log in the reverse chronological order.
492 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
493 SENSOR_REGISTRATIONS_BUF_SIZE;
494 const int startIndex = currentIndex;
495 do {
496 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
497 if (SensorRegistrationInfo::isSentinel(reg_info)) {
498 // Ignore sentinel, proceed to next item.
499 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
500 SENSOR_REGISTRATIONS_BUF_SIZE;
501 continue;
502 }
Peng Xu51224682017-03-10 16:57:27 -0800503 result.appendFormat("%s\n", reg_info.dump().c_str());
Aravind Akella18d6d512015-06-18 14:18:28 -0700504 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
505 SENSOR_REGISTRATIONS_BUF_SIZE;
506 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700507 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700508 }
509 write(fd, result.string(), result.size());
510 return NO_ERROR;
511}
512
Mike Ma24743862020-01-29 00:36:55 -0800513/**
514 * Dump debugging information as android.service.SensorServiceProto protobuf message using
515 * ProtoOutputStream.
516 *
517 * See proto definition and some notes about ProtoOutputStream in
518 * frameworks/base/core/proto/android/service/sensor_service.proto
519 */
520status_t SensorService::dumpProtoLocked(int fd, ConnectionSafeAutolock* connLock) const {
521 using namespace service::SensorServiceProto;
522 util::ProtoOutputStream proto;
523 const bool privileged = IPCThreadState::self()->getCallingUid() == 0;
524
525 timespec curTime;
526 clock_gettime(CLOCK_REALTIME, &curTime);
527 proto.write(CURRENT_TIME_MS, curTime.tv_sec * 1000 + ns2ms(curTime.tv_nsec));
528
529 // Write SensorDeviceProto
530 uint64_t token = proto.start(SENSOR_DEVICE);
531 SensorDevice::getInstance().dump(&proto);
532 proto.end(token);
533
534 // Write SensorListProto
535 token = proto.start(SENSORS);
536 mSensors.dump(&proto);
537 proto.end(token);
538
539 // Write SensorFusionProto
540 token = proto.start(FUSION_STATE);
541 SensorFusion::getInstance().dump(&proto);
542 proto.end(token);
543
544 // Write SensorEventsProto
545 token = proto.start(SENSOR_EVENTS);
546 for (auto&& i : mRecentEvent) {
547 sp<SensorInterface> s = mSensors.getInterface(i.first);
548 if (!i.second->isEmpty()) {
549 i.second->setFormat(privileged || s->getSensor().getRequiredPermission().isEmpty() ?
550 "normal" : "mask_data");
551 const uint64_t mToken = proto.start(service::SensorEventsProto::RECENT_EVENTS_LOGS);
552 proto.write(service::SensorEventsProto::RecentEventsLog::NAME,
553 std::string(s->getSensor().getName().string()));
554 i.second->dump(&proto);
555 proto.end(mToken);
556 }
557 }
558 proto.end(token);
559
560 // Write ActiveSensorProto
561 SensorDevice& dev = SensorDevice::getInstance();
562 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
563 int handle = mActiveSensors.keyAt(i);
564 if (dev.isSensorActive(handle)) {
565 token = proto.start(ACTIVE_SENSORS);
566 proto.write(service::ActiveSensorProto::NAME,
567 std::string(getSensorName(handle).string()));
568 proto.write(service::ActiveSensorProto::HANDLE, handle);
569 proto.write(service::ActiveSensorProto::NUM_CONNECTIONS,
570 int(mActiveSensors.valueAt(i)->getNumConnections()));
571 proto.end(token);
572 }
573 }
574
575 proto.write(SOCKET_BUFFER_SIZE, int(mSocketBufferSize));
576 proto.write(SOCKET_BUFFER_SIZE_IN_EVENTS, int(mSocketBufferSize / sizeof(sensors_event_t)));
577 proto.write(WAKE_LOCK_ACQUIRED, mWakeLockAcquired);
578
579 switch(mCurrentOperatingMode) {
580 case NORMAL:
581 proto.write(OPERATING_MODE, OP_MODE_NORMAL);
582 break;
583 case RESTRICTED:
584 proto.write(OPERATING_MODE, OP_MODE_RESTRICTED);
585 proto.write(WHITELISTED_PACKAGE, std::string(mWhiteListedPackage.string()));
586 break;
587 case DATA_INJECTION:
588 proto.write(OPERATING_MODE, OP_MODE_DATA_INJECTION);
589 proto.write(WHITELISTED_PACKAGE, std::string(mWhiteListedPackage.string()));
590 break;
591 default:
592 proto.write(OPERATING_MODE, OP_MODE_UNKNOWN);
593 }
594 proto.write(SENSOR_PRIVACY, mSensorPrivacyPolicy->isSensorPrivacyEnabled());
595
596 // Write repeated SensorEventConnectionProto
597 const auto& activeConnections = connLock->getActiveConnections();
598 for (size_t i = 0; i < activeConnections.size(); i++) {
599 token = proto.start(ACTIVE_CONNECTIONS);
600 activeConnections[i]->dump(&proto);
601 proto.end(token);
602 }
603
604 // Write repeated SensorDirectConnectionProto
605 const auto& directConnections = connLock->getDirectConnections();
606 for (size_t i = 0 ; i < directConnections.size() ; i++) {
607 token = proto.start(DIRECT_CONNECTIONS);
608 directConnections[i]->dump(&proto);
609 proto.end(token);
610 }
611
612 // Write repeated SensorRegistrationInfoProto
613 const int startIndex = mNextSensorRegIndex;
614 int curr = startIndex;
615 do {
616 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[curr];
617 if (SensorRegistrationInfo::isSentinel(reg_info)) {
618 // Ignore sentinel, proceed to next item.
619 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
620 continue;
621 }
622 token = proto.start(PREVIOUS_REGISTRATIONS);
623 reg_info.dump(&proto);
624 proto.end(token);
625 curr = (curr + 1 + SENSOR_REGISTRATIONS_BUF_SIZE) % SENSOR_REGISTRATIONS_BUF_SIZE;
626 } while (startIndex != curr);
627
628 return proto.flush(fd) ? OK : UNKNOWN_ERROR;
629}
630
Michael Groover5e1f60b2018-12-04 22:34:29 -0800631void SensorService::disableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700632 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
633 disableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800634}
635
Brian Duddie967ce172019-06-10 11:08:27 -0700636void SensorService::disableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800637 SensorDevice& dev(SensorDevice::getInstance());
Brian Duddie967ce172019-06-10 11:08:27 -0700638 for (const sp<SensorDirectConnection>& connection : connLock->getDirectConnections()) {
639 connection->stopAll(true /* backupRecord */);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800640 }
641 dev.disableAllSensors();
642 // Clear all pending flush connections for all active sensors. If one of the active
643 // connections has called flush() and the underlying sensor has been disabled before a
644 // flush complete event is returned, we need to remove the connection from this queue.
645 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
646 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
647 }
648}
649
650void SensorService::enableAllSensors() {
Brian Duddie967ce172019-06-10 11:08:27 -0700651 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
652 enableAllSensorsLocked(&connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800653}
654
Brian Duddie967ce172019-06-10 11:08:27 -0700655void SensorService::enableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
Michael Groover5e1f60b2018-12-04 22:34:29 -0800656 // sensors should only be enabled if the operating state is not restricted and sensor
657 // privacy is not enabled.
658 if (mCurrentOperatingMode == RESTRICTED || mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
659 ALOGW("Sensors cannot be enabled: mCurrentOperatingMode = %d, sensor privacy = %s",
660 mCurrentOperatingMode,
661 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
662 return;
663 }
664 SensorDevice& dev(SensorDevice::getInstance());
665 dev.enableAllSensors();
Brian Duddie967ce172019-06-10 11:08:27 -0700666 for (const sp<SensorDirectConnection>& connection : connLock->getDirectConnections()) {
667 connection->recoverAll();
Michael Groover5e1f60b2018-12-04 22:34:29 -0800668 }
669}
670
Brian Duddie967ce172019-06-10 11:08:27 -0700671
Svet Ganove752a5c2018-01-15 17:14:20 -0800672// NOTE: This is a remote API - make sure all args are validated
673status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
674 if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
675 return PERMISSION_DENIED;
676 }
677 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
678 return BAD_VALUE;
679 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700680 if (args[0] == String16("set-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800681 return handleSetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700682 } else if (args[0] == String16("reset-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800683 return handleResetUidState(args, err);
Tanmay Patild33a1822019-04-11 18:38:55 -0700684 } else if (args[0] == String16("get-uid-state")) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800685 return handleGetUidState(args, out, err);
686 } else if (args.size() == 1 && args[0] == String16("help")) {
687 printHelp(out);
688 return NO_ERROR;
689 }
690 printHelp(err);
691 return BAD_VALUE;
692}
693
Tanmay Patild33a1822019-04-11 18:38:55 -0700694static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
Svet Ganove752a5c2018-01-15 17:14:20 -0800695 PermissionController pc;
Tanmay Patild33a1822019-04-11 18:38:55 -0700696 uid = pc.getPackageUid(packageName, 0);
Svet Ganove752a5c2018-01-15 17:14:20 -0800697 if (uid <= 0) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700698 ALOGE("Unknown package: '%s'", String8(packageName).string());
699 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
Svet Ganove752a5c2018-01-15 17:14:20 -0800700 return BAD_VALUE;
701 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700702
703 if (userId < 0) {
704 ALOGE("Invalid user: %d", userId);
705 dprintf(err, "Invalid user: %d\n", userId);
706 return BAD_VALUE;
707 }
708
709 uid = multiuser_get_uid(userId, uid);
710 return NO_ERROR;
711}
712
713status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
714 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
715 if (!(args.size() == 3 || args.size() == 5)) {
716 printHelp(err);
717 return BAD_VALUE;
718 }
719
Svet Ganove752a5c2018-01-15 17:14:20 -0800720 bool active = false;
721 if (args[2] == String16("active")) {
722 active = true;
723 } else if ((args[2] != String16("idle"))) {
724 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
725 return BAD_VALUE;
726 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700727
728 int userId = 0;
729 if (args.size() == 5 && args[3] == String16("--user")) {
730 userId = atoi(String8(args[4]));
731 }
732
733 uid_t uid;
734 if (getUidForPackage(args[1], userId, uid, err) != NO_ERROR) {
735 return BAD_VALUE;
736 }
737
Svet Ganove752a5c2018-01-15 17:14:20 -0800738 mUidPolicy->addOverrideUid(uid, active);
739 return NO_ERROR;
740}
741
742status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700743 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
744 if (!(args.size() == 2 || args.size() == 4)) {
745 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800746 return BAD_VALUE;
747 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700748
749 int userId = 0;
750 if (args.size() == 4 && args[2] == String16("--user")) {
751 userId = atoi(String8(args[3]));
752 }
753
754 uid_t uid;
755 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
756 return BAD_VALUE;
757 }
758
Svet Ganove752a5c2018-01-15 17:14:20 -0800759 mUidPolicy->removeOverrideUid(uid);
760 return NO_ERROR;
761}
762
763status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
Tanmay Patild33a1822019-04-11 18:38:55 -0700764 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
765 if (!(args.size() == 2 || args.size() == 4)) {
766 printHelp(err);
Svet Ganove752a5c2018-01-15 17:14:20 -0800767 return BAD_VALUE;
768 }
Tanmay Patild33a1822019-04-11 18:38:55 -0700769
770 int userId = 0;
771 if (args.size() == 4 && args[2] == String16("--user")) {
772 userId = atoi(String8(args[3]));
773 }
774
775 uid_t uid;
776 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
777 return BAD_VALUE;
778 }
779
Svet Ganove752a5c2018-01-15 17:14:20 -0800780 if (mUidPolicy->isUidActive(uid)) {
781 return dprintf(out, "active\n");
782 } else {
783 return dprintf(out, "idle\n");
784 }
785}
786
787status_t SensorService::printHelp(int out) {
788 return dprintf(out, "Sensor service commands:\n"
Tanmay Patild33a1822019-04-11 18:38:55 -0700789 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
790 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
791 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Svet Ganove752a5c2018-01-15 17:14:20 -0800792 " help print this message\n");
793}
794
Peng Xu0cc8f802016-04-05 23:46:03 -0700795//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -0800796void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700797 sensors_event_t const* buffer, const int count) {
798 for (int i=0 ; i<count ; i++) {
799 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700800 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
801 handle = buffer[i].meta_data.sensor;
802 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700803 if (connection->hasSensor(handle)) {
Peng Xu755c4512016-04-07 23:15:14 -0700804 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -0700805 // If this buffer has an event from a one_shot sensor and this connection is registered
806 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu755c4512016-04-07 23:15:14 -0700807 if (si != nullptr &&
Peng Xu0cc8f802016-04-05 23:46:03 -0700808 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
809 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800810 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700811 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700812
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700813 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700814 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700815}
816
Peng Xu47e96012016-03-28 17:55:56 -0700817bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +0000818 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700819
Peng Xueb4d6282015-12-10 18:02:41 -0800820 // each virtual sensor could generate an event per "real" event, that's why we need to size
821 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
822 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -0700823 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700824 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -0700825 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700826
Mathias Agopianf001c922010-11-11 17:58:51 -0800827 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700828
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700829 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700830 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700831 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
832 if (count < 0) {
Brian Stack156da082018-10-01 15:58:53 -0700833 if(count == DEAD_OBJECT && device.isReconnecting()) {
834 device.reconnect();
835 continue;
836 } else {
837 ALOGE("sensor poll failed (%s)", strerror(-count));
838 break;
839 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700840 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700841
842 // Reset sensors_event_t.flags to zero for all events in the buffer.
843 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700844 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700845 }
Brian Duddie967ce172019-06-10 11:08:27 -0700846 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Aravind Akellae148bc22014-09-24 22:12:58 -0700847
Aravind Akella9a844cf2014-02-11 18:58:52 -0800848 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
849 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
850 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
851 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
852 // releasing the wakelock.
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700853 uint32_t wakeEvents = 0;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700854 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700855 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700856 wakeEvents++;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700857 }
858 }
859
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700860 if (wakeEvents > 0) {
861 if (!mWakeLockAcquired) {
862 setWakeLockAcquiredLocked(true);
863 }
864 device.writeWakeLockHandled(wakeEvents);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800865 }
Aravind Akella8493b792014-09-08 15:45:47 -0700866 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800867
Mathias Agopianf001c922010-11-11 17:58:51 -0800868 // handle virtual sensors
869 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700870 sensors_event_t const * const event = mSensorEventBuffer;
Peng Xu755c4512016-04-07 23:15:14 -0700871 if (!mActiveVirtualSensors.empty()) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800872 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700873 SensorFusion& fusion(SensorFusion::getInstance());
874 if (fusion.isEnabled()) {
875 for (size_t i=0 ; i<size_t(count) ; i++) {
876 fusion.process(event[i]);
877 }
878 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700879 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Peng Xu755c4512016-04-07 23:15:14 -0700880 for (int handle : mActiveVirtualSensors) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700881 if (count + k >= minBufferSize) {
882 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700883 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700884 count, k, minBufferSize);
885 break;
886 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800887 sensors_event_t out;
Peng Xu755c4512016-04-07 23:15:14 -0700888 sp<SensorInterface> si = mSensors.getInterface(handle);
889 if (si == nullptr) {
890 ALOGE("handle %d is not an valid virtual sensor", handle);
891 continue;
892 }
893
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700894 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700895 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800896 k++;
897 }
898 }
899 }
900 if (k) {
901 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700902 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800903 count += k;
904 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700905 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700906 }
907 }
908 }
909
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700910 // handle backward compatibility for RotationVector sensor
911 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
912 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700913 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700914 // All the 4 components of the quaternion should be available
915 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700916 mSensorEventBuffer[i].data[4] = -1;
917 }
918 }
919 }
920
Brian Duddie967ce172019-06-10 11:08:27 -0700921 // Cache the list of active connections, since we use it in multiple places below but won't
922 // modify it here
923 const std::vector<sp<SensorEventConnection>> activeConnections = connLock.getActiveConnections();
924
Aravind Akella8493b792014-09-08 15:45:47 -0700925 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700926 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
927 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
928 // SensorEventConnection mapped to the corresponding flush_complete_event in
929 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Yi Kong8f313e32018-07-17 14:13:29 -0700930 mMapFlushEventsToConnections[i] = nullptr;
Aravind Akella8493b792014-09-08 15:45:47 -0700931 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
932 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
933 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
Yi Kong8f313e32018-07-17 14:13:29 -0700934 if (rec != nullptr) {
Aravind Akella8493b792014-09-08 15:45:47 -0700935 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
936 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700937 }
938 }
Peng Xu2576cb62016-01-20 00:22:09 -0800939
940 // handle dynamic sensor meta events, process registration and unregistration of dynamic
941 // sensor based on content of event.
942 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
943 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
944 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
945 const sensor_t& dynamicSensor =
946 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
947 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
948 handle, dynamicSensor.type, dynamicSensor.name);
949
Peng Xu0cc8f802016-04-05 23:46:03 -0700950 if (mSensors.isNewHandle(handle)) {
Peng Xu6a2d3a02015-12-21 12:00:23 -0800951 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
Peng Xu47e96012016-03-28 17:55:56 -0700952 sensor_t s = dynamicSensor;
953 // make sure the dynamic sensor flag is set
954 s.flags |= DYNAMIC_SENSOR_MASK;
955 // force the handle to be consistent
956 s.handle = handle;
Peng Xu6a2d3a02015-12-21 12:00:23 -0800957
958 SensorInterface *si = new HardwareSensor(s, uuid);
Peng Xu2576cb62016-01-20 00:22:09 -0800959
Peng Xu0cc8f802016-04-05 23:46:03 -0700960 // This will release hold on dynamic sensor meta, so it should be called
961 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -0700962 device.handleDynamicSensorConnection(handle, true /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800963 registerDynamicSensorLocked(si);
Peng Xu47e96012016-03-28 17:55:56 -0700964 } else {
965 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
966 }
Peng Xu2576cb62016-01-20 00:22:09 -0800967 } else {
968 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
969 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
970
971 device.handleDynamicSensorConnection(handle, false /*connected*/);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800972 if (!unregisterDynamicSensorLocked(handle)) {
Peng Xu2576cb62016-01-20 00:22:09 -0800973 ALOGE("Dynamic sensor release error.");
974 }
975
Brian Duddie967ce172019-06-10 11:08:27 -0700976 for (const sp<SensorEventConnection>& connection : activeConnections) {
977 connection->removeSensor(handle);
Peng Xu2576cb62016-01-20 00:22:09 -0800978 }
979 }
980 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700981 }
982
Aravind Akella9a844cf2014-02-11 18:58:52 -0800983 // Send our events to clients. Check the state of wake lock for each client and release the
984 // lock if none of the clients need it.
985 bool needsWakeLock = false;
Brian Duddie967ce172019-06-10 11:08:27 -0700986 for (const sp<SensorEventConnection>& connection : activeConnections) {
987 connection->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
988 mMapFlushEventsToConnections);
989 needsWakeLock |= connection->needsWakeLock();
990 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
991 // Early check for one-shot sensors.
992 if (connection->hasOneShotSensors()) {
993 cleanupAutoDisabledSensorLocked(connection, mSensorEventBuffer, count);
Mathias Agopianf001c922010-11-11 17:58:51 -0800994 }
995 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700996
Aravind Akella9a844cf2014-02-11 18:58:52 -0800997 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700998 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800999 }
Aravind Akella8493b792014-09-08 15:45:47 -07001000 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -07001001
Steve Block3c20fbe2012-01-05 23:22:43 +00001002 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -08001003 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -07001004 return false;
1005}
1006
Aravind Akella56ae4262014-07-10 16:01:10 -07001007sp<Looper> SensorService::getLooper() const {
1008 return mLooper;
1009}
1010
Aravind Akellab4373ac2014-10-29 17:55:20 -07001011void SensorService::resetAllWakeLockRefCounts() {
Brian Duddie967ce172019-06-10 11:08:27 -07001012 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1013 for (const sp<SensorEventConnection>& connection : connLock.getActiveConnections()) {
1014 connection->resetWakeLockRefCount();
Aravind Akellab4373ac2014-10-29 17:55:20 -07001015 }
Brian Duddie967ce172019-06-10 11:08:27 -07001016 setWakeLockAcquiredLocked(false);
Aravind Akellab4373ac2014-10-29 17:55:20 -07001017}
1018
1019void SensorService::setWakeLockAcquiredLocked(bool acquire) {
1020 if (acquire) {
1021 if (!mWakeLockAcquired) {
1022 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
1023 mWakeLockAcquired = true;
1024 }
1025 mLooper->wake();
1026 } else {
1027 if (mWakeLockAcquired) {
1028 release_wake_lock(WAKE_LOCK_NAME);
1029 mWakeLockAcquired = false;
1030 }
1031 }
1032}
1033
Aravind Akellab4373ac2014-10-29 17:55:20 -07001034bool SensorService::isWakeLockAcquired() {
1035 Mutex::Autolock _l(mLock);
1036 return mWakeLockAcquired;
1037}
1038
Aravind Akella56ae4262014-07-10 16:01:10 -07001039bool SensorService::SensorEventAckReceiver::threadLoop() {
1040 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -07001041 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -07001042 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001043 bool wakeLockAcquired = mService->isWakeLockAcquired();
1044 int timeout = -1;
1045 if (wakeLockAcquired) timeout = 5000;
1046 int ret = looper->pollOnce(timeout);
1047 if (ret == ALOOPER_POLL_TIMEOUT) {
1048 mService->resetAllWakeLockRefCounts();
1049 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001050 } while(!Thread::exitPending());
1051 return false;
1052}
1053
Aravind Akella9a844cf2014-02-11 18:58:52 -08001054void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -08001055 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -08001056 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -08001057 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
1058 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu6a2d3a02015-12-21 12:00:23 -08001059 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
Peng Xu2576cb62016-01-20 00:22:09 -08001060 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -08001061 }
Peng Xu2576cb62016-01-20 00:22:09 -08001062
Peng Xu6a2d3a02015-12-21 12:00:23 -08001063 auto logger = mRecentEvent.find(buffer[i].sensor);
1064 if (logger != mRecentEvent.end()) {
1065 logger->second->addEvent(buffer[i]);
Peng Xu2576cb62016-01-20 00:22:09 -08001066 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001067 }
Mathias Agopian94e8f682010-11-10 17:50:28 -08001068}
1069
Peng Xu47e96012016-03-28 17:55:56 -07001070void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -08001071 struct compar {
1072 static int cmp(void const* lhs, void const* rhs) {
1073 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
1074 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -07001075 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -08001076 }
1077 };
1078 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
1079}
1080
Mathias Agopian5d270722010-07-19 15:20:39 -07001081String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001082 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -07001083}
1084
Aravind Akellab4099e72013-10-15 15:43:10 -07001085bool SensorService::isVirtualSensor(int handle) const {
Peng Xu755c4512016-04-07 23:15:14 -07001086 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1087 return sensor != nullptr && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -07001088}
1089
Aravind Akella9a844cf2014-02-11 18:58:52 -08001090bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -07001091 int handle = event.sensor;
1092 if (event.type == SENSOR_TYPE_META_DATA) {
1093 handle = event.meta_data.sensor;
1094 }
Peng Xu755c4512016-04-07 23:15:14 -07001095 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1096 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -08001097}
1098
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001099int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
1100 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
1101 // UUID is not supported for this device.
1102 return 0;
1103 }
1104 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
1105 // This sensor can be uniquely identified in the system by
1106 // the combination of its type and name.
1107 return -1;
1108 }
1109
1110 // We have a dynamic sensor.
1111
1112 if (!sHmacGlobalKeyIsValid) {
1113 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1114 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
1115 return 0;
1116 }
1117
1118 // We want each app author/publisher to get a different ID, so that the
1119 // same dynamic sensor cannot be tracked across apps by multiple
1120 // authors/publishers. So we use both our UUID and our User ID.
1121 // Note potential confusion:
1122 // UUID => Universally Unique Identifier.
1123 // UID => User Identifier.
1124 // We refrain from using "uid" except as needed by API to try to
1125 // keep this distinction clear.
1126
1127 auto appUserId = IPCThreadState::self()->getCallingUid();
1128 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
1129 memcpy(uuidAndApp, &uuid, sizeof(uuid));
1130 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
1131
1132 // Now we use our key on our UUID/app combo to get the hash.
1133 uint8_t hash[EVP_MAX_MD_SIZE];
1134 unsigned int hashLen;
1135 if (HMAC(EVP_sha256(),
1136 sHmacGlobalKey, sizeof(sHmacGlobalKey),
1137 uuidAndApp, sizeof(uuidAndApp),
1138 hash, &hashLen) == nullptr) {
1139 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1140 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
1141 return 0;
1142 }
1143
1144 int32_t id = 0;
1145 if (hashLen < sizeof(id)) {
1146 // We never expect this case, but out of paranoia, we handle it.
1147 // Our 'id' length is already quite small, we don't want the
1148 // effective length of it to be even smaller.
1149 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1150 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
1151 return 0;
1152 }
1153
1154 // This is almost certainly less than all of 'hash', but it's as secure
1155 // as we can be with our current 'id' length.
1156 memcpy(&id, hash, sizeof(id));
1157
1158 // Note at the beginning of the function that we return the values of
1159 // 0 and -1 to represent special cases. As a result, we can't return
1160 // those as dynamic sensor IDs. If we happened to hash to one of those
1161 // values, we change 'id' so we report as a dynamic sensor, and not as
1162 // one of those special cases.
1163 if (id == -1) {
1164 id = -2;
1165 } else if (id == 0) {
1166 id = 1;
1167 }
1168 return id;
1169}
1170
1171void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
1172 for (auto &sensor : sensorList) {
1173 int32_t id = getIdFromUuid(sensor.getUuid());
1174 sensor.setId(id);
1175 }
1176}
1177
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001178Vector<Sensor> SensorService::getSensorList(const String16& /* opPackageName */) {
Mathias Agopian33264862012-06-28 19:46:54 -07001179 char value[PROPERTY_VALUE_MAX];
1180 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +00001181 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -07001182 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +00001183 Vector<Sensor> accessibleSensorList;
1184 for (size_t i = 0; i < initialSensorList.size(); i++) {
1185 Sensor sensor = initialSensorList[i];
Nick Vaccaro2c588c52016-11-23 08:44:15 -08001186 accessibleSensorList.add(sensor);
Mathias Agopian33264862012-06-28 19:46:54 -07001187 }
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001188 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Aravind Akella70018042014-04-07 22:52:37 +00001189 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -07001190}
1191
Peng Xu47e96012016-03-28 17:55:56 -07001192Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -08001193 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -07001194 mSensors.forEachSensor(
1195 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
Peng Xu755c4512016-04-07 23:15:14 -07001196 if (sensor.isDynamicSensor()) {
1197 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
1198 accessibleSensorList.add(sensor);
1199 } else {
1200 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
1201 sensor.getName().string(),
1202 sensor.getRequiredPermission().string(),
1203 sensor.getRequiredAppOp());
1204 }
Peng Xu0cc8f802016-04-05 23:46:03 -07001205 }
1206 return true;
1207 });
Greg Kaiser53ca2e02016-06-21 16:11:14 -07001208 makeUuidsIntoIdsForSensorList(accessibleSensorList);
Peng Xu2576cb62016-01-20 00:22:09 -08001209 return accessibleSensorList;
1210}
1211
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001212sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -07001213 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001214 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
1215 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001216 return nullptr;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001217 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001218
1219 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001220 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1221 // operating in DI mode.
1222 if (requestedMode == DATA_INJECTION) {
Yi Kong8f313e32018-07-17 14:13:29 -07001223 if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
1224 if (!isWhiteListedPackage(packageName)) return nullptr;
Aravind Akella841a5922015-06-29 12:37:48 -07001225 }
1226
Mathias Agopian5307d172012-09-18 17:02:43 -07001227 uid_t uid = IPCThreadState::self()->getCallingUid();
Peng Xu58d450a2017-06-08 15:08:39 -07001228 pid_t pid = IPCThreadState::self()->getCallingPid();
1229
1230 String8 connPackageName =
1231 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1232 String16 connOpPackageName =
1233 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
Svet Ganove752a5c2018-01-15 17:14:20 -08001234 bool hasSensorAccess = mUidPolicy->isUidActive(uid);
Peng Xu58d450a2017-06-08 15:08:39 -07001235 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
Svet Ganove752a5c2018-01-15 17:14:20 -08001236 requestedMode == DATA_INJECTION, connOpPackageName, hasSensorAccess));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001237 if (requestedMode == DATA_INJECTION) {
Brian Duddie967ce172019-06-10 11:08:27 -07001238 mConnectionHolder.addEventConnectionIfNotPresent(result);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001239 // Add the associated file descriptor to the Looper for polling whenever there is data to
1240 // be injected.
1241 result->updateLooperRegistration(mLooper);
1242 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001243 return result;
1244}
1245
Aravind Akella841a5922015-06-29 12:37:48 -07001246int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001247 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001248 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001249}
1250
Peng Xue36e3472016-11-03 11:57:10 -07001251sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
1252 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
1253 const native_handle *resource) {
Brian Duddie967ce172019-06-10 11:08:27 -07001254 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001255
Michael Groover5e1f60b2018-12-04 22:34:29 -08001256 // No new direct connections are allowed when sensor privacy is enabled
1257 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1258 ALOGE("Cannot create new direct connections when sensor privacy is enabled");
1259 return nullptr;
1260 }
1261
Peng Xue36e3472016-11-03 11:57:10 -07001262 struct sensors_direct_mem_t mem = {
1263 .type = type,
1264 .format = format,
1265 .size = size,
1266 .handle = resource,
1267 };
1268 uid_t uid = IPCThreadState::self()->getCallingUid();
1269
1270 if (mem.handle == nullptr) {
1271 ALOGE("Failed to clone resource handle");
1272 return nullptr;
1273 }
1274
1275 // check format
1276 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1277 ALOGE("Direct channel format %d is unsupported!", format);
1278 return nullptr;
1279 }
1280
1281 // check for duplication
Brian Duddie967ce172019-06-10 11:08:27 -07001282 for (const sp<SensorDirectConnection>& connection : connLock.getDirectConnections()) {
1283 if (connection->isEquivalent(&mem)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001284 ALOGE("Duplicate create channel request for the same share memory");
Peng Xue36e3472016-11-03 11:57:10 -07001285 return nullptr;
1286 }
1287 }
1288
1289 // check specific to memory type
1290 switch(type) {
1291 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
Brian Duddie0eb46242018-02-15 15:02:29 -08001292 if (resource->numFds < 1) {
1293 ALOGE("Ashmem direct channel requires a memory region to be supplied");
1294 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1295 return nullptr;
1296 }
Peng Xue36e3472016-11-03 11:57:10 -07001297 int fd = resource->data[0];
Anthony Stange3de91192019-11-21 18:35:04 -05001298 if (!ashmem_valid(fd)) {
1299 ALOGE("Supplied Ashmem memory region is invalid");
1300 return nullptr;
1301 }
1302
Peng Xue36e3472016-11-03 11:57:10 -07001303 int size2 = ashmem_get_size_region(fd);
1304 // check size consistency
Brian Duddie0eb46242018-02-15 15:02:29 -08001305 if (size2 < static_cast<int64_t>(size)) {
Peng Xuf88e2b92017-04-10 15:52:58 -07001306 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1307 size, size2);
Peng Xue36e3472016-11-03 11:57:10 -07001308 return nullptr;
1309 }
1310 break;
1311 }
1312 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
Peng Xuf88e2b92017-04-10 15:52:58 -07001313 // no specific checks for gralloc
Peng Xue36e3472016-11-03 11:57:10 -07001314 break;
1315 default:
1316 ALOGE("Unknown direct connection memory type %d", type);
1317 return nullptr;
1318 }
1319
1320 native_handle_t *clone = native_handle_clone(resource);
1321 if (!clone) {
1322 return nullptr;
1323 }
1324
Brian Duddie967ce172019-06-10 11:08:27 -07001325 sp<SensorDirectConnection> conn;
Peng Xue36e3472016-11-03 11:57:10 -07001326 SensorDevice& dev(SensorDevice::getInstance());
1327 int channelHandle = dev.registerDirectChannel(&mem);
1328
1329 if (channelHandle <= 0) {
1330 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1331 } else {
1332 mem.handle = clone;
1333 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1334 }
1335
1336 if (conn == nullptr) {
1337 native_handle_close(clone);
1338 native_handle_delete(clone);
1339 } else {
1340 // add to list of direct connections
1341 // sensor service should never hold pointer or sp of SensorDirectConnection object.
Brian Duddie967ce172019-06-10 11:08:27 -07001342 mConnectionHolder.addDirectConnection(conn);
Peng Xue36e3472016-11-03 11:57:10 -07001343 }
1344 return conn;
1345}
1346
Peng Xudd5c5cb2017-03-16 17:39:43 -07001347int SensorService::setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -07001348 int32_t handle, int32_t type,
1349 const Vector<float> &floats, const Vector<int32_t> &ints) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001350 Mutex::Autolock _l(mLock);
1351
Alexey Polyudov88711e82017-05-23 19:54:04 -07001352 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
Peng Xudd5c5cb2017-03-16 17:39:43 -07001353 return PERMISSION_DENIED;
1354 }
1355
1356 bool isFloat = true;
Alexey Polyudov88711e82017-05-23 19:54:04 -07001357 bool isCustom = false;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001358 size_t expectSize = INT32_MAX;
1359 switch (type) {
1360 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1361 isFloat = true;
1362 expectSize = 3;
1363 break;
1364 case AINFO_LOCAL_GRAVITY:
1365 isFloat = true;
1366 expectSize = 1;
1367 break;
1368 case AINFO_DOCK_STATE:
1369 case AINFO_HIGH_PERFORMANCE_MODE:
1370 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1371 isFloat = false;
1372 expectSize = 1;
1373 break;
1374 default:
Alexey Polyudov88711e82017-05-23 19:54:04 -07001375 // CUSTOM events must only contain float data; it may have variable size
1376 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1377 ints.size() ||
1378 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1379 handle < 0) {
1380 return BAD_VALUE;
1381 }
1382 isFloat = true;
1383 isCustom = true;
1384 expectSize = floats.size();
1385 break;
1386 }
1387
1388 if (!isCustom && handle != -1) {
1389 return BAD_VALUE;
Peng Xudd5c5cb2017-03-16 17:39:43 -07001390 }
1391
1392 // three events: first one is begin tag, last one is end tag, the one in the middle
1393 // is the payload.
1394 sensors_event_t event[3];
1395 int64_t timestamp = elapsedRealtimeNano();
1396 for (sensors_event_t* i = event; i < event + 3; i++) {
1397 *i = (sensors_event_t) {
1398 .version = sizeof(sensors_event_t),
Alexey Polyudov88711e82017-05-23 19:54:04 -07001399 .sensor = handle,
Peng Xudd5c5cb2017-03-16 17:39:43 -07001400 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1401 .timestamp = timestamp++,
1402 .additional_info = (additional_info_event_t) {
1403 .serial = 0
1404 }
1405 };
1406 }
1407
1408 event[0].additional_info.type = AINFO_BEGIN;
1409 event[1].additional_info.type = type;
1410 event[2].additional_info.type = AINFO_END;
1411
1412 if (isFloat) {
1413 if (floats.size() != expectSize) {
1414 return BAD_VALUE;
1415 }
1416 for (size_t i = 0; i < expectSize; ++i) {
1417 event[1].additional_info.data_float[i] = floats[i];
1418 }
1419 } else {
1420 if (ints.size() != expectSize) {
1421 return BAD_VALUE;
1422 }
1423 for (size_t i = 0; i < expectSize; ++i) {
1424 event[1].additional_info.data_int32[i] = ints[i];
1425 }
1426 }
1427
1428 SensorDevice& dev(SensorDevice::getInstance());
1429 for (sensors_event_t* i = event; i < event + 3; i++) {
1430 int ret = dev.injectSensorData(i);
1431 if (ret != NO_ERROR) {
1432 return ret;
1433 }
1434 }
1435 return NO_ERROR;
1436}
1437
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001438status_t SensorService::resetToNormalMode() {
1439 Mutex::Autolock _l(mLock);
1440 return resetToNormalModeLocked();
1441}
1442
1443status_t SensorService::resetToNormalModeLocked() {
1444 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001445 status_t err = dev.setMode(NORMAL);
Aniroop Mathurbfac17e2016-08-31 22:59:44 +05301446 if (err == NO_ERROR) {
1447 mCurrentOperatingMode = NORMAL;
1448 dev.enableAllSensors();
1449 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001450 return err;
1451}
1452
Peng Xu47e96012016-03-28 17:55:56 -07001453void SensorService::cleanupConnection(SensorEventConnection* c) {
Brian Duddie967ce172019-06-10 11:08:27 -07001454 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001455 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001456 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -07001457 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001458 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001459 int handle = mActiveSensors.keyAt(i);
1460 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -07001461 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu755c4512016-04-07 23:15:14 -07001462 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1463 if (sensor != nullptr) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001464 sensor->activate(c, false);
Peng Xu755c4512016-04-07 23:15:14 -07001465 } else {
1466 ALOGE("sensor interface of handle=0x%08x is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001467 }
Aravind Akella8a969552014-09-28 17:52:41 -07001468 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001469 }
1470 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -07001471 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +00001472 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -07001473 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -07001474 c, i, handle);
1475
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -08001476 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +00001477 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001478 mActiveSensors.removeItemsAt(i, 1);
Peng Xu755c4512016-04-07 23:15:14 -07001479 mActiveVirtualSensors.erase(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001480 delete rec;
1481 size--;
1482 } else {
1483 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -07001484 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001485 }
Aravind Akella8a969552014-09-28 17:52:41 -07001486 c->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001487 mConnectionHolder.removeEventConnection(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001488 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -08001489 if (c->needsWakeLock()) {
Brian Duddie967ce172019-06-10 11:08:27 -07001490 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001491 }
Peng Xu4f707f82016-09-26 11:28:32 -07001492
Brian Stack793f4642019-04-18 17:21:34 -07001493 {
1494 Mutex::Autolock packageLock(sPackageTargetVersionLock);
1495 auto iter = sPackageTargetVersion.find(c->mOpPackageName);
1496 if (iter != sPackageTargetVersion.end()) {
1497 sPackageTargetVersion.erase(iter);
1498 }
1499 }
1500
Peng Xu4f707f82016-09-26 11:28:32 -07001501 SensorDevice& dev(SensorDevice::getInstance());
1502 dev.notifyConnectionDestroyed(c);
Mathias Agopianfc328812010-07-14 23:41:37 -07001503}
1504
Peng Xue36e3472016-11-03 11:57:10 -07001505void SensorService::cleanupConnection(SensorDirectConnection* c) {
1506 Mutex::Autolock _l(mLock);
1507
1508 SensorDevice& dev(SensorDevice::getInstance());
1509 dev.unregisterDirectChannel(c->getHalChannelHandle());
Brian Duddie967ce172019-06-10 11:08:27 -07001510 mConnectionHolder.removeDirectConnection(c);
Peng Xue36e3472016-11-03 11:57:10 -07001511}
1512
Peng Xu755c4512016-04-07 23:15:14 -07001513sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -07001514 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -07001515}
1516
Mathias Agopianfc328812010-07-14 23:41:37 -07001517status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001518 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -07001519 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001520 if (mInitCheck != NO_ERROR)
1521 return mInitCheck;
1522
Peng Xu755c4512016-04-07 23:15:14 -07001523 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1524 if (sensor == nullptr ||
1525 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001526 return BAD_VALUE;
1527 }
1528
Brian Duddie967ce172019-06-10 11:08:27 -07001529 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
Peng Xue36e3472016-11-03 11:57:10 -07001530 if (mCurrentOperatingMode != NORMAL
Aravind Akella841a5922015-06-29 12:37:48 -07001531 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001532 return INVALID_OPERATION;
1533 }
1534
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001535 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001536 if (rec == nullptr) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001537 rec = new SensorRecord(connection);
1538 mActiveSensors.add(handle, rec);
1539 if (sensor->isVirtual()) {
Peng Xu755c4512016-04-07 23:15:14 -07001540 mActiveVirtualSensors.emplace(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001541 }
Brian Stack26029ee2019-04-22 17:25:49 -07001542
1543 // There was no SensorRecord for this sensor which means it was previously disabled. Mark
1544 // the recent event as stale to ensure that the previous event is not sent to a client. This
1545 // ensures on-change events that were generated during a previous sensor activation are not
1546 // erroneously sent to newly connected clients, especially if a second client registers for
1547 // an on-change sensor before the first client receives the updated event. Once an updated
1548 // event is received, the recent events will be marked as current, and any new clients will
1549 // immediately receive the most recent event.
1550 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
1551 auto logger = mRecentEvent.find(handle);
1552 if (logger != mRecentEvent.end()) {
1553 logger->second->setLastEventStale();
1554 }
1555 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001556 } else {
1557 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001558 // this sensor is already activated, but we are adding a connection that uses it.
1559 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001560 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001561 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001562 // NOTE: The wake_up flag of this event may get set to
1563 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xu6a2d3a02015-12-21 12:00:23 -08001564
1565 auto logger = mRecentEvent.find(handle);
1566 if (logger != mRecentEvent.end()) {
Aravind Akella444f2672015-05-07 12:40:52 -07001567 sensors_event_t event;
Brian Stack0b858c12018-10-19 10:53:25 -07001568 // Verify that the last sensor event was generated from the current activation
1569 // of the sensor. If not, it is possible for an on-change sensor to receive a
1570 // sensor event that is stale if two clients re-activate the sensor
1571 // simultaneously.
1572 if(logger->second->populateLastEventIfCurrent(&event)) {
Aravind Akella444f2672015-05-07 12:40:52 -07001573 event.sensor = handle;
1574 if (event.version == sizeof(sensors_event_t)) {
1575 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1576 setWakeLockAcquiredLocked(true);
1577 }
Yi Kong8f313e32018-07-17 14:13:29 -07001578 connection->sendEvents(&event, 1, nullptr);
Aravind Akella444f2672015-05-07 12:40:52 -07001579 if (!connection->needsWakeLock() && mWakeLockAcquired) {
Brian Duddie967ce172019-06-10 11:08:27 -07001580 checkWakeLockStateLocked(&connLock);
Aravind Akella444f2672015-05-07 12:40:52 -07001581 }
1582 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001583 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001584 }
1585 }
1586 }
1587 }
1588
1589 if (connection->addSensor(handle)) {
1590 BatteryService::enableSensor(connection->getUid(), handle);
1591 // the sensor was added (which means it wasn't already there)
1592 // so, see if this connection becomes active
Brian Duddie967ce172019-06-10 11:08:27 -07001593 mConnectionHolder.addEventConnectionIfNotPresent(connection);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001594 } else {
1595 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1596 handle, connection.get());
1597 }
1598
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301599 // Check maximum delay for the sensor.
Jim Kaye663720b2017-05-08 09:07:27 -07001600 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
Aniroop Mathurd8a5ce32016-06-01 22:17:05 +05301601 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1602 samplingPeriodNs = maxDelayNs;
1603 }
1604
Aravind Akella724d91d2013-06-27 12:04:23 -07001605 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1606 if (samplingPeriodNs < minDelayNs) {
1607 samplingPeriodNs = minDelayNs;
1608 }
1609
Aravind Akella6c2664a2014-08-13 12:24:50 -07001610 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1611 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001612 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1613
Aravind Akella4949c502015-02-11 15:54:35 -08001614 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001615 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001616
Peng Xu20483c42015-10-26 15:14:43 -07001617 // Call flush() before calling activate() on the sensor. Wait for a first
1618 // flush complete event before sending events on this connection. Ignore
1619 // one-shot sensors which don't support flush(). Ignore on-change sensors
1620 // to maintain the on-change logic (any on-change events except the initial
1621 // one should be trigger by a change in value). Also if this sensor isn't
1622 // already active, don't call flush().
1623 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001624 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001625 rec->getNumConnections() > 1) {
1626 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001627 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001628 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001629 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001630 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001631 } else {
1632 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001633 }
1634 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001635
1636 if (err == NO_ERROR) {
1637 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1638 err = sensor->activate(connection.get(), true);
1639 }
1640
Aravind Akella8a969552014-09-28 17:52:41 -07001641 if (err == NO_ERROR) {
1642 connection->updateLooperRegistration(mLooper);
Peng Xu51224682017-03-10 16:57:27 -08001643
Brian Stack240d1d62019-05-17 09:49:39 -07001644 if (sensor->getSensor().getRequiredPermission().size() > 0 &&
1645 sensor->getSensor().getRequiredAppOp() >= 0) {
Brian Stackc225aa12019-04-19 09:30:25 -07001646 connection->mHandleToAppOp[handle] = sensor->getSensor().getRequiredAppOp();
1647 }
1648
Peng Xu51224682017-03-10 16:57:27 -08001649 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1650 SensorRegistrationInfo(handle, connection->getPackageName(),
1651 samplingPeriodNs, maxBatchReportLatencyNs, true);
Aravind Akella18d6d512015-06-18 14:18:28 -07001652 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001653 }
1654
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001655 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001656 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001657 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001658 }
1659 return err;
1660}
1661
Peng Xu47e96012016-03-28 17:55:56 -07001662status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001663 if (mInitCheck != NO_ERROR)
1664 return mInitCheck;
1665
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001666 Mutex::Autolock _l(mLock);
1667 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001668 if (err == NO_ERROR) {
Peng Xu755c4512016-04-07 23:15:14 -07001669 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1670 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001671
1672 }
1673 if (err == NO_ERROR) {
Peng Xu51224682017-03-10 16:57:27 -08001674 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1675 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
Aravind Akella18d6d512015-06-18 14:18:28 -07001676 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001677 }
1678 return err;
1679}
1680
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001681status_t SensorService::cleanupWithoutDisable(
1682 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001683 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001684 return cleanupWithoutDisableLocked(connection, handle);
1685}
1686
1687status_t SensorService::cleanupWithoutDisableLocked(
1688 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001689 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001690 if (rec) {
1691 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001692 if (connection->removeSensor(handle)) {
1693 BatteryService::disableSensor(connection->getUid(), handle);
1694 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001695 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001696 connection->updateLooperRegistration(mLooper);
Brian Duddie967ce172019-06-10 11:08:27 -07001697 mConnectionHolder.removeEventConnection(connection);
Mathias Agopianfc328812010-07-14 23:41:37 -07001698 }
1699 // see if this sensor becomes inactive
1700 if (rec->removeConnection(connection)) {
1701 mActiveSensors.removeItem(handle);
Peng Xu755c4512016-04-07 23:15:14 -07001702 mActiveVirtualSensors.erase(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001703 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001704 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001705 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001706 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001707 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001708}
1709
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001710status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001711 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001712 if (mInitCheck != NO_ERROR)
1713 return mInitCheck;
1714
Peng Xu755c4512016-04-07 23:15:14 -07001715 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1716 if (sensor == nullptr ||
1717 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001718 return BAD_VALUE;
1719 }
1720
Mathias Agopian1cd70002010-07-21 15:59:50 -07001721 if (ns < 0)
1722 return BAD_VALUE;
1723
Mathias Agopian62569ec2011-11-07 21:21:47 -08001724 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1725 if (ns < minDelayNs) {
1726 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001727 }
1728
Mathias Agopianf001c922010-11-11 17:58:51 -08001729 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001730}
1731
Svetoslavb412f6e2015-04-29 16:50:41 -07001732status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1733 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001734 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001735 SensorDevice& dev(SensorDevice::getInstance());
1736 const int halVersion = dev.getHalDeviceVersion();
1737 status_t err(NO_ERROR);
1738 Mutex::Autolock _l(mLock);
1739 // Loop through all sensors for this connection and call flush on each of them.
1740 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1741 const int handle = connection->mSensorInfo.keyAt(i);
Peng Xu755c4512016-04-07 23:15:14 -07001742 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1743 if (sensor == nullptr) {
1744 continue;
1745 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001746 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1747 ALOGE("flush called on a one-shot sensor");
1748 err = INVALID_OPERATION;
1749 continue;
1750 }
Aravind Akella8493b792014-09-08 15:45:47 -07001751 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001752 // For older devices just increment pending flush count which will send a trivial
1753 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001754 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001755 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001756 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1757 err = INVALID_OPERATION;
1758 continue;
1759 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001760 status_t err_flush = sensor->flush(connection.get(), handle);
1761 if (err_flush == NO_ERROR) {
1762 SensorRecord* rec = mActiveSensors.valueFor(handle);
Yi Kong8f313e32018-07-17 14:13:29 -07001763 if (rec != nullptr) rec->addPendingFlushConnection(connection);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001764 }
1765 err = (err_flush != NO_ERROR) ? err_flush : err;
1766 }
Aravind Akella70018042014-04-07 22:52:37 +00001767 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001768 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001769}
Aravind Akella70018042014-04-07 22:52:37 +00001770
Svetoslavb412f6e2015-04-29 16:50:41 -07001771bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1772 const String16& opPackageName) {
Brian Stack793f4642019-04-18 17:21:34 -07001773 // Check if a permission is required for this sensor
1774 if (sensor.getRequiredPermission().length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001775 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001776 }
1777
Brian Stack793f4642019-04-18 17:21:34 -07001778 const int32_t opCode = sensor.getRequiredAppOp();
1779 const int32_t appOpMode = sAppOpsManager.checkOp(opCode,
1780 IPCThreadState::self()->getCallingUid(), opPackageName);
Brian Stack6a700f92019-05-08 17:02:53 -07001781 bool appOpAllowed = appOpMode == AppOpsManager::MODE_ALLOWED;
Brian Stack793f4642019-04-18 17:21:34 -07001782
Brian Stack793f4642019-04-18 17:21:34 -07001783 bool canAccess = false;
Brian Stack6a700f92019-05-08 17:02:53 -07001784 if (hasPermissionForSensor(sensor)) {
1785 // Ensure that the AppOp is allowed, or that there is no necessary app op for the sensor
1786 if (opCode < 0 || appOpAllowed) {
Brian Stack793f4642019-04-18 17:21:34 -07001787 canAccess = true;
Brian Stack6a700f92019-05-08 17:02:53 -07001788 }
1789 } else if (sensor.getType() == SENSOR_TYPE_STEP_COUNTER ||
1790 sensor.getType() == SENSOR_TYPE_STEP_DETECTOR) {
1791 int targetSdkVersion = getTargetSdkVersion(opPackageName);
1792 // Allow access to the sensor if the application targets pre-Q, which is before the
1793 // requirement to hold the AR permission to access Step Counter and Step Detector events
1794 // was introduced, and the user hasn't revoked the app op.
1795 //
1796 // Verifying the app op is required to ensure that the user hasn't revoked the necessary
1797 // permissions to access the Step Detector and Step Counter when the application targets
1798 // pre-Q. Without this check, if the user revokes the pre-Q install-time GMS Core AR
1799 // permission, the app would still be able to receive Step Counter and Step Detector events.
1800 if (appOpAllowed &&
1801 targetSdkVersion > 0 &&
1802 targetSdkVersion <= __ANDROID_API_P__) {
1803 canAccess = true;
Brian Stack793f4642019-04-18 17:21:34 -07001804 }
1805 }
1806
1807 if (canAccess) {
1808 sAppOpsManager.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName);
1809 } else {
1810 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1811 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
1812 }
1813
1814 return canAccess;
1815}
1816
1817bool SensorService::hasPermissionForSensor(const Sensor& sensor) {
Svetoslavb412f6e2015-04-29 16:50:41 -07001818 bool hasPermission = false;
Brian Stack793f4642019-04-18 17:21:34 -07001819 const String8& requiredPermission = sensor.getRequiredPermission();
Svetoslavb412f6e2015-04-29 16:50:41 -07001820
1821 // Runtime permissions can't use the cache as they may change.
1822 if (sensor.isRequiredPermissionRuntime()) {
1823 hasPermission = checkPermission(String16(requiredPermission),
1824 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001825 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001826 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1827 }
Brian Stack793f4642019-04-18 17:21:34 -07001828 return hasPermission;
1829}
Svetoslavb412f6e2015-04-29 16:50:41 -07001830
Brian Stack793f4642019-04-18 17:21:34 -07001831int SensorService::getTargetSdkVersion(const String16& opPackageName) {
1832 Mutex::Autolock packageLock(sPackageTargetVersionLock);
1833 int targetSdkVersion = -1;
1834 auto entry = sPackageTargetVersion.find(opPackageName);
1835 if (entry != sPackageTargetVersion.end()) {
1836 targetSdkVersion = entry->second;
1837 } else {
1838 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
1839 if (binder != nullptr) {
1840 sp<content::pm::IPackageManagerNative> packageManager =
1841 interface_cast<content::pm::IPackageManagerNative>(binder);
1842 if (packageManager != nullptr) {
1843 binder::Status status = packageManager->getTargetSdkVersionForPackage(
1844 opPackageName, &targetSdkVersion);
1845 if (!status.isOk()) {
1846 targetSdkVersion = -1;
1847 }
1848 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001849 }
Brian Stack793f4642019-04-18 17:21:34 -07001850 sPackageTargetVersion[opPackageName] = targetSdkVersion;
Svetoslavb412f6e2015-04-29 16:50:41 -07001851 }
Brian Stack793f4642019-04-18 17:21:34 -07001852 return targetSdkVersion;
Aravind Akella70018042014-04-07 22:52:37 +00001853}
1854
Aravind Akella9a844cf2014-02-11 18:58:52 -08001855void SensorService::checkWakeLockState() {
Brian Duddie967ce172019-06-10 11:08:27 -07001856 ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
1857 checkWakeLockStateLocked(&connLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001858}
1859
Brian Duddie967ce172019-06-10 11:08:27 -07001860void SensorService::checkWakeLockStateLocked(ConnectionSafeAutolock* connLock) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001861 if (!mWakeLockAcquired) {
1862 return;
1863 }
1864 bool releaseLock = true;
Brian Duddie967ce172019-06-10 11:08:27 -07001865 for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
1866 if (connection->needsWakeLock()) {
1867 releaseLock = false;
1868 break;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001869 }
1870 }
1871 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001872 setWakeLockAcquiredLocked(false);
1873 }
1874}
1875
1876void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1877 Mutex::Autolock _l(mLock);
1878 connection->writeToSocketFromCache();
1879 if (connection->needsWakeLock()) {
1880 setWakeLockAcquiredLocked(true);
1881 }
1882}
1883
Aravind Akella4949c502015-02-11 15:54:35 -08001884bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001885 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001886}
1887
Brian Stack5180e462019-03-08 17:15:19 -08001888bool SensorService::isOperationPermitted(const String16& opPackageName) {
Peng Xue36e3472016-11-03 11:57:10 -07001889 Mutex::Autolock _l(mLock);
Brian Stack5180e462019-03-08 17:15:19 -08001890 if (mCurrentOperatingMode == RESTRICTED) {
Peng Xue36e3472016-11-03 11:57:10 -07001891 String8 package(opPackageName);
Brian Stack5180e462019-03-08 17:15:19 -08001892 return isWhiteListedPackage(package);
Peng Xue36e3472016-11-03 11:57:10 -07001893 }
Brian Stack5180e462019-03-08 17:15:19 -08001894 return true;
Peng Xue36e3472016-11-03 11:57:10 -07001895}
1896
Svet Ganove752a5c2018-01-15 17:14:20 -08001897void SensorService::UidPolicy::registerSelf() {
1898 ActivityManager am;
1899 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
1900 | ActivityManager::UID_OBSERVER_IDLE
1901 | ActivityManager::UID_OBSERVER_ACTIVE,
1902 ActivityManager::PROCESS_STATE_UNKNOWN,
1903 String16("android"));
1904}
1905
1906void SensorService::UidPolicy::unregisterSelf() {
1907 ActivityManager am;
1908 am.unregisterUidObserver(this);
1909}
1910
1911void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
1912 onUidIdle(uid, disabled);
1913}
1914
1915void SensorService::UidPolicy::onUidActive(uid_t uid) {
1916 {
1917 Mutex::Autolock _l(mUidLock);
1918 mActiveUids.insert(uid);
1919 }
1920 sp<SensorService> service = mService.promote();
1921 if (service != nullptr) {
1922 service->setSensorAccess(uid, true);
1923 }
1924}
1925
1926void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
1927 bool deleted = false;
1928 {
1929 Mutex::Autolock _l(mUidLock);
1930 if (mActiveUids.erase(uid) > 0) {
1931 deleted = true;
1932 }
1933 }
1934 if (deleted) {
1935 sp<SensorService> service = mService.promote();
1936 if (service != nullptr) {
1937 service->setSensorAccess(uid, false);
1938 }
1939 }
1940}
1941
1942void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
1943 updateOverrideUid(uid, active, true);
1944}
1945
1946void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
1947 updateOverrideUid(uid, false, false);
1948}
1949
1950void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
1951 bool wasActive = false;
1952 bool isActive = false;
1953 {
1954 Mutex::Autolock _l(mUidLock);
1955 wasActive = isUidActiveLocked(uid);
1956 mOverrideUids.erase(uid);
1957 if (insert) {
1958 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
1959 }
1960 isActive = isUidActiveLocked(uid);
1961 }
1962 if (wasActive != isActive) {
1963 sp<SensorService> service = mService.promote();
1964 if (service != nullptr) {
1965 service->setSensorAccess(uid, isActive);
1966 }
1967 }
1968}
1969
1970bool SensorService::UidPolicy::isUidActive(uid_t uid) {
1971 // Non-app UIDs are considered always active
1972 if (uid < FIRST_APPLICATION_UID) {
1973 return true;
1974 }
1975 Mutex::Autolock _l(mUidLock);
1976 return isUidActiveLocked(uid);
1977}
1978
1979bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
1980 // Non-app UIDs are considered always active
1981 if (uid < FIRST_APPLICATION_UID) {
1982 return true;
1983 }
1984 auto it = mOverrideUids.find(uid);
1985 if (it != mOverrideUids.end()) {
1986 return it->second;
1987 }
1988 return mActiveUids.find(uid) != mActiveUids.end();
1989}
1990
Michael Groover5e1f60b2018-12-04 22:34:29 -08001991void SensorService::SensorPrivacyPolicy::registerSelf() {
1992 SensorPrivacyManager spm;
1993 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1994 spm.addSensorPrivacyListener(this);
1995}
1996
1997void SensorService::SensorPrivacyPolicy::unregisterSelf() {
1998 SensorPrivacyManager spm;
1999 spm.removeSensorPrivacyListener(this);
2000}
2001
2002bool SensorService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
2003 return mSensorPrivacyEnabled;
2004}
2005
2006binder::Status SensorService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
2007 mSensorPrivacyEnabled = enabled;
2008 sp<SensorService> service = mService.promote();
2009 if (service != nullptr) {
2010 if (enabled) {
2011 service->disableAllSensors();
2012 } else {
2013 service->enableAllSensors();
2014 }
2015 }
2016 return binder::Status::ok();
2017}
Brian Duddie967ce172019-06-10 11:08:27 -07002018
2019SensorService::ConnectionSafeAutolock::ConnectionSafeAutolock(
2020 SensorService::SensorConnectionHolder& holder, Mutex& mutex)
2021 : mConnectionHolder(holder), mAutolock(mutex) {}
2022
2023template<typename ConnectionType>
2024const std::vector<sp<ConnectionType>>& SensorService::ConnectionSafeAutolock::getConnectionsHelper(
2025 const SortedVector<wp<ConnectionType>>& connectionList,
2026 std::vector<std::vector<sp<ConnectionType>>>* referenceHolder) {
2027 referenceHolder->emplace_back();
2028 std::vector<sp<ConnectionType>>& connections = referenceHolder->back();
2029 for (const wp<ConnectionType>& weakConnection : connectionList){
2030 sp<ConnectionType> connection = weakConnection.promote();
2031 if (connection != nullptr) {
2032 connections.push_back(std::move(connection));
2033 }
2034 }
2035 return connections;
2036}
2037
2038const std::vector<sp<SensorService::SensorEventConnection>>&
2039 SensorService::ConnectionSafeAutolock::getActiveConnections() {
2040 return getConnectionsHelper(mConnectionHolder.mActiveConnections,
2041 &mReferencedActiveConnections);
2042}
2043
2044const std::vector<sp<SensorService::SensorDirectConnection>>&
2045 SensorService::ConnectionSafeAutolock::getDirectConnections() {
2046 return getConnectionsHelper(mConnectionHolder.mDirectConnections,
2047 &mReferencedDirectConnections);
2048}
2049
2050void SensorService::SensorConnectionHolder::addEventConnectionIfNotPresent(
2051 const sp<SensorService::SensorEventConnection>& connection) {
2052 if (mActiveConnections.indexOf(connection) < 0) {
2053 mActiveConnections.add(connection);
2054 }
2055}
2056
2057void SensorService::SensorConnectionHolder::removeEventConnection(
2058 const wp<SensorService::SensorEventConnection>& connection) {
2059 mActiveConnections.remove(connection);
2060}
2061
2062void SensorService::SensorConnectionHolder::addDirectConnection(
2063 const sp<SensorService::SensorDirectConnection>& connection) {
2064 mDirectConnections.add(connection);
2065}
2066
2067void SensorService::SensorConnectionHolder::removeDirectConnection(
2068 const wp<SensorService::SensorDirectConnection>& connection) {
2069 mDirectConnections.remove(connection);
2070}
2071
2072SensorService::ConnectionSafeAutolock SensorService::SensorConnectionHolder::lock(Mutex& mutex) {
2073 return ConnectionSafeAutolock(*this, mutex);
2074}
2075
2076} // namespace android