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