1 /*
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 */
16 #include <android/content/pm/IPackageManagerNative.h>
17 #include <binder/ActivityManager.h>
18 #include <binder/BinderService.h>
19 #include <binder/IServiceManager.h>
20 #include <binder/PermissionCache.h>
21 #include <binder/PermissionController.h>
22 #include <cutils/ashmem.h>
23 #include <cutils/misc.h>
24 #include <cutils/properties.h>
25 #include <hardware/sensors.h>
26 #include <hardware_legacy/power.h>
27 #include <log/log.h>
28 #include <openssl/digest.h>
29 #include <openssl/hmac.h>
30 #include <openssl/rand.h>
31 #include <sensor/SensorEventQueue.h>
32 #include <sensorprivacy/SensorPrivacyManager.h>
33 #include <utils/SystemClock.h>
34
35 #include "BatteryService.h"
36 #include "CorrectedGyroSensor.h"
37 #include "GravitySensor.h"
38 #include "LinearAccelerationSensor.h"
39 #include "OrientationSensor.h"
40 #include "RotationVectorSensor.h"
41 #include "SensorFusion.h"
42 #include "SensorInterface.h"
43
44 #include "SensorService.h"
45 #include "SensorDirectConnection.h"
46 #include "SensorEventAckReceiver.h"
47 #include "SensorEventConnection.h"
48 #include "SensorRecord.h"
49 #include "SensorRegistrationInfo.h"
50
51 #include <ctime>
52 #include <inttypes.h>
53 #include <math.h>
54 #include <sched.h>
55 #include <stdint.h>
56 #include <sys/socket.h>
57 #include <sys/stat.h>
58 #include <sys/types.h>
59 #include <unistd.h>
60
61 #include <private/android_filesystem_config.h>
62
63 namespace android {
64 // ---------------------------------------------------------------------------
65
66 /*
67 * Notes:
68 *
69 * - what about a gyro-corrected magnetic-field sensor?
70 * - run mag sensor from time to time to force calibration
71 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
72 *
73 */
74
75 const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
76 uint8_t SensorService::sHmacGlobalKey[128] = {};
77 bool SensorService::sHmacGlobalKeyIsValid = false;
78 std::map<String16, int> SensorService::sPackageTargetVersion;
79 Mutex SensorService::sPackageTargetVersionLock;
80 AppOpsManager SensorService::sAppOpsManager;
81
82 #define SENSOR_SERVICE_DIR "/data/system/sensor_service"
83 #define SENSOR_SERVICE_HMAC_KEY_FILE SENSOR_SERVICE_DIR "/hmac_key"
84 #define SENSOR_SERVICE_SCHED_FIFO_PRIORITY 10
85
86 // Permissions.
87 static const String16 sDumpPermission("android.permission.DUMP");
88 static const String16 sLocationHardwarePermission("android.permission.LOCATION_HARDWARE");
89 static const String16 sManageSensorsPermission("android.permission.MANAGE_SENSORS");
90
SensorService()91 SensorService::SensorService()
92 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
93 mWakeLockAcquired(false) {
94 mUidPolicy = new UidPolicy(this);
95 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
96 }
97
initializeHmacKey()98 bool SensorService::initializeHmacKey() {
99 int fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_RDONLY|O_CLOEXEC);
100 if (fd != -1) {
101 int result = read(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
102 close(fd);
103 if (result == sizeof(sHmacGlobalKey)) {
104 return true;
105 }
106 ALOGW("Unable to read HMAC key; generating new one.");
107 }
108
109 if (RAND_bytes(sHmacGlobalKey, sizeof(sHmacGlobalKey)) == -1) {
110 ALOGW("Can't generate HMAC key; dynamic sensor getId() will be wrong.");
111 return false;
112 }
113
114 // We need to make sure this is only readable to us.
115 bool wroteKey = false;
116 mkdir(SENSOR_SERVICE_DIR, S_IRWXU);
117 fd = open(SENSOR_SERVICE_HMAC_KEY_FILE, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC,
118 S_IRUSR|S_IWUSR);
119 if (fd != -1) {
120 int result = write(fd, sHmacGlobalKey, sizeof(sHmacGlobalKey));
121 close(fd);
122 wroteKey = (result == sizeof(sHmacGlobalKey));
123 }
124 if (wroteKey) {
125 ALOGI("Generated new HMAC key.");
126 } else {
127 ALOGW("Unable to write HMAC key; dynamic sensor getId() will change "
128 "after reboot.");
129 }
130 // Even if we failed to write the key we return true, because we did
131 // initialize the HMAC key.
132 return true;
133 }
134
135 // Set main thread to SCHED_FIFO to lower sensor event latency when system is under load
enableSchedFifoMode()136 void SensorService::enableSchedFifoMode() {
137 struct sched_param param = {0};
138 param.sched_priority = SENSOR_SERVICE_SCHED_FIFO_PRIORITY;
139 if (sched_setscheduler(getTid(), SCHED_FIFO | SCHED_RESET_ON_FORK, ¶m) != 0) {
140 ALOGE("Couldn't set SCHED_FIFO for SensorService thread");
141 }
142 }
143
onFirstRef()144 void SensorService::onFirstRef() {
145 ALOGD("nuSensorService starting...");
146 SensorDevice& dev(SensorDevice::getInstance());
147
148 sHmacGlobalKeyIsValid = initializeHmacKey();
149
150 if (dev.initCheck() == NO_ERROR) {
151 sensor_t const* list;
152 ssize_t count = dev.getSensorList(&list);
153 if (count > 0) {
154 ssize_t orientationIndex = -1;
155 bool hasGyro = false, hasAccel = false, hasMag = false;
156 uint32_t virtualSensorsNeeds =
157 (1<<SENSOR_TYPE_GRAVITY) |
158 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
159 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
160 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
161 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
162
163 for (ssize_t i=0 ; i<count ; i++) {
164 bool useThisSensor=true;
165
166 switch (list[i].type) {
167 case SENSOR_TYPE_ACCELEROMETER:
168 hasAccel = true;
169 break;
170 case SENSOR_TYPE_MAGNETIC_FIELD:
171 hasMag = true;
172 break;
173 case SENSOR_TYPE_ORIENTATION:
174 orientationIndex = i;
175 break;
176 case SENSOR_TYPE_GYROSCOPE:
177 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
178 hasGyro = true;
179 break;
180 case SENSOR_TYPE_GRAVITY:
181 case SENSOR_TYPE_LINEAR_ACCELERATION:
182 case SENSOR_TYPE_ROTATION_VECTOR:
183 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
184 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
185 if (IGNORE_HARDWARE_FUSION) {
186 useThisSensor = false;
187 } else {
188 virtualSensorsNeeds &= ~(1<<list[i].type);
189 }
190 break;
191 }
192 if (useThisSensor) {
193 registerSensor( new HardwareSensor(list[i]) );
194 }
195 }
196
197 // it's safe to instantiate the SensorFusion object here
198 // (it wants to be instantiated after h/w sensors have been
199 // registered)
200 SensorFusion::getInstance();
201
202 if (hasGyro && hasAccel && hasMag) {
203 // Add Android virtual sensors if they're not already
204 // available in the HAL
205 bool needRotationVector =
206 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
207
208 registerSensor(new RotationVectorSensor(), !needRotationVector, true);
209 registerSensor(new OrientationSensor(), !needRotationVector, true);
210
211 bool needLinearAcceleration =
212 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
213
214 registerSensor(new LinearAccelerationSensor(list, count),
215 !needLinearAcceleration, true);
216
217 // virtual debugging sensors are not for user
218 registerSensor( new CorrectedGyroSensor(list, count), true, true);
219 registerSensor( new GyroDriftSensor(), true, true);
220 }
221
222 if (hasAccel && hasGyro) {
223 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
224 registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
225
226 bool needGameRotationVector =
227 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
228 registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
229 }
230
231 if (hasAccel && hasMag) {
232 bool needGeoMagRotationVector =
233 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
234 registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true);
235 }
236
237 // Check if the device really supports batching by looking at the FIFO event
238 // counts for each sensor.
239 bool batchingSupported = false;
240 mSensors.forEachSensor(
241 [&batchingSupported] (const Sensor& s) -> bool {
242 if (s.getFifoMaxEventCount() > 0) {
243 batchingSupported = true;
244 }
245 return !batchingSupported;
246 });
247
248 if (batchingSupported) {
249 // Increase socket buffer size to a max of 100 KB for batching capabilities.
250 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
251 } else {
252 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
253 }
254
255 // Compare the socketBufferSize value against the system limits and limit
256 // it to maxSystemSocketBufferSize if necessary.
257 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
258 char line[128];
259 if (fp != nullptr && fgets(line, sizeof(line), fp) != nullptr) {
260 line[sizeof(line) - 1] = '\0';
261 size_t maxSystemSocketBufferSize;
262 sscanf(line, "%zu", &maxSystemSocketBufferSize);
263 if (mSocketBufferSize > maxSystemSocketBufferSize) {
264 mSocketBufferSize = maxSystemSocketBufferSize;
265 }
266 }
267 if (fp) {
268 fclose(fp);
269 }
270
271 mWakeLockAcquired = false;
272 mLooper = new Looper(false);
273 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
274 mSensorEventBuffer = new sensors_event_t[minBufferSize];
275 mSensorEventScratch = new sensors_event_t[minBufferSize];
276 mMapFlushEventsToConnections = new wp<const SensorEventConnection> [minBufferSize];
277 mCurrentOperatingMode = NORMAL;
278
279 mNextSensorRegIndex = 0;
280 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
281 mLastNSensorRegistrations.push();
282 }
283
284 mInitCheck = NO_ERROR;
285 mAckReceiver = new SensorEventAckReceiver(this);
286 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
287 run("SensorService", PRIORITY_URGENT_DISPLAY);
288
289 // priority can only be changed after run
290 enableSchedFifoMode();
291
292 // Start watching UID changes to apply policy.
293 mUidPolicy->registerSelf();
294
295 // Start watching sensor privacy changes
296 mSensorPrivacyPolicy->registerSelf();
297 }
298 }
299 }
300
setSensorAccess(uid_t uid,bool hasAccess)301 void SensorService::setSensorAccess(uid_t uid, bool hasAccess) {
302 SortedVector< sp<SensorEventConnection> > activeConnections;
303 populateActiveConnections(&activeConnections);
304 {
305 Mutex::Autolock _l(mLock);
306 for (size_t i = 0 ; i < activeConnections.size(); i++) {
307 if (activeConnections[i] != nullptr && activeConnections[i]->getUid() == uid) {
308 activeConnections[i]->setSensorAccess(hasAccess);
309 }
310 }
311 }
312 }
313
registerSensor(SensorInterface * s,bool isDebug,bool isVirtual)314 const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
315 int handle = s->getSensor().getHandle();
316 int type = s->getSensor().getType();
317 if (mSensors.add(handle, s, isDebug, isVirtual)){
318 mRecentEvent.emplace(handle, new SensorServiceUtil::RecentEventLogger(type));
319 return s->getSensor();
320 } else {
321 return mSensors.getNonSensor();
322 }
323 }
324
registerDynamicSensorLocked(SensorInterface * s,bool isDebug)325 const Sensor& SensorService::registerDynamicSensorLocked(SensorInterface* s, bool isDebug) {
326 return registerSensor(s, isDebug);
327 }
328
unregisterDynamicSensorLocked(int handle)329 bool SensorService::unregisterDynamicSensorLocked(int handle) {
330 bool ret = mSensors.remove(handle);
331
332 const auto i = mRecentEvent.find(handle);
333 if (i != mRecentEvent.end()) {
334 delete i->second;
335 mRecentEvent.erase(i);
336 }
337 return ret;
338 }
339
registerVirtualSensor(SensorInterface * s,bool isDebug)340 const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
341 return registerSensor(s, isDebug, true);
342 }
343
~SensorService()344 SensorService::~SensorService() {
345 for (auto && entry : mRecentEvent) {
346 delete entry.second;
347 }
348 mUidPolicy->unregisterSelf();
349 mSensorPrivacyPolicy->unregisterSelf();
350 }
351
dump(int fd,const Vector<String16> & args)352 status_t SensorService::dump(int fd, const Vector<String16>& args) {
353 String8 result;
354 if (!PermissionCache::checkCallingPermission(sDumpPermission)) {
355 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
356 IPCThreadState::self()->getCallingPid(),
357 IPCThreadState::self()->getCallingUid());
358 } else {
359 bool privileged = IPCThreadState::self()->getCallingUid() == 0;
360 if (args.size() > 2) {
361 return INVALID_OPERATION;
362 }
363 Mutex::Autolock _l(mLock);
364 SensorDevice& dev(SensorDevice::getInstance());
365 if (args.size() == 2 && args[0] == String16("restrict")) {
366 // If already in restricted mode. Ignore.
367 if (mCurrentOperatingMode == RESTRICTED) {
368 return status_t(NO_ERROR);
369 }
370 // If in any mode other than normal, ignore.
371 if (mCurrentOperatingMode != NORMAL) {
372 return INVALID_OPERATION;
373 }
374
375 mCurrentOperatingMode = RESTRICTED;
376 // temporarily stop all sensor direct report and disable sensors
377 disableAllSensorsLocked();
378 mWhiteListedPackage.setTo(String8(args[1]));
379 return status_t(NO_ERROR);
380 } else if (args.size() == 1 && args[0] == String16("enable")) {
381 // If currently in restricted mode, reset back to NORMAL mode else ignore.
382 if (mCurrentOperatingMode == RESTRICTED) {
383 mCurrentOperatingMode = NORMAL;
384 // enable sensors and recover all sensor direct report
385 enableAllSensorsLocked();
386 }
387 if (mCurrentOperatingMode == DATA_INJECTION) {
388 resetToNormalModeLocked();
389 }
390 mWhiteListedPackage.clear();
391 return status_t(NO_ERROR);
392 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
393 if (mCurrentOperatingMode == NORMAL) {
394 dev.disableAllSensors();
395 status_t err = dev.setMode(DATA_INJECTION);
396 if (err == NO_ERROR) {
397 mCurrentOperatingMode = DATA_INJECTION;
398 } else {
399 // Re-enable sensors.
400 dev.enableAllSensors();
401 }
402 mWhiteListedPackage.setTo(String8(args[1]));
403 return NO_ERROR;
404 } else if (mCurrentOperatingMode == DATA_INJECTION) {
405 // Already in DATA_INJECTION mode. Treat this as a no_op.
406 return NO_ERROR;
407 } else {
408 // Transition to data injection mode supported only from NORMAL mode.
409 return INVALID_OPERATION;
410 }
411 } else if (!mSensors.hasAnySensor()) {
412 result.append("No Sensors on the device\n");
413 result.appendFormat("devInitCheck : %d\n", SensorDevice::getInstance().initCheck());
414 } else {
415 // Default dump the sensor list and debugging information.
416 //
417 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));
422 result.append("Sensor Device:\n");
423 result.append(SensorDevice::getInstance().dump().c_str());
424
425 result.append("Sensor List:\n");
426 result.append(mSensors.dump().c_str());
427
428 result.append("Fusion States:\n");
429 SensorFusion::getInstance().dump(result);
430
431 result.append("Recent Sensor events:\n");
432 for (auto&& i : mRecentEvent) {
433 sp<SensorInterface> s = mSensors.getInterface(i.first);
434 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 }
440 // 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 }
445
446 result.append("Active sensors:\n");
447 SensorDevice& dev = SensorDevice::getInstance();
448 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
449 int handle = mActiveSensors.keyAt(i);
450 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 }
456 }
457
458 result.appendFormat("Socket Buffer size = %zd events\n",
459 mSocketBufferSize/sizeof(sensors_event_t));
460 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
461 "not held");
462 result.appendFormat("Mode :");
463 switch(mCurrentOperatingMode) {
464 case NORMAL:
465 result.appendFormat(" NORMAL\n");
466 break;
467 case RESTRICTED:
468 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
469 break;
470 case DATA_INJECTION:
471 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
472 }
473 result.appendFormat("Sensor Privacy: %s\n",
474 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
475
476 result.appendFormat("%zd active connections\n", mActiveConnections.size());
477 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
478 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
479 if (connection != nullptr) {
480 result.appendFormat("Connection Number: %zu \n", i);
481 connection->dump(result);
482 }
483 }
484
485 result.appendFormat("%zd direct connections\n", mDirectConnections.size());
486 for (size_t i = 0 ; i < mDirectConnections.size() ; i++) {
487 sp<SensorDirectConnection> connection(mDirectConnections[i].promote());
488 if (connection != nullptr) {
489 result.appendFormat("Direct connection %zu:\n", i);
490 connection->dump(result);
491 }
492 }
493
494 result.appendFormat("Previous Registrations:\n");
495 // Log in the reverse chronological order.
496 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
497 SENSOR_REGISTRATIONS_BUF_SIZE;
498 const int startIndex = currentIndex;
499 do {
500 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
501 if (SensorRegistrationInfo::isSentinel(reg_info)) {
502 // Ignore sentinel, proceed to next item.
503 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
504 SENSOR_REGISTRATIONS_BUF_SIZE;
505 continue;
506 }
507 result.appendFormat("%s\n", reg_info.dump().c_str());
508 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
509 SENSOR_REGISTRATIONS_BUF_SIZE;
510 } while(startIndex != currentIndex);
511 }
512 }
513 write(fd, result.string(), result.size());
514 return NO_ERROR;
515 }
516
disableAllSensors()517 void SensorService::disableAllSensors() {
518 Mutex::Autolock _l(mLock);
519 disableAllSensorsLocked();
520 }
521
disableAllSensorsLocked()522 void SensorService::disableAllSensorsLocked() {
523 SensorDevice& dev(SensorDevice::getInstance());
524 for (auto &i : mDirectConnections) {
525 sp<SensorDirectConnection> connection(i.promote());
526 if (connection != nullptr) {
527 connection->stopAll(true /* backupRecord */);
528 }
529 }
530 dev.disableAllSensors();
531 // Clear all pending flush connections for all active sensors. If one of the active
532 // connections has called flush() and the underlying sensor has been disabled before a
533 // flush complete event is returned, we need to remove the connection from this queue.
534 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
535 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
536 }
537 }
538
enableAllSensors()539 void SensorService::enableAllSensors() {
540 Mutex::Autolock _l(mLock);
541 enableAllSensorsLocked();
542 }
543
enableAllSensorsLocked()544 void SensorService::enableAllSensorsLocked() {
545 // sensors should only be enabled if the operating state is not restricted and sensor
546 // privacy is not enabled.
547 if (mCurrentOperatingMode == RESTRICTED || mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
548 ALOGW("Sensors cannot be enabled: mCurrentOperatingMode = %d, sensor privacy = %s",
549 mCurrentOperatingMode,
550 mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
551 return;
552 }
553 SensorDevice& dev(SensorDevice::getInstance());
554 dev.enableAllSensors();
555 for (auto &i : mDirectConnections) {
556 sp<SensorDirectConnection> connection(i.promote());
557 if (connection != nullptr) {
558 connection->recoverAll();
559 }
560 }
561 }
562
563 // NOTE: This is a remote API - make sure all args are validated
shellCommand(int in,int out,int err,Vector<String16> & args)564 status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
565 if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
566 return PERMISSION_DENIED;
567 }
568 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
569 return BAD_VALUE;
570 }
571 if (args[0] == String16("set-uid-state")) {
572 return handleSetUidState(args, err);
573 } else if (args[0] == String16("reset-uid-state")) {
574 return handleResetUidState(args, err);
575 } else if (args[0] == String16("get-uid-state")) {
576 return handleGetUidState(args, out, err);
577 } else if (args.size() == 1 && args[0] == String16("help")) {
578 printHelp(out);
579 return NO_ERROR;
580 }
581 printHelp(err);
582 return BAD_VALUE;
583 }
584
getUidForPackage(String16 packageName,int userId,uid_t & uid,int err)585 static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
586 PermissionController pc;
587 uid = pc.getPackageUid(packageName, 0);
588 if (uid <= 0) {
589 ALOGE("Unknown package: '%s'", String8(packageName).string());
590 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
591 return BAD_VALUE;
592 }
593
594 if (userId < 0) {
595 ALOGE("Invalid user: %d", userId);
596 dprintf(err, "Invalid user: %d\n", userId);
597 return BAD_VALUE;
598 }
599
600 uid = multiuser_get_uid(userId, uid);
601 return NO_ERROR;
602 }
603
handleSetUidState(Vector<String16> & args,int err)604 status_t SensorService::handleSetUidState(Vector<String16>& args, int err) {
605 // Valid arg.size() is 3 or 5, args.size() is 5 with --user option.
606 if (!(args.size() == 3 || args.size() == 5)) {
607 printHelp(err);
608 return BAD_VALUE;
609 }
610
611 bool active = false;
612 if (args[2] == String16("active")) {
613 active = true;
614 } else if ((args[2] != String16("idle"))) {
615 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
616 return BAD_VALUE;
617 }
618
619 int userId = 0;
620 if (args.size() == 5 && args[3] == String16("--user")) {
621 userId = atoi(String8(args[4]));
622 }
623
624 uid_t uid;
625 if (getUidForPackage(args[1], userId, uid, err) != NO_ERROR) {
626 return BAD_VALUE;
627 }
628
629 mUidPolicy->addOverrideUid(uid, active);
630 return NO_ERROR;
631 }
632
handleResetUidState(Vector<String16> & args,int err)633 status_t SensorService::handleResetUidState(Vector<String16>& args, int err) {
634 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
635 if (!(args.size() == 2 || args.size() == 4)) {
636 printHelp(err);
637 return BAD_VALUE;
638 }
639
640 int userId = 0;
641 if (args.size() == 4 && args[2] == String16("--user")) {
642 userId = atoi(String8(args[3]));
643 }
644
645 uid_t uid;
646 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
647 return BAD_VALUE;
648 }
649
650 mUidPolicy->removeOverrideUid(uid);
651 return NO_ERROR;
652 }
653
handleGetUidState(Vector<String16> & args,int out,int err)654 status_t SensorService::handleGetUidState(Vector<String16>& args, int out, int err) {
655 // Valid arg.size() is 2 or 4, args.size() is 4 with --user option.
656 if (!(args.size() == 2 || args.size() == 4)) {
657 printHelp(err);
658 return BAD_VALUE;
659 }
660
661 int userId = 0;
662 if (args.size() == 4 && args[2] == String16("--user")) {
663 userId = atoi(String8(args[3]));
664 }
665
666 uid_t uid;
667 if (getUidForPackage(args[1], userId, uid, err) == BAD_VALUE) {
668 return BAD_VALUE;
669 }
670
671 if (mUidPolicy->isUidActive(uid)) {
672 return dprintf(out, "active\n");
673 } else {
674 return dprintf(out, "idle\n");
675 }
676 }
677
printHelp(int out)678 status_t SensorService::printHelp(int out) {
679 return dprintf(out, "Sensor service commands:\n"
680 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
681 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
682 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
683 " help print this message\n");
684 }
685
686 //TODO: move to SensorEventConnection later
cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection> & connection,sensors_event_t const * buffer,const int count)687 void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
688 sensors_event_t const* buffer, const int count) {
689 for (int i=0 ; i<count ; i++) {
690 int handle = buffer[i].sensor;
691 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
692 handle = buffer[i].meta_data.sensor;
693 }
694 if (connection->hasSensor(handle)) {
695 sp<SensorInterface> si = getSensorInterfaceFromHandle(handle);
696 // If this buffer has an event from a one_shot sensor and this connection is registered
697 // for this particular one_shot sensor, try cleaning up the connection.
698 if (si != nullptr &&
699 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
700 si->autoDisable(connection.get(), handle);
701 cleanupWithoutDisableLocked(connection, handle);
702 }
703
704 }
705 }
706 }
707
threadLoop()708 bool SensorService::threadLoop() {
709 ALOGD("nuSensorService thread starting...");
710
711 // each virtual sensor could generate an event per "real" event, that's why we need to size
712 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
713 // aggressive, but guaranteed to be enough.
714 const size_t vcount = mSensors.getVirtualSensors().size();
715 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
716 const size_t numEventMax = minBufferSize / (1 + vcount);
717
718 SensorDevice& device(SensorDevice::getInstance());
719
720 const int halVersion = device.getHalDeviceVersion();
721 do {
722 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
723 if (count < 0) {
724 if(count == DEAD_OBJECT && device.isReconnecting()) {
725 device.reconnect();
726 continue;
727 } else {
728 ALOGE("sensor poll failed (%s)", strerror(-count));
729 break;
730 }
731 }
732
733 // Reset sensors_event_t.flags to zero for all events in the buffer.
734 for (int i = 0; i < count; i++) {
735 mSensorEventBuffer[i].flags = 0;
736 }
737
738 // Make a copy of the connection vector as some connections may be removed during the course
739 // of this loop (especially when one-shot sensor events are present in the sensor_event
740 // buffer). Promote all connections to StrongPointers before the lock is acquired. If the
741 // destructor of the sp gets called when the lock is acquired, it may result in a deadlock
742 // as ~SensorEventConnection() needs to acquire mLock again for cleanup. So copy all the
743 // strongPointers to a vector before the lock is acquired.
744 SortedVector< sp<SensorEventConnection> > activeConnections;
745 populateActiveConnections(&activeConnections);
746
747 Mutex::Autolock _l(mLock);
748 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
749 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
750 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
751 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
752 // releasing the wakelock.
753 uint32_t wakeEvents = 0;
754 for (int i = 0; i < count; i++) {
755 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
756 wakeEvents++;
757 }
758 }
759
760 if (wakeEvents > 0) {
761 if (!mWakeLockAcquired) {
762 setWakeLockAcquiredLocked(true);
763 }
764 device.writeWakeLockHandled(wakeEvents);
765 }
766 recordLastValueLocked(mSensorEventBuffer, count);
767
768 // handle virtual sensors
769 if (count && vcount) {
770 sensors_event_t const * const event = mSensorEventBuffer;
771 if (!mActiveVirtualSensors.empty()) {
772 size_t k = 0;
773 SensorFusion& fusion(SensorFusion::getInstance());
774 if (fusion.isEnabled()) {
775 for (size_t i=0 ; i<size_t(count) ; i++) {
776 fusion.process(event[i]);
777 }
778 }
779 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
780 for (int handle : mActiveVirtualSensors) {
781 if (count + k >= minBufferSize) {
782 ALOGE("buffer too small to hold all events: "
783 "count=%zd, k=%zu, size=%zu",
784 count, k, minBufferSize);
785 break;
786 }
787 sensors_event_t out;
788 sp<SensorInterface> si = mSensors.getInterface(handle);
789 if (si == nullptr) {
790 ALOGE("handle %d is not an valid virtual sensor", handle);
791 continue;
792 }
793
794 if (si->process(&out, event[i])) {
795 mSensorEventBuffer[count + k] = out;
796 k++;
797 }
798 }
799 }
800 if (k) {
801 // record the last synthesized values
802 recordLastValueLocked(&mSensorEventBuffer[count], k);
803 count += k;
804 // sort the buffer by time-stamps
805 sortEventBuffer(mSensorEventBuffer, count);
806 }
807 }
808 }
809
810 // handle backward compatibility for RotationVector sensor
811 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
812 for (int i = 0; i < count; i++) {
813 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
814 // All the 4 components of the quaternion should be available
815 // No heading accuracy. Set it to -1
816 mSensorEventBuffer[i].data[4] = -1;
817 }
818 }
819 }
820
821 for (int i = 0; i < count; ++i) {
822 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
823 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
824 // SensorEventConnection mapped to the corresponding flush_complete_event in
825 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
826 mMapFlushEventsToConnections[i] = nullptr;
827 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
828 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
829 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
830 if (rec != nullptr) {
831 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
832 rec->removeFirstPendingFlushConnection();
833 }
834 }
835
836 // handle dynamic sensor meta events, process registration and unregistration of dynamic
837 // sensor based on content of event.
838 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
839 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
840 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
841 const sensor_t& dynamicSensor =
842 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
843 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
844 handle, dynamicSensor.type, dynamicSensor.name);
845
846 if (mSensors.isNewHandle(handle)) {
847 const auto& uuid = mSensorEventBuffer[i].dynamic_sensor_meta.uuid;
848 sensor_t s = dynamicSensor;
849 // make sure the dynamic sensor flag is set
850 s.flags |= DYNAMIC_SENSOR_MASK;
851 // force the handle to be consistent
852 s.handle = handle;
853
854 SensorInterface *si = new HardwareSensor(s, uuid);
855
856 // This will release hold on dynamic sensor meta, so it should be called
857 // after Sensor object is created.
858 device.handleDynamicSensorConnection(handle, true /*connected*/);
859 registerDynamicSensorLocked(si);
860 } else {
861 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
862 }
863 } else {
864 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
865 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
866
867 device.handleDynamicSensorConnection(handle, false /*connected*/);
868 if (!unregisterDynamicSensorLocked(handle)) {
869 ALOGE("Dynamic sensor release error.");
870 }
871
872 size_t numConnections = activeConnections.size();
873 for (size_t i=0 ; i < numConnections; ++i) {
874 if (activeConnections[i] != nullptr) {
875 activeConnections[i]->removeSensor(handle);
876 }
877 }
878 }
879 }
880 }
881
882 // Send our events to clients. Check the state of wake lock for each client and release the
883 // lock if none of the clients need it.
884 bool needsWakeLock = false;
885 size_t numConnections = activeConnections.size();
886 for (size_t i=0 ; i < numConnections; ++i) {
887 if (activeConnections[i] != nullptr) {
888 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
889 mMapFlushEventsToConnections);
890 needsWakeLock |= activeConnections[i]->needsWakeLock();
891 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
892 // Early check for one-shot sensors.
893 if (activeConnections[i]->hasOneShotSensors()) {
894 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
895 count);
896 }
897 }
898 }
899
900 if (mWakeLockAcquired && !needsWakeLock) {
901 setWakeLockAcquiredLocked(false);
902 }
903 } while (!Thread::exitPending());
904
905 ALOGW("Exiting SensorService::threadLoop => aborting...");
906 abort();
907 return false;
908 }
909
getLooper() const910 sp<Looper> SensorService::getLooper() const {
911 return mLooper;
912 }
913
resetAllWakeLockRefCounts()914 void SensorService::resetAllWakeLockRefCounts() {
915 SortedVector< sp<SensorEventConnection> > activeConnections;
916 populateActiveConnections(&activeConnections);
917 {
918 Mutex::Autolock _l(mLock);
919 for (size_t i=0 ; i < activeConnections.size(); ++i) {
920 if (activeConnections[i] != nullptr) {
921 activeConnections[i]->resetWakeLockRefCount();
922 }
923 }
924 setWakeLockAcquiredLocked(false);
925 }
926 }
927
setWakeLockAcquiredLocked(bool acquire)928 void SensorService::setWakeLockAcquiredLocked(bool acquire) {
929 if (acquire) {
930 if (!mWakeLockAcquired) {
931 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
932 mWakeLockAcquired = true;
933 }
934 mLooper->wake();
935 } else {
936 if (mWakeLockAcquired) {
937 release_wake_lock(WAKE_LOCK_NAME);
938 mWakeLockAcquired = false;
939 }
940 }
941 }
942
isWakeLockAcquired()943 bool SensorService::isWakeLockAcquired() {
944 Mutex::Autolock _l(mLock);
945 return mWakeLockAcquired;
946 }
947
threadLoop()948 bool SensorService::SensorEventAckReceiver::threadLoop() {
949 ALOGD("new thread SensorEventAckReceiver");
950 sp<Looper> looper = mService->getLooper();
951 do {
952 bool wakeLockAcquired = mService->isWakeLockAcquired();
953 int timeout = -1;
954 if (wakeLockAcquired) timeout = 5000;
955 int ret = looper->pollOnce(timeout);
956 if (ret == ALOOPER_POLL_TIMEOUT) {
957 mService->resetAllWakeLockRefCounts();
958 }
959 } while(!Thread::exitPending());
960 return false;
961 }
962
recordLastValueLocked(const sensors_event_t * buffer,size_t count)963 void SensorService::recordLastValueLocked(
964 const sensors_event_t* buffer, size_t count) {
965 for (size_t i = 0; i < count; i++) {
966 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
967 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
968 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO) {
969 continue;
970 }
971
972 auto logger = mRecentEvent.find(buffer[i].sensor);
973 if (logger != mRecentEvent.end()) {
974 logger->second->addEvent(buffer[i]);
975 }
976 }
977 }
978
sortEventBuffer(sensors_event_t * buffer,size_t count)979 void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
980 struct compar {
981 static int cmp(void const* lhs, void const* rhs) {
982 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
983 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
984 return l->timestamp - r->timestamp;
985 }
986 };
987 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
988 }
989
getSensorName(int handle) const990 String8 SensorService::getSensorName(int handle) const {
991 return mSensors.getName(handle);
992 }
993
isVirtualSensor(int handle) const994 bool SensorService::isVirtualSensor(int handle) const {
995 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
996 return sensor != nullptr && sensor->isVirtual();
997 }
998
isWakeUpSensorEvent(const sensors_event_t & event) const999 bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
1000 int handle = event.sensor;
1001 if (event.type == SENSOR_TYPE_META_DATA) {
1002 handle = event.meta_data.sensor;
1003 }
1004 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1005 return sensor != nullptr && sensor->getSensor().isWakeUpSensor();
1006 }
1007
getIdFromUuid(const Sensor::uuid_t & uuid) const1008 int32_t SensorService::getIdFromUuid(const Sensor::uuid_t &uuid) const {
1009 if ((uuid.i64[0] == 0) && (uuid.i64[1] == 0)) {
1010 // UUID is not supported for this device.
1011 return 0;
1012 }
1013 if ((uuid.i64[0] == INT64_C(~0)) && (uuid.i64[1] == INT64_C(~0))) {
1014 // This sensor can be uniquely identified in the system by
1015 // the combination of its type and name.
1016 return -1;
1017 }
1018
1019 // We have a dynamic sensor.
1020
1021 if (!sHmacGlobalKeyIsValid) {
1022 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1023 ALOGW("HMAC key failure; dynamic sensor getId() will be wrong.");
1024 return 0;
1025 }
1026
1027 // We want each app author/publisher to get a different ID, so that the
1028 // same dynamic sensor cannot be tracked across apps by multiple
1029 // authors/publishers. So we use both our UUID and our User ID.
1030 // Note potential confusion:
1031 // UUID => Universally Unique Identifier.
1032 // UID => User Identifier.
1033 // We refrain from using "uid" except as needed by API to try to
1034 // keep this distinction clear.
1035
1036 auto appUserId = IPCThreadState::self()->getCallingUid();
1037 uint8_t uuidAndApp[sizeof(uuid) + sizeof(appUserId)];
1038 memcpy(uuidAndApp, &uuid, sizeof(uuid));
1039 memcpy(uuidAndApp + sizeof(uuid), &appUserId, sizeof(appUserId));
1040
1041 // Now we use our key on our UUID/app combo to get the hash.
1042 uint8_t hash[EVP_MAX_MD_SIZE];
1043 unsigned int hashLen;
1044 if (HMAC(EVP_sha256(),
1045 sHmacGlobalKey, sizeof(sHmacGlobalKey),
1046 uuidAndApp, sizeof(uuidAndApp),
1047 hash, &hashLen) == nullptr) {
1048 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1049 ALOGW("HMAC failure; dynamic sensor getId() will be wrong.");
1050 return 0;
1051 }
1052
1053 int32_t id = 0;
1054 if (hashLen < sizeof(id)) {
1055 // We never expect this case, but out of paranoia, we handle it.
1056 // Our 'id' length is already quite small, we don't want the
1057 // effective length of it to be even smaller.
1058 // Rather than risk exposing UUIDs, we cripple dynamic sensors.
1059 ALOGW("HMAC insufficient; dynamic sensor getId() will be wrong.");
1060 return 0;
1061 }
1062
1063 // This is almost certainly less than all of 'hash', but it's as secure
1064 // as we can be with our current 'id' length.
1065 memcpy(&id, hash, sizeof(id));
1066
1067 // Note at the beginning of the function that we return the values of
1068 // 0 and -1 to represent special cases. As a result, we can't return
1069 // those as dynamic sensor IDs. If we happened to hash to one of those
1070 // values, we change 'id' so we report as a dynamic sensor, and not as
1071 // one of those special cases.
1072 if (id == -1) {
1073 id = -2;
1074 } else if (id == 0) {
1075 id = 1;
1076 }
1077 return id;
1078 }
1079
makeUuidsIntoIdsForSensorList(Vector<Sensor> & sensorList) const1080 void SensorService::makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const {
1081 for (auto &sensor : sensorList) {
1082 int32_t id = getIdFromUuid(sensor.getUuid());
1083 sensor.setId(id);
1084 }
1085 }
1086
getSensorList(const String16 &)1087 Vector<Sensor> SensorService::getSensorList(const String16& /* opPackageName */) {
1088 char value[PROPERTY_VALUE_MAX];
1089 property_get("debug.sensors", value, "0");
1090 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
1091 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
1092 Vector<Sensor> accessibleSensorList;
1093 for (size_t i = 0; i < initialSensorList.size(); i++) {
1094 Sensor sensor = initialSensorList[i];
1095 accessibleSensorList.add(sensor);
1096 }
1097 makeUuidsIntoIdsForSensorList(accessibleSensorList);
1098 return accessibleSensorList;
1099 }
1100
getDynamicSensorList(const String16 & opPackageName)1101 Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
1102 Vector<Sensor> accessibleSensorList;
1103 mSensors.forEachSensor(
1104 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
1105 if (sensor.isDynamicSensor()) {
1106 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
1107 accessibleSensorList.add(sensor);
1108 } else {
1109 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
1110 sensor.getName().string(),
1111 sensor.getRequiredPermission().string(),
1112 sensor.getRequiredAppOp());
1113 }
1114 }
1115 return true;
1116 });
1117 makeUuidsIntoIdsForSensorList(accessibleSensorList);
1118 return accessibleSensorList;
1119 }
1120
createSensorEventConnection(const String8 & packageName,int requestedMode,const String16 & opPackageName)1121 sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
1122 int requestedMode, const String16& opPackageName) {
1123 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
1124 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
1125 return nullptr;
1126 }
1127
1128 Mutex::Autolock _l(mLock);
1129 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
1130 // operating in DI mode.
1131 if (requestedMode == DATA_INJECTION) {
1132 if (mCurrentOperatingMode != DATA_INJECTION) return nullptr;
1133 if (!isWhiteListedPackage(packageName)) return nullptr;
1134 }
1135
1136 uid_t uid = IPCThreadState::self()->getCallingUid();
1137 pid_t pid = IPCThreadState::self()->getCallingPid();
1138
1139 String8 connPackageName =
1140 (packageName == "") ? String8::format("unknown_package_pid_%d", pid) : packageName;
1141 String16 connOpPackageName =
1142 (opPackageName == String16("")) ? String16(connPackageName) : opPackageName;
1143 bool hasSensorAccess = mUidPolicy->isUidActive(uid);
1144 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, connPackageName,
1145 requestedMode == DATA_INJECTION, connOpPackageName, hasSensorAccess));
1146 if (requestedMode == DATA_INJECTION) {
1147 if (mActiveConnections.indexOf(result) < 0) {
1148 mActiveConnections.add(result);
1149 }
1150 // Add the associated file descriptor to the Looper for polling whenever there is data to
1151 // be injected.
1152 result->updateLooperRegistration(mLooper);
1153 }
1154 return result;
1155 }
1156
isDataInjectionEnabled()1157 int SensorService::isDataInjectionEnabled() {
1158 Mutex::Autolock _l(mLock);
1159 return (mCurrentOperatingMode == DATA_INJECTION);
1160 }
1161
createSensorDirectConnection(const String16 & opPackageName,uint32_t size,int32_t type,int32_t format,const native_handle * resource)1162 sp<ISensorEventConnection> SensorService::createSensorDirectConnection(
1163 const String16& opPackageName, uint32_t size, int32_t type, int32_t format,
1164 const native_handle *resource) {
1165 Mutex::Autolock _l(mLock);
1166
1167 // No new direct connections are allowed when sensor privacy is enabled
1168 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1169 ALOGE("Cannot create new direct connections when sensor privacy is enabled");
1170 return nullptr;
1171 }
1172
1173 struct sensors_direct_mem_t mem = {
1174 .type = type,
1175 .format = format,
1176 .size = size,
1177 .handle = resource,
1178 };
1179 uid_t uid = IPCThreadState::self()->getCallingUid();
1180
1181 if (mem.handle == nullptr) {
1182 ALOGE("Failed to clone resource handle");
1183 return nullptr;
1184 }
1185
1186 // check format
1187 if (format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1188 ALOGE("Direct channel format %d is unsupported!", format);
1189 return nullptr;
1190 }
1191
1192 // check for duplication
1193 for (auto &i : mDirectConnections) {
1194 sp<SensorDirectConnection> connection(i.promote());
1195 if (connection != nullptr && connection->isEquivalent(&mem)) {
1196 ALOGE("Duplicate create channel request for the same share memory");
1197 return nullptr;
1198 }
1199 }
1200
1201 // check specific to memory type
1202 switch(type) {
1203 case SENSOR_DIRECT_MEM_TYPE_ASHMEM: { // channel backed by ashmem
1204 if (resource->numFds < 1) {
1205 ALOGE("Ashmem direct channel requires a memory region to be supplied");
1206 android_errorWriteLog(0x534e4554, "70986337"); // SafetyNet
1207 return nullptr;
1208 }
1209 int fd = resource->data[0];
1210 int size2 = ashmem_get_size_region(fd);
1211 // check size consistency
1212 if (size2 < static_cast<int64_t>(size)) {
1213 ALOGE("Ashmem direct channel size %" PRIu32 " greater than shared memory size %d",
1214 size, size2);
1215 return nullptr;
1216 }
1217 break;
1218 }
1219 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
1220 // no specific checks for gralloc
1221 break;
1222 default:
1223 ALOGE("Unknown direct connection memory type %d", type);
1224 return nullptr;
1225 }
1226
1227 native_handle_t *clone = native_handle_clone(resource);
1228 if (!clone) {
1229 return nullptr;
1230 }
1231
1232 SensorDirectConnection* conn = nullptr;
1233 SensorDevice& dev(SensorDevice::getInstance());
1234 int channelHandle = dev.registerDirectChannel(&mem);
1235
1236 if (channelHandle <= 0) {
1237 ALOGE("SensorDevice::registerDirectChannel returns %d", channelHandle);
1238 } else {
1239 mem.handle = clone;
1240 conn = new SensorDirectConnection(this, uid, &mem, channelHandle, opPackageName);
1241 }
1242
1243 if (conn == nullptr) {
1244 native_handle_close(clone);
1245 native_handle_delete(clone);
1246 } else {
1247 // add to list of direct connections
1248 // sensor service should never hold pointer or sp of SensorDirectConnection object.
1249 mDirectConnections.add(wp<SensorDirectConnection>(conn));
1250 }
1251 return conn;
1252 }
1253
setOperationParameter(int32_t handle,int32_t type,const Vector<float> & floats,const Vector<int32_t> & ints)1254 int SensorService::setOperationParameter(
1255 int32_t handle, int32_t type,
1256 const Vector<float> &floats, const Vector<int32_t> &ints) {
1257 Mutex::Autolock _l(mLock);
1258
1259 if (!checkCallingPermission(sLocationHardwarePermission, nullptr, nullptr)) {
1260 return PERMISSION_DENIED;
1261 }
1262
1263 bool isFloat = true;
1264 bool isCustom = false;
1265 size_t expectSize = INT32_MAX;
1266 switch (type) {
1267 case AINFO_LOCAL_GEOMAGNETIC_FIELD:
1268 isFloat = true;
1269 expectSize = 3;
1270 break;
1271 case AINFO_LOCAL_GRAVITY:
1272 isFloat = true;
1273 expectSize = 1;
1274 break;
1275 case AINFO_DOCK_STATE:
1276 case AINFO_HIGH_PERFORMANCE_MODE:
1277 case AINFO_MAGNETIC_FIELD_CALIBRATION:
1278 isFloat = false;
1279 expectSize = 1;
1280 break;
1281 default:
1282 // CUSTOM events must only contain float data; it may have variable size
1283 if (type < AINFO_CUSTOM_START || type >= AINFO_DEBUGGING_START ||
1284 ints.size() ||
1285 sizeof(additional_info_event_t::data_float)/sizeof(float) < floats.size() ||
1286 handle < 0) {
1287 return BAD_VALUE;
1288 }
1289 isFloat = true;
1290 isCustom = true;
1291 expectSize = floats.size();
1292 break;
1293 }
1294
1295 if (!isCustom && handle != -1) {
1296 return BAD_VALUE;
1297 }
1298
1299 // three events: first one is begin tag, last one is end tag, the one in the middle
1300 // is the payload.
1301 sensors_event_t event[3];
1302 int64_t timestamp = elapsedRealtimeNano();
1303 for (sensors_event_t* i = event; i < event + 3; i++) {
1304 *i = (sensors_event_t) {
1305 .version = sizeof(sensors_event_t),
1306 .sensor = handle,
1307 .type = SENSOR_TYPE_ADDITIONAL_INFO,
1308 .timestamp = timestamp++,
1309 .additional_info = (additional_info_event_t) {
1310 .serial = 0
1311 }
1312 };
1313 }
1314
1315 event[0].additional_info.type = AINFO_BEGIN;
1316 event[1].additional_info.type = type;
1317 event[2].additional_info.type = AINFO_END;
1318
1319 if (isFloat) {
1320 if (floats.size() != expectSize) {
1321 return BAD_VALUE;
1322 }
1323 for (size_t i = 0; i < expectSize; ++i) {
1324 event[1].additional_info.data_float[i] = floats[i];
1325 }
1326 } else {
1327 if (ints.size() != expectSize) {
1328 return BAD_VALUE;
1329 }
1330 for (size_t i = 0; i < expectSize; ++i) {
1331 event[1].additional_info.data_int32[i] = ints[i];
1332 }
1333 }
1334
1335 SensorDevice& dev(SensorDevice::getInstance());
1336 for (sensors_event_t* i = event; i < event + 3; i++) {
1337 int ret = dev.injectSensorData(i);
1338 if (ret != NO_ERROR) {
1339 return ret;
1340 }
1341 }
1342 return NO_ERROR;
1343 }
1344
resetToNormalMode()1345 status_t SensorService::resetToNormalMode() {
1346 Mutex::Autolock _l(mLock);
1347 return resetToNormalModeLocked();
1348 }
1349
resetToNormalModeLocked()1350 status_t SensorService::resetToNormalModeLocked() {
1351 SensorDevice& dev(SensorDevice::getInstance());
1352 status_t err = dev.setMode(NORMAL);
1353 if (err == NO_ERROR) {
1354 mCurrentOperatingMode = NORMAL;
1355 dev.enableAllSensors();
1356 }
1357 return err;
1358 }
1359
cleanupConnection(SensorEventConnection * c)1360 void SensorService::cleanupConnection(SensorEventConnection* c) {
1361 Mutex::Autolock _l(mLock);
1362 const wp<SensorEventConnection> connection(c);
1363 size_t size = mActiveSensors.size();
1364 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
1365 for (size_t i=0 ; i<size ; ) {
1366 int handle = mActiveSensors.keyAt(i);
1367 if (c->hasSensor(handle)) {
1368 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
1369 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1370 if (sensor != nullptr) {
1371 sensor->activate(c, false);
1372 } else {
1373 ALOGE("sensor interface of handle=0x%08x is null!", handle);
1374 }
1375 c->removeSensor(handle);
1376 }
1377 SensorRecord* rec = mActiveSensors.valueAt(i);
1378 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
1379 ALOGD_IF(DEBUG_CONNECTIONS,
1380 "removing connection %p for sensor[%zu].handle=0x%08x",
1381 c, i, handle);
1382
1383 if (rec && rec->removeConnection(connection)) {
1384 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
1385 mActiveSensors.removeItemsAt(i, 1);
1386 mActiveVirtualSensors.erase(handle);
1387 delete rec;
1388 size--;
1389 } else {
1390 i++;
1391 }
1392 }
1393 c->updateLooperRegistration(mLooper);
1394 mActiveConnections.remove(connection);
1395 BatteryService::cleanup(c->getUid());
1396 if (c->needsWakeLock()) {
1397 checkWakeLockStateLocked();
1398 }
1399
1400 {
1401 Mutex::Autolock packageLock(sPackageTargetVersionLock);
1402 auto iter = sPackageTargetVersion.find(c->mOpPackageName);
1403 if (iter != sPackageTargetVersion.end()) {
1404 sPackageTargetVersion.erase(iter);
1405 }
1406 }
1407
1408 SensorDevice& dev(SensorDevice::getInstance());
1409 dev.notifyConnectionDestroyed(c);
1410 }
1411
cleanupConnection(SensorDirectConnection * c)1412 void SensorService::cleanupConnection(SensorDirectConnection* c) {
1413 Mutex::Autolock _l(mLock);
1414
1415 SensorDevice& dev(SensorDevice::getInstance());
1416 dev.unregisterDirectChannel(c->getHalChannelHandle());
1417 mDirectConnections.remove(c);
1418 }
1419
getSensorInterfaceFromHandle(int handle) const1420 sp<SensorInterface> SensorService::getSensorInterfaceFromHandle(int handle) const {
1421 return mSensors.getInterface(handle);
1422 }
1423
enable(const sp<SensorEventConnection> & connection,int handle,nsecs_t samplingPeriodNs,nsecs_t maxBatchReportLatencyNs,int reservedFlags,const String16 & opPackageName)1424 status_t SensorService::enable(const sp<SensorEventConnection>& connection,
1425 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
1426 const String16& opPackageName) {
1427 if (mInitCheck != NO_ERROR)
1428 return mInitCheck;
1429
1430 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1431 if (sensor == nullptr ||
1432 !canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
1433 return BAD_VALUE;
1434 }
1435
1436 Mutex::Autolock _l(mLock);
1437 if (mCurrentOperatingMode != NORMAL
1438 && !isWhiteListedPackage(connection->getPackageName())) {
1439 return INVALID_OPERATION;
1440 }
1441
1442 SensorRecord* rec = mActiveSensors.valueFor(handle);
1443 if (rec == nullptr) {
1444 rec = new SensorRecord(connection);
1445 mActiveSensors.add(handle, rec);
1446 if (sensor->isVirtual()) {
1447 mActiveVirtualSensors.emplace(handle);
1448 }
1449
1450 // There was no SensorRecord for this sensor which means it was previously disabled. Mark
1451 // the recent event as stale to ensure that the previous event is not sent to a client. This
1452 // ensures on-change events that were generated during a previous sensor activation are not
1453 // erroneously sent to newly connected clients, especially if a second client registers for
1454 // an on-change sensor before the first client receives the updated event. Once an updated
1455 // event is received, the recent events will be marked as current, and any new clients will
1456 // immediately receive the most recent event.
1457 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
1458 auto logger = mRecentEvent.find(handle);
1459 if (logger != mRecentEvent.end()) {
1460 logger->second->setLastEventStale();
1461 }
1462 }
1463 } else {
1464 if (rec->addConnection(connection)) {
1465 // this sensor is already activated, but we are adding a connection that uses it.
1466 // Immediately send down the last known value of the requested sensor if it's not a
1467 // "continuous" sensor.
1468 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
1469 // NOTE: The wake_up flag of this event may get set to
1470 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
1471
1472 auto logger = mRecentEvent.find(handle);
1473 if (logger != mRecentEvent.end()) {
1474 sensors_event_t event;
1475 // Verify that the last sensor event was generated from the current activation
1476 // of the sensor. If not, it is possible for an on-change sensor to receive a
1477 // sensor event that is stale if two clients re-activate the sensor
1478 // simultaneously.
1479 if(logger->second->populateLastEventIfCurrent(&event)) {
1480 event.sensor = handle;
1481 if (event.version == sizeof(sensors_event_t)) {
1482 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1483 setWakeLockAcquiredLocked(true);
1484 }
1485 connection->sendEvents(&event, 1, nullptr);
1486 if (!connection->needsWakeLock() && mWakeLockAcquired) {
1487 checkWakeLockStateLocked();
1488 }
1489 }
1490 }
1491 }
1492 }
1493 }
1494 }
1495
1496 if (connection->addSensor(handle)) {
1497 BatteryService::enableSensor(connection->getUid(), handle);
1498 // the sensor was added (which means it wasn't already there)
1499 // so, see if this connection becomes active
1500 if (mActiveConnections.indexOf(connection) < 0) {
1501 mActiveConnections.add(connection);
1502 }
1503 } else {
1504 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1505 handle, connection.get());
1506 }
1507
1508 // Check maximum delay for the sensor.
1509 nsecs_t maxDelayNs = sensor->getSensor().getMaxDelay() * 1000LL;
1510 if (maxDelayNs > 0 && (samplingPeriodNs > maxDelayNs)) {
1511 samplingPeriodNs = maxDelayNs;
1512 }
1513
1514 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1515 if (samplingPeriodNs < minDelayNs) {
1516 samplingPeriodNs = minDelayNs;
1517 }
1518
1519 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1520 "rate=%" PRId64 " timeout== %" PRId64"",
1521 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1522
1523 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
1524 maxBatchReportLatencyNs);
1525
1526 // Call flush() before calling activate() on the sensor. Wait for a first
1527 // flush complete event before sending events on this connection. Ignore
1528 // one-shot sensors which don't support flush(). Ignore on-change sensors
1529 // to maintain the on-change logic (any on-change events except the initial
1530 // one should be trigger by a change in value). Also if this sensor isn't
1531 // already active, don't call flush().
1532 if (err == NO_ERROR &&
1533 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
1534 rec->getNumConnections() > 1) {
1535 connection->setFirstFlushPending(handle, true);
1536 status_t err_flush = sensor->flush(connection.get(), handle);
1537 // Flush may return error if the underlying h/w sensor uses an older HAL.
1538 if (err_flush == NO_ERROR) {
1539 rec->addPendingFlushConnection(connection.get());
1540 } else {
1541 connection->setFirstFlushPending(handle, false);
1542 }
1543 }
1544
1545 if (err == NO_ERROR) {
1546 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1547 err = sensor->activate(connection.get(), true);
1548 }
1549
1550 if (err == NO_ERROR) {
1551 connection->updateLooperRegistration(mLooper);
1552
1553 if (sensor->getSensor().getRequiredPermission().size() > 0 &&
1554 sensor->getSensor().getRequiredAppOp() >= 0) {
1555 connection->mHandleToAppOp[handle] = sensor->getSensor().getRequiredAppOp();
1556 }
1557
1558 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1559 SensorRegistrationInfo(handle, connection->getPackageName(),
1560 samplingPeriodNs, maxBatchReportLatencyNs, true);
1561 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
1562 }
1563
1564 if (err != NO_ERROR) {
1565 // batch/activate has failed, reset our state.
1566 cleanupWithoutDisableLocked(connection, handle);
1567 }
1568 return err;
1569 }
1570
disable(const sp<SensorEventConnection> & connection,int handle)1571 status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
1572 if (mInitCheck != NO_ERROR)
1573 return mInitCheck;
1574
1575 Mutex::Autolock _l(mLock);
1576 status_t err = cleanupWithoutDisableLocked(connection, handle);
1577 if (err == NO_ERROR) {
1578 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1579 err = sensor != nullptr ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
1580
1581 }
1582 if (err == NO_ERROR) {
1583 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex) =
1584 SensorRegistrationInfo(handle, connection->getPackageName(), 0, 0, false);
1585 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
1586 }
1587 return err;
1588 }
1589
cleanupWithoutDisable(const sp<SensorEventConnection> & connection,int handle)1590 status_t SensorService::cleanupWithoutDisable(
1591 const sp<SensorEventConnection>& connection, int handle) {
1592 Mutex::Autolock _l(mLock);
1593 return cleanupWithoutDisableLocked(connection, handle);
1594 }
1595
cleanupWithoutDisableLocked(const sp<SensorEventConnection> & connection,int handle)1596 status_t SensorService::cleanupWithoutDisableLocked(
1597 const sp<SensorEventConnection>& connection, int handle) {
1598 SensorRecord* rec = mActiveSensors.valueFor(handle);
1599 if (rec) {
1600 // see if this connection becomes inactive
1601 if (connection->removeSensor(handle)) {
1602 BatteryService::disableSensor(connection->getUid(), handle);
1603 }
1604 if (connection->hasAnySensor() == false) {
1605 connection->updateLooperRegistration(mLooper);
1606 mActiveConnections.remove(connection);
1607 }
1608 // see if this sensor becomes inactive
1609 if (rec->removeConnection(connection)) {
1610 mActiveSensors.removeItem(handle);
1611 mActiveVirtualSensors.erase(handle);
1612 delete rec;
1613 }
1614 return NO_ERROR;
1615 }
1616 return BAD_VALUE;
1617 }
1618
setEventRate(const sp<SensorEventConnection> & connection,int handle,nsecs_t ns,const String16 & opPackageName)1619 status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
1620 int handle, nsecs_t ns, const String16& opPackageName) {
1621 if (mInitCheck != NO_ERROR)
1622 return mInitCheck;
1623
1624 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1625 if (sensor == nullptr ||
1626 !canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
1627 return BAD_VALUE;
1628 }
1629
1630 if (ns < 0)
1631 return BAD_VALUE;
1632
1633 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1634 if (ns < minDelayNs) {
1635 ns = minDelayNs;
1636 }
1637
1638 return sensor->setDelay(connection.get(), handle, ns);
1639 }
1640
flushSensor(const sp<SensorEventConnection> & connection,const String16 & opPackageName)1641 status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1642 const String16& opPackageName) {
1643 if (mInitCheck != NO_ERROR) return mInitCheck;
1644 SensorDevice& dev(SensorDevice::getInstance());
1645 const int halVersion = dev.getHalDeviceVersion();
1646 status_t err(NO_ERROR);
1647 Mutex::Autolock _l(mLock);
1648 // Loop through all sensors for this connection and call flush on each of them.
1649 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1650 const int handle = connection->mSensorInfo.keyAt(i);
1651 sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
1652 if (sensor == nullptr) {
1653 continue;
1654 }
1655 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1656 ALOGE("flush called on a one-shot sensor");
1657 err = INVALID_OPERATION;
1658 continue;
1659 }
1660 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
1661 // For older devices just increment pending flush count which will send a trivial
1662 // flush complete event.
1663 connection->incrementPendingFlushCount(handle);
1664 } else {
1665 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1666 err = INVALID_OPERATION;
1667 continue;
1668 }
1669 status_t err_flush = sensor->flush(connection.get(), handle);
1670 if (err_flush == NO_ERROR) {
1671 SensorRecord* rec = mActiveSensors.valueFor(handle);
1672 if (rec != nullptr) rec->addPendingFlushConnection(connection);
1673 }
1674 err = (err_flush != NO_ERROR) ? err_flush : err;
1675 }
1676 }
1677 return err;
1678 }
1679
canAccessSensor(const Sensor & sensor,const char * operation,const String16 & opPackageName)1680 bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1681 const String16& opPackageName) {
1682 // Check if a permission is required for this sensor
1683 if (sensor.getRequiredPermission().length() <= 0) {
1684 return true;
1685 }
1686
1687 const int32_t opCode = sensor.getRequiredAppOp();
1688 const int32_t appOpMode = sAppOpsManager.checkOp(opCode,
1689 IPCThreadState::self()->getCallingUid(), opPackageName);
1690 bool appOpAllowed = appOpMode == AppOpsManager::MODE_ALLOWED;
1691
1692 bool canAccess = false;
1693 if (hasPermissionForSensor(sensor)) {
1694 // Ensure that the AppOp is allowed, or that there is no necessary app op for the sensor
1695 if (opCode < 0 || appOpAllowed) {
1696 canAccess = true;
1697 }
1698 } else if (sensor.getType() == SENSOR_TYPE_STEP_COUNTER ||
1699 sensor.getType() == SENSOR_TYPE_STEP_DETECTOR) {
1700 int targetSdkVersion = getTargetSdkVersion(opPackageName);
1701 // Allow access to the sensor if the application targets pre-Q, which is before the
1702 // requirement to hold the AR permission to access Step Counter and Step Detector events
1703 // was introduced, and the user hasn't revoked the app op.
1704 //
1705 // Verifying the app op is required to ensure that the user hasn't revoked the necessary
1706 // permissions to access the Step Detector and Step Counter when the application targets
1707 // pre-Q. Without this check, if the user revokes the pre-Q install-time GMS Core AR
1708 // permission, the app would still be able to receive Step Counter and Step Detector events.
1709 if (appOpAllowed &&
1710 targetSdkVersion > 0 &&
1711 targetSdkVersion <= __ANDROID_API_P__) {
1712 canAccess = true;
1713 }
1714 }
1715
1716 if (canAccess) {
1717 sAppOpsManager.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName);
1718 } else {
1719 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1720 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
1721 }
1722
1723 return canAccess;
1724 }
1725
hasPermissionForSensor(const Sensor & sensor)1726 bool SensorService::hasPermissionForSensor(const Sensor& sensor) {
1727 bool hasPermission = false;
1728 const String8& requiredPermission = sensor.getRequiredPermission();
1729
1730 // Runtime permissions can't use the cache as they may change.
1731 if (sensor.isRequiredPermissionRuntime()) {
1732 hasPermission = checkPermission(String16(requiredPermission),
1733 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
1734 } else {
1735 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1736 }
1737 return hasPermission;
1738 }
1739
getTargetSdkVersion(const String16 & opPackageName)1740 int SensorService::getTargetSdkVersion(const String16& opPackageName) {
1741 Mutex::Autolock packageLock(sPackageTargetVersionLock);
1742 int targetSdkVersion = -1;
1743 auto entry = sPackageTargetVersion.find(opPackageName);
1744 if (entry != sPackageTargetVersion.end()) {
1745 targetSdkVersion = entry->second;
1746 } else {
1747 sp<IBinder> binder = defaultServiceManager()->getService(String16("package_native"));
1748 if (binder != nullptr) {
1749 sp<content::pm::IPackageManagerNative> packageManager =
1750 interface_cast<content::pm::IPackageManagerNative>(binder);
1751 if (packageManager != nullptr) {
1752 binder::Status status = packageManager->getTargetSdkVersionForPackage(
1753 opPackageName, &targetSdkVersion);
1754 if (!status.isOk()) {
1755 targetSdkVersion = -1;
1756 }
1757 }
1758 }
1759 sPackageTargetVersion[opPackageName] = targetSdkVersion;
1760 }
1761 return targetSdkVersion;
1762 }
1763
checkWakeLockState()1764 void SensorService::checkWakeLockState() {
1765 Mutex::Autolock _l(mLock);
1766 checkWakeLockStateLocked();
1767 }
1768
checkWakeLockStateLocked()1769 void SensorService::checkWakeLockStateLocked() {
1770 if (!mWakeLockAcquired) {
1771 return;
1772 }
1773 bool releaseLock = true;
1774 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1775 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1776 if (connection != nullptr) {
1777 if (connection->needsWakeLock()) {
1778 releaseLock = false;
1779 break;
1780 }
1781 }
1782 }
1783 if (releaseLock) {
1784 setWakeLockAcquiredLocked(false);
1785 }
1786 }
1787
sendEventsFromCache(const sp<SensorEventConnection> & connection)1788 void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1789 Mutex::Autolock _l(mLock);
1790 connection->writeToSocketFromCache();
1791 if (connection->needsWakeLock()) {
1792 setWakeLockAcquiredLocked(true);
1793 }
1794 }
1795
populateActiveConnections(SortedVector<sp<SensorEventConnection>> * activeConnections)1796 void SensorService::populateActiveConnections(
1797 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1798 Mutex::Autolock _l(mLock);
1799 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1800 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1801 if (connection != nullptr) {
1802 activeConnections->add(connection);
1803 }
1804 }
1805 }
1806
isWhiteListedPackage(const String8 & packageName)1807 bool SensorService::isWhiteListedPackage(const String8& packageName) {
1808 return (packageName.contains(mWhiteListedPackage.string()));
1809 }
1810
isOperationPermitted(const String16 & opPackageName)1811 bool SensorService::isOperationPermitted(const String16& opPackageName) {
1812 Mutex::Autolock _l(mLock);
1813 if (mCurrentOperatingMode == RESTRICTED) {
1814 String8 package(opPackageName);
1815 return isWhiteListedPackage(package);
1816 }
1817 return true;
1818 }
1819
registerSelf()1820 void SensorService::UidPolicy::registerSelf() {
1821 ActivityManager am;
1822 am.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
1823 | ActivityManager::UID_OBSERVER_IDLE
1824 | ActivityManager::UID_OBSERVER_ACTIVE,
1825 ActivityManager::PROCESS_STATE_UNKNOWN,
1826 String16("android"));
1827 }
1828
unregisterSelf()1829 void SensorService::UidPolicy::unregisterSelf() {
1830 ActivityManager am;
1831 am.unregisterUidObserver(this);
1832 }
1833
onUidGone(__unused uid_t uid,__unused bool disabled)1834 void SensorService::UidPolicy::onUidGone(__unused uid_t uid, __unused bool disabled) {
1835 onUidIdle(uid, disabled);
1836 }
1837
onUidActive(uid_t uid)1838 void SensorService::UidPolicy::onUidActive(uid_t uid) {
1839 {
1840 Mutex::Autolock _l(mUidLock);
1841 mActiveUids.insert(uid);
1842 }
1843 sp<SensorService> service = mService.promote();
1844 if (service != nullptr) {
1845 service->setSensorAccess(uid, true);
1846 }
1847 }
1848
onUidIdle(uid_t uid,__unused bool disabled)1849 void SensorService::UidPolicy::onUidIdle(uid_t uid, __unused bool disabled) {
1850 bool deleted = false;
1851 {
1852 Mutex::Autolock _l(mUidLock);
1853 if (mActiveUids.erase(uid) > 0) {
1854 deleted = true;
1855 }
1856 }
1857 if (deleted) {
1858 sp<SensorService> service = mService.promote();
1859 if (service != nullptr) {
1860 service->setSensorAccess(uid, false);
1861 }
1862 }
1863 }
1864
addOverrideUid(uid_t uid,bool active)1865 void SensorService::UidPolicy::addOverrideUid(uid_t uid, bool active) {
1866 updateOverrideUid(uid, active, true);
1867 }
1868
removeOverrideUid(uid_t uid)1869 void SensorService::UidPolicy::removeOverrideUid(uid_t uid) {
1870 updateOverrideUid(uid, false, false);
1871 }
1872
updateOverrideUid(uid_t uid,bool active,bool insert)1873 void SensorService::UidPolicy::updateOverrideUid(uid_t uid, bool active, bool insert) {
1874 bool wasActive = false;
1875 bool isActive = false;
1876 {
1877 Mutex::Autolock _l(mUidLock);
1878 wasActive = isUidActiveLocked(uid);
1879 mOverrideUids.erase(uid);
1880 if (insert) {
1881 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
1882 }
1883 isActive = isUidActiveLocked(uid);
1884 }
1885 if (wasActive != isActive) {
1886 sp<SensorService> service = mService.promote();
1887 if (service != nullptr) {
1888 service->setSensorAccess(uid, isActive);
1889 }
1890 }
1891 }
1892
isUidActive(uid_t uid)1893 bool SensorService::UidPolicy::isUidActive(uid_t uid) {
1894 // Non-app UIDs are considered always active
1895 if (uid < FIRST_APPLICATION_UID) {
1896 return true;
1897 }
1898 Mutex::Autolock _l(mUidLock);
1899 return isUidActiveLocked(uid);
1900 }
1901
isUidActiveLocked(uid_t uid)1902 bool SensorService::UidPolicy::isUidActiveLocked(uid_t uid) {
1903 // Non-app UIDs are considered always active
1904 if (uid < FIRST_APPLICATION_UID) {
1905 return true;
1906 }
1907 auto it = mOverrideUids.find(uid);
1908 if (it != mOverrideUids.end()) {
1909 return it->second;
1910 }
1911 return mActiveUids.find(uid) != mActiveUids.end();
1912 }
1913
registerSelf()1914 void SensorService::SensorPrivacyPolicy::registerSelf() {
1915 SensorPrivacyManager spm;
1916 mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
1917 spm.addSensorPrivacyListener(this);
1918 }
1919
unregisterSelf()1920 void SensorService::SensorPrivacyPolicy::unregisterSelf() {
1921 SensorPrivacyManager spm;
1922 spm.removeSensorPrivacyListener(this);
1923 }
1924
isSensorPrivacyEnabled()1925 bool SensorService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
1926 return mSensorPrivacyEnabled;
1927 }
1928
onSensorPrivacyChanged(bool enabled)1929 binder::Status SensorService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
1930 mSensorPrivacyEnabled = enabled;
1931 sp<SensorService> service = mService.promote();
1932 if (service != nullptr) {
1933 if (enabled) {
1934 service->disableAllSensors();
1935 } else {
1936 service->enableAllSensors();
1937 }
1938 }
1939 return binder::Status::ok();
1940 }
1941 }; // namespace android
1942