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