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