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 17 #ifndef ANDROID_SENSOR_SERVICE_H 18 #define ANDROID_SENSOR_SERVICE_H 19 20 #include "SensorList.h" 21 #include "RecentEventLogger.h" 22 23 #include <android-base/macros.h> 24 #include <binder/AppOpsManager.h> 25 #include <binder/BinderService.h> 26 #include <binder/IUidObserver.h> 27 #include <cutils/compiler.h> 28 #include <cutils/multiuser.h> 29 #include <sensor/ISensorServer.h> 30 #include <sensor/ISensorEventConnection.h> 31 #include <sensor/Sensor.h> 32 #include "android/hardware/BnSensorPrivacyListener.h" 33 34 #include <utils/AndroidThreads.h> 35 #include <utils/KeyedVector.h> 36 #include <utils/Looper.h> 37 #include <utils/SortedVector.h> 38 #include <utils/String8.h> 39 #include <utils/Vector.h> 40 #include <utils/threads.h> 41 42 #include <stdint.h> 43 #include <sys/types.h> 44 #include <unordered_map> 45 #include <unordered_set> 46 #include <vector> 47 48 #if __clang__ 49 // Clang warns about SensorEventConnection::dump hiding BBinder::dump. The cause isn't fixable 50 // without changing the API, so let's tell clang this is indeed intentional. 51 #pragma clang diagnostic ignored "-Woverloaded-virtual" 52 #endif 53 54 // --------------------------------------------------------------------------- 55 #define IGNORE_HARDWARE_FUSION false 56 #define DEBUG_CONNECTIONS false 57 // Max size is 100 KB which is enough to accept a batch of about 1000 events. 58 #define MAX_SOCKET_BUFFER_SIZE_BATCHED (100 * 1024) 59 // For older HALs which don't support batching, use a smaller socket buffer size. 60 #define SOCKET_BUFFER_SIZE_NON_BATCHED (4 * 1024) 61 62 #define SENSOR_REGISTRATIONS_BUF_SIZE 200 63 64 // Apps that targets S+ and do not have HIGH_SAMPLING_RATE_SENSORS permission will be capped 65 // at 200 Hz. The cap also applies to all requests when the mic toggle is flipped to on, regardless 66 // of their target SDKs and permission. 67 // Capped sampling periods for apps that have non-direct sensor connections. 68 #define SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS (5 * 1000 * 1000) 69 // Capped sampling rate level for apps that have direct sensor connections. 70 // The enum SENSOR_DIRECT_RATE_NORMAL corresponds to a rate value of at most 110 Hz. 71 #define SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL SENSOR_DIRECT_RATE_NORMAL 72 73 namespace android { 74 // --------------------------------------------------------------------------- 75 class SensorInterface; 76 77 class SensorService : 78 public BinderService<SensorService>, 79 public BnSensorServer, 80 protected Thread 81 { 82 // nested class/struct for internal use 83 class SensorEventConnection; 84 class SensorDirectConnection; 85 86 public: 87 enum UidState { 88 UID_STATE_ACTIVE = 0, 89 UID_STATE_IDLE, 90 }; 91 92 class ProximityActiveListener : public virtual RefBase { 93 public: 94 // Note that the callback is invoked from an async thread and can interact with the 95 // SensorService directly. 96 virtual void onProximityActive(bool isActive) = 0; 97 }; 98 getServiceName()99 static char const* getServiceName() ANDROID_API { return "sensorservice"; } 100 SensorService() ANDROID_API; 101 102 void cleanupConnection(SensorEventConnection* connection); 103 void cleanupConnection(SensorDirectConnection* c); 104 105 // Call with mLock held. 106 void onProximityActiveLocked(bool isActive); 107 void notifyProximityStateLocked(const std::vector<sp<ProximityActiveListener>>& listeners); 108 109 status_t enable(const sp<SensorEventConnection>& connection, int handle, 110 nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags, 111 const String16& opPackageName); 112 113 status_t disable(const sp<SensorEventConnection>& connection, int handle); 114 115 status_t setEventRate(const sp<SensorEventConnection>& connection, int handle, nsecs_t ns, 116 const String16& opPackageName); 117 118 status_t flushSensor(const sp<SensorEventConnection>& connection, 119 const String16& opPackageName); 120 121 status_t addProximityActiveListener(const sp<ProximityActiveListener>& callback) ANDROID_API; 122 status_t removeProximityActiveListener(const sp<ProximityActiveListener>& callback) ANDROID_API; 123 124 // Returns true if a sensor should be throttled according to our rate-throttling rules. 125 static bool isSensorInCappedSet(int sensorType); 126 127 virtual status_t shellCommand(int in, int out, int err, Vector<String16>& args); 128 129 private: 130 friend class BinderService<SensorService>; 131 132 // nested class/struct for internal use 133 class ConnectionSafeAutolock; 134 class SensorConnectionHolder; 135 class SensorEventAckReceiver; 136 class SensorRecord; 137 class SensorRegistrationInfo; 138 139 // Promoting a SensorEventConnection or SensorDirectConnection from wp to sp must be done with 140 // mLock held, but destroying that sp must be done unlocked to avoid a race condition that 141 // causes a deadlock (remote dies while we hold a local sp, then our decStrong() call invokes 142 // the dtor -> cleanupConnection() tries to re-lock the mutex). This class ensures safe usage 143 // by wrapping a Mutex::Autolock on SensorService's mLock, plus vectors that hold promoted sp<> 144 // references until the lock is released, when they are safely destroyed. 145 // All read accesses to the connection lists in mConnectionHolder must be done via this class. 146 class ConnectionSafeAutolock final { 147 public: 148 // Returns a list of non-null promoted connection references 149 const std::vector<sp<SensorEventConnection>>& getActiveConnections(); 150 const std::vector<sp<SensorDirectConnection>>& getDirectConnections(); 151 152 private: 153 // Constructed via SensorConnectionHolder::lock() 154 friend class SensorConnectionHolder; 155 explicit ConnectionSafeAutolock(SensorConnectionHolder& holder, Mutex& mutex); 156 DISALLOW_IMPLICIT_CONSTRUCTORS(ConnectionSafeAutolock); 157 158 // NOTE: Order of these members is important, as the destructor for non-static members 159 // get invoked in the reverse order of their declaration. Here we are relying on the 160 // Autolock to be destroyed *before* the vectors, so the sp<> objects are destroyed without 161 // the lock held, which avoids the deadlock. 162 SensorConnectionHolder& mConnectionHolder; 163 std::vector<std::vector<sp<SensorEventConnection>>> mReferencedActiveConnections; 164 std::vector<std::vector<sp<SensorDirectConnection>>> mReferencedDirectConnections; 165 Mutex::Autolock mAutolock; 166 167 template<typename ConnectionType> 168 const std::vector<sp<ConnectionType>>& getConnectionsHelper( 169 const SortedVector<wp<ConnectionType>>& connectionList, 170 std::vector<std::vector<sp<ConnectionType>>>* referenceHolder); 171 }; 172 173 // Encapsulates the collection of active SensorEventConection and SensorDirectConnection 174 // references. Write access is done through this class with mLock held, but all read access 175 // must be routed through ConnectionSafeAutolock. 176 class SensorConnectionHolder { 177 public: 178 void addEventConnectionIfNotPresent(const sp<SensorEventConnection>& connection); 179 void removeEventConnection(const wp<SensorEventConnection>& connection); 180 181 void addDirectConnection(const sp<SensorDirectConnection>& connection); 182 void removeDirectConnection(const wp<SensorDirectConnection>& connection); 183 184 // Pass in the mutex that protects this connection holder; acquires the lock and returns an 185 // object that can be used to safely read the lists of connections 186 ConnectionSafeAutolock lock(Mutex& mutex); 187 188 private: 189 friend class ConnectionSafeAutolock; 190 SortedVector< wp<SensorEventConnection> > mActiveConnections; 191 SortedVector< wp<SensorDirectConnection> > mDirectConnections; 192 }; 193 194 // If accessing a sensor we need to make sure the UID has access to it. If 195 // the app UID is idle then it cannot access sensors and gets no trigger 196 // events, no on-change events, flush event behavior does not change, and 197 // recurring events are the same as the first one delivered in idle state 198 // emulating no sensor change. As soon as the app UID transitions to an 199 // active state we will start reporting events as usual and vise versa. This 200 // approach transparently handles observing sensors while the app UID transitions 201 // between idle/active state avoiding to get stuck in a state receiving sensor 202 // data while idle or not receiving sensor data while active. 203 class UidPolicy : public BnUidObserver { 204 public: UidPolicy(wp<SensorService> service)205 explicit UidPolicy(wp<SensorService> service) 206 : mService(service) {} 207 void registerSelf(); 208 void unregisterSelf(); 209 210 bool isUidActive(uid_t uid); 211 212 void onUidGone(uid_t uid, bool disabled); 213 void onUidActive(uid_t uid); 214 void onUidIdle(uid_t uid, bool disabled); onUidStateChanged(uid_t uid __unused,int32_t procState __unused,int64_t procStateSeq __unused,int32_t capability __unused)215 void onUidStateChanged(uid_t uid __unused, int32_t procState __unused, 216 int64_t procStateSeq __unused, int32_t capability __unused) {} 217 218 void addOverrideUid(uid_t uid, bool active); 219 void removeOverrideUid(uid_t uid); 220 private: 221 bool isUidActiveLocked(uid_t uid); 222 void updateOverrideUid(uid_t uid, bool active, bool insert); 223 224 Mutex mUidLock; 225 wp<SensorService> mService; 226 std::unordered_set<uid_t> mActiveUids; 227 std::unordered_map<uid_t, bool> mOverrideUids; 228 }; 229 230 bool isUidActive(uid_t uid); 231 232 // Sensor privacy allows a user to disable access to all sensors on the device. When 233 // enabled sensor privacy will prevent all apps, including active apps, from accessing 234 // sensors, they will not receive trigger nor on-change events, flush event behavior 235 // does not change, and recurring events are the same as the first one delivered when 236 // sensor privacy was enabled. All sensor direct connections will be stopped as well 237 // and new direct connections will not be allowed while sensor privacy is enabled. 238 // Once sensor privacy is disabled access to sensors will be restored for active 239 // apps, previously stopped direct connections will be restarted, and new direct 240 // connections will be allowed again. 241 class SensorPrivacyPolicy : public hardware::BnSensorPrivacyListener { 242 public: SensorPrivacyPolicy(wp<SensorService> service)243 explicit SensorPrivacyPolicy(wp<SensorService> service) 244 : mService(service), mIsIndividualMic(false), mUserId(0) {} 245 void registerSelf(); 246 void unregisterSelf(); 247 248 status_t registerSelfForIndividual(int userId); 249 250 bool isSensorPrivacyEnabled(); 251 252 binder::Status onSensorPrivacyChanged(bool enabled); 253 254 private: 255 wp<SensorService> mService; 256 Mutex mSensorPrivacyLock; 257 std::atomic_bool mSensorPrivacyEnabled; 258 bool mIsIndividualMic; 259 userid_t mUserId; 260 }; 261 262 // A class automatically clearing and restoring binder caller identity inside 263 // a code block (scoped variable). 264 // Declare one systematically before calling SensorPrivacyManager methods so that they are 265 // executed with the same level of privilege as the SensorService process. 266 class AutoCallerClear { 267 public: AutoCallerClear()268 AutoCallerClear() : 269 mToken(IPCThreadState::self()->clearCallingIdentity()) {} ~AutoCallerClear()270 ~AutoCallerClear() { 271 IPCThreadState::self()->restoreCallingIdentity(mToken); 272 } 273 274 private: 275 const int64_t mToken; 276 }; 277 278 enum Mode { 279 // The regular operating mode where any application can register/unregister/call flush on 280 // sensors. 281 NORMAL = 0, 282 // This mode is only used for testing purposes. Not all HALs support this mode. In this mode, 283 // the HAL ignores the sensor data provided by physical sensors and accepts the data that is 284 // injected from the SensorService as if it were the real sensor data. This mode is primarily 285 // used for testing various algorithms like vendor provided SensorFusion, Step Counter and 286 // Step Detector etc. Typically in this mode, there will be a client (a 287 // SensorEventConnection) which will be injecting sensor data into the HAL. Normal apps can 288 // unregister and register for any sensor that supports injection. Registering to sensors 289 // that do not support injection will give an error. TODO(aakella) : Allow exactly one 290 // client to inject sensor data at a time. 291 DATA_INJECTION = 1, 292 // This mode is used only for testing sensors. Each sensor can be tested in isolation with 293 // the required sampling_rate and maxReportLatency parameters without having to think about 294 // the data rates requested by other applications. End user devices are always expected to be 295 // in NORMAL mode. When this mode is first activated, all active sensors from all connections 296 // are disabled. Calling flush() will return an error. In this mode, only the requests from 297 // selected apps whose package names are whitelisted are allowed (typically CTS apps). Only 298 // these apps can register/unregister/call flush() on sensors. If SensorService switches to 299 // NORMAL mode again, all sensors that were previously registered to are activated with the 300 // corresponding paramaters if the application hasn't unregistered for sensors in the mean 301 // time. NOTE: Non whitelisted app whose sensors were previously deactivated may still 302 // receive events if a whitelisted app requests data from the same sensor. 303 RESTRICTED = 2 304 305 // State Transitions supported. 306 // RESTRICTED <--- NORMAL ---> DATA_INJECTION 307 // ---> <--- 308 309 // Shell commands to switch modes in SensorService. 310 // 1) Put SensorService in RESTRICTED mode with packageName .cts. If it is already in 311 // restricted mode it is treated as a NO_OP (and packageName is NOT changed). 312 // 313 // $ adb shell dumpsys sensorservice restrict .cts. 314 // 315 // 2) Put SensorService in DATA_INJECTION mode with packageName .xts. If it is already in 316 // data_injection mode it is treated as a NO_OP (and packageName is NOT changed). 317 // 318 // $ adb shell dumpsys sensorservice data_injection .xts. 319 // 320 // 3) Reset sensorservice back to NORMAL mode. 321 // $ adb shell dumpsys sensorservice enable 322 }; 323 324 static const char* WAKE_LOCK_NAME; 325 virtual ~SensorService(); 326 327 virtual void onFirstRef(); 328 329 // Thread interface 330 virtual bool threadLoop(); 331 332 // ISensorServer interface 333 virtual Vector<Sensor> getSensorList(const String16& opPackageName); 334 virtual Vector<Sensor> getDynamicSensorList(const String16& opPackageName); 335 virtual sp<ISensorEventConnection> createSensorEventConnection( 336 const String8& packageName, 337 int requestedMode, const String16& opPackageName, const String16& attributionTag); 338 virtual int isDataInjectionEnabled(); 339 virtual sp<ISensorEventConnection> createSensorDirectConnection(const String16& opPackageName, 340 uint32_t size, int32_t type, int32_t format, const native_handle *resource); 341 virtual int setOperationParameter( 342 int32_t handle, int32_t type, const Vector<float> &floats, const Vector<int32_t> &ints); 343 virtual status_t dump(int fd, const Vector<String16>& args); 344 345 status_t dumpProtoLocked(int fd, ConnectionSafeAutolock* connLock) const; 346 String8 getSensorName(int handle) const; 347 String8 getSensorStringType(int handle) const; 348 bool isVirtualSensor(int handle) const; 349 sp<SensorInterface> getSensorInterfaceFromHandle(int handle) const; 350 bool isWakeUpSensor(int type) const; 351 void recordLastValueLocked(sensors_event_t const* buffer, size_t count); 352 static void sortEventBuffer(sensors_event_t* buffer, size_t count); 353 const Sensor& registerSensor(SensorInterface* sensor, 354 bool isDebug = false, bool isVirtual = false); 355 const Sensor& registerVirtualSensor(SensorInterface* sensor, bool isDebug = false); 356 const Sensor& registerDynamicSensorLocked(SensorInterface* sensor, bool isDebug = false); 357 bool unregisterDynamicSensorLocked(int handle); 358 status_t cleanupWithoutDisable(const sp<SensorEventConnection>& connection, int handle); 359 status_t cleanupWithoutDisableLocked(const sp<SensorEventConnection>& connection, int handle); 360 void cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection, 361 sensors_event_t const* buffer, const int count); 362 static bool canAccessSensor(const Sensor& sensor, const char* operation, 363 const String16& opPackageName); 364 static bool hasPermissionForSensor(const Sensor& sensor); 365 static int getTargetSdkVersion(const String16& opPackageName); 366 // SensorService acquires a partial wakelock for delivering events from wake up sensors. This 367 // method checks whether all the events from these wake up sensors have been delivered to the 368 // corresponding applications, if yes the wakelock is released. 369 void checkWakeLockState(); 370 void checkWakeLockStateLocked(ConnectionSafeAutolock* connLock); 371 bool isWakeLockAcquired(); 372 bool isWakeUpSensorEvent(const sensors_event_t& event) const; 373 374 sp<Looper> getLooper() const; 375 376 // Reset mWakeLockRefCounts for all SensorEventConnections to zero. This may happen if 377 // SensorService did not receive any acknowledgements from apps which have registered for 378 // wake_up sensors. 379 void resetAllWakeLockRefCounts(); 380 381 // Acquire or release wake_lock. If wake_lock is acquired, set the timeout in the looper to 5 382 // seconds and wake the looper. 383 void setWakeLockAcquiredLocked(bool acquire); 384 385 // Send events from the event cache for this particular connection. 386 void sendEventsFromCache(const sp<SensorEventConnection>& connection); 387 388 // If SensorService is operating in RESTRICTED mode, only select whitelisted packages are 389 // allowed to register for or call flush on sensors. Typically only cts test packages are 390 // allowed. 391 bool isWhiteListedPackage(const String8& packageName); 392 393 // Returns true if a connection with the specified opPackageName has no access to sensors 394 // in the RESTRICTED mode (i.e. the service is in RESTRICTED mode, and the package is not 395 // whitelisted). mLock must be held to invoke this method. 396 bool isOperationRestrictedLocked(const String16& opPackageName); 397 398 status_t adjustSamplingPeriodBasedOnMicAndPermission(nsecs_t* requestedPeriodNs, 399 const String16& opPackageName); 400 status_t adjustRateLevelBasedOnMicAndPermission(int* requestedRateLevel, 401 const String16& opPackageName); 402 bool isRateCappedBasedOnPermission(const String16& opPackageName); 403 bool isPackageDebuggable(const String16& opPackageName); 404 405 // Reset the state of SensorService to NORMAL mode. 406 status_t resetToNormalMode(); 407 status_t resetToNormalModeLocked(); 408 409 // Transforms the UUIDs for all the sensors into proper IDs. 410 void makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const; 411 // Gets the appropriate ID from the given UUID. 412 int32_t getIdFromUuid(const Sensor::uuid_t &uuid) const; 413 // Either read from storage or create a new one. 414 static bool initializeHmacKey(); 415 416 // Enable SCHED_FIFO priority for thread 417 void enableSchedFifoMode(); 418 419 // Sets whether the given UID can get sensor data 420 void onUidStateChanged(uid_t uid, UidState state); 421 422 // Returns true if a connection with the given uid and opPackageName 423 // currently has access to sensors. 424 bool hasSensorAccess(uid_t uid, const String16& opPackageName); 425 // Same as hasSensorAccess but with mLock held. 426 bool hasSensorAccessLocked(uid_t uid, const String16& opPackageName); 427 428 // Overrides the UID state as if it is idle 429 status_t handleSetUidState(Vector<String16>& args, int err); 430 // Clears the override for the UID state 431 status_t handleResetUidState(Vector<String16>& args, int err); 432 // Gets the UID state 433 status_t handleGetUidState(Vector<String16>& args, int out, int err); 434 // Prints the shell command help 435 status_t printHelp(int out); 436 437 // temporarily stops all active direct connections and disables all sensors 438 void disableAllSensors(); 439 void disableAllSensorsLocked(ConnectionSafeAutolock* connLock); 440 // restarts the previously stopped direct connections and enables all sensors 441 void enableAllSensors(); 442 void enableAllSensorsLocked(ConnectionSafeAutolock* connLock); 443 444 // Caps active direct connections (when the mic toggle is flipped to on) 445 void capRates(userid_t userId); 446 // Removes the capped rate on active direct connections (when the mic toggle is flipped to off) 447 void uncapRates(userid_t userId); 448 449 static uint8_t sHmacGlobalKey[128]; 450 static bool sHmacGlobalKeyIsValid; 451 452 static std::atomic_uint64_t curProxCallbackSeq; 453 static std::atomic_uint64_t completedCallbackSeq; 454 455 SensorServiceUtil::SensorList mSensors; 456 status_t mInitCheck; 457 458 // Socket buffersize used to initialize BitTube. This size depends on whether batching is 459 // supported or not. 460 uint32_t mSocketBufferSize; 461 sp<Looper> mLooper; 462 sp<SensorEventAckReceiver> mAckReceiver; 463 464 // protected by mLock 465 mutable Mutex mLock; 466 DefaultKeyedVector<int, SensorRecord*> mActiveSensors; 467 std::unordered_set<int> mActiveVirtualSensors; 468 SensorConnectionHolder mConnectionHolder; 469 bool mWakeLockAcquired; 470 sensors_event_t *mSensorEventBuffer, *mSensorEventScratch; 471 // WARNING: these SensorEventConnection instances must not be promoted to sp, except via 472 // modification to add support for them in ConnectionSafeAutolock 473 wp<const SensorEventConnection> * mMapFlushEventsToConnections; 474 std::unordered_map<int, SensorServiceUtil::RecentEventLogger*> mRecentEvent; 475 Mode mCurrentOperatingMode; 476 477 // This packagaName is set when SensorService is in RESTRICTED or DATA_INJECTION mode. Only 478 // applications with this packageName are allowed to activate/deactivate or call flush on 479 // sensors. To run CTS this is can be set to ".cts." and only CTS tests will get access to 480 // sensors. 481 String8 mWhiteListedPackage; 482 483 int mNextSensorRegIndex; 484 Vector<SensorRegistrationInfo> mLastNSensorRegistrations; 485 486 sp<UidPolicy> mUidPolicy; 487 sp<SensorPrivacyPolicy> mSensorPrivacyPolicy; 488 489 static AppOpsManager sAppOpsManager; 490 static std::map<String16, int> sPackageTargetVersion; 491 static Mutex sPackageTargetVersionLock; 492 static String16 sSensorInterfaceDescriptorPrefix; 493 494 // Map from user to SensorPrivacyPolicy 495 std::map<userid_t, sp<SensorPrivacyPolicy>> mMicSensorPrivacyPolicies; 496 // Checks if the mic sensor privacy is enabled for the uid 497 bool isMicSensorPrivacyEnabledForUid(uid_t uid); 498 499 // Counts how many proximity sensors are currently active. 500 int mProximityActiveCount; 501 std::vector<sp<ProximityActiveListener>> mProximityActiveListeners; 502 }; 503 504 } // namespace android 505 #endif // ANDROID_SENSOR_SERVICE_H 506