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 namespace android { 65 // --------------------------------------------------------------------------- 66 class SensorInterface; 67 68 class SensorService : 69 public BinderService<SensorService>, 70 public BnSensorServer, 71 protected Thread 72 { 73 // nested class/struct for internal use 74 class SensorEventConnection; 75 class SensorDirectConnection; 76 77 public: 78 enum UidState { 79 UID_STATE_ACTIVE = 0, 80 UID_STATE_IDLE, 81 }; 82 83 void cleanupConnection(SensorEventConnection* connection); 84 void cleanupConnection(SensorDirectConnection* c); 85 86 status_t enable(const sp<SensorEventConnection>& connection, int handle, 87 nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags, 88 const String16& opPackageName); 89 90 status_t disable(const sp<SensorEventConnection>& connection, int handle); 91 92 status_t setEventRate(const sp<SensorEventConnection>& connection, int handle, nsecs_t ns, 93 const String16& opPackageName); 94 95 status_t flushSensor(const sp<SensorEventConnection>& connection, 96 const String16& opPackageName); 97 98 99 virtual status_t shellCommand(int in, int out, int err, Vector<String16>& args); 100 101 private: 102 friend class BinderService<SensorService>; 103 104 // nested class/struct for internal use 105 class ConnectionSafeAutolock; 106 class SensorConnectionHolder; 107 class SensorEventAckReceiver; 108 class SensorRecord; 109 class SensorRegistrationInfo; 110 111 // Promoting a SensorEventConnection or SensorDirectConnection from wp to sp must be done with 112 // mLock held, but destroying that sp must be done unlocked to avoid a race condition that 113 // causes a deadlock (remote dies while we hold a local sp, then our decStrong() call invokes 114 // the dtor -> cleanupConnection() tries to re-lock the mutex). This class ensures safe usage 115 // by wrapping a Mutex::Autolock on SensorService's mLock, plus vectors that hold promoted sp<> 116 // references until the lock is released, when they are safely destroyed. 117 // All read accesses to the connection lists in mConnectionHolder must be done via this class. 118 class ConnectionSafeAutolock final { 119 public: 120 // Returns a list of non-null promoted connection references 121 const std::vector<sp<SensorEventConnection>>& getActiveConnections(); 122 const std::vector<sp<SensorDirectConnection>>& getDirectConnections(); 123 124 private: 125 // Constructed via SensorConnectionHolder::lock() 126 friend class SensorConnectionHolder; 127 explicit ConnectionSafeAutolock(SensorConnectionHolder& holder, Mutex& mutex); 128 DISALLOW_IMPLICIT_CONSTRUCTORS(ConnectionSafeAutolock); 129 130 // NOTE: Order of these members is important, as the destructor for non-static members 131 // get invoked in the reverse order of their declaration. Here we are relying on the 132 // Autolock to be destroyed *before* the vectors, so the sp<> objects are destroyed without 133 // the lock held, which avoids the deadlock. 134 SensorConnectionHolder& mConnectionHolder; 135 std::vector<std::vector<sp<SensorEventConnection>>> mReferencedActiveConnections; 136 std::vector<std::vector<sp<SensorDirectConnection>>> mReferencedDirectConnections; 137 Mutex::Autolock mAutolock; 138 139 template<typename ConnectionType> 140 const std::vector<sp<ConnectionType>>& getConnectionsHelper( 141 const SortedVector<wp<ConnectionType>>& connectionList, 142 std::vector<std::vector<sp<ConnectionType>>>* referenceHolder); 143 }; 144 145 // Encapsulates the collection of active SensorEventConection and SensorDirectConnection 146 // references. Write access is done through this class with mLock held, but all read access 147 // must be routed through ConnectionSafeAutolock. 148 class SensorConnectionHolder { 149 public: 150 void addEventConnectionIfNotPresent(const sp<SensorEventConnection>& connection); 151 void removeEventConnection(const wp<SensorEventConnection>& connection); 152 153 void addDirectConnection(const sp<SensorDirectConnection>& connection); 154 void removeDirectConnection(const wp<SensorDirectConnection>& connection); 155 156 // Pass in the mutex that protects this connection holder; acquires the lock and returns an 157 // object that can be used to safely read the lists of connections 158 ConnectionSafeAutolock lock(Mutex& mutex); 159 160 private: 161 friend class ConnectionSafeAutolock; 162 SortedVector< wp<SensorEventConnection> > mActiveConnections; 163 SortedVector< wp<SensorDirectConnection> > mDirectConnections; 164 }; 165 166 // If accessing a sensor we need to make sure the UID has access to it. If 167 // the app UID is idle then it cannot access sensors and gets no trigger 168 // events, no on-change events, flush event behavior does not change, and 169 // recurring events are the same as the first one delivered in idle state 170 // emulating no sensor change. As soon as the app UID transitions to an 171 // active state we will start reporting events as usual and vise versa. This 172 // approach transparently handles observing sensors while the app UID transitions 173 // between idle/active state avoiding to get stuck in a state receiving sensor 174 // data while idle or not receiving sensor data while active. 175 class UidPolicy : public BnUidObserver { 176 public: UidPolicy(wp<SensorService> service)177 explicit UidPolicy(wp<SensorService> service) 178 : mService(service) {} 179 void registerSelf(); 180 void unregisterSelf(); 181 182 bool isUidActive(uid_t uid); 183 184 void onUidGone(uid_t uid, bool disabled); 185 void onUidActive(uid_t uid); 186 void onUidIdle(uid_t uid, bool disabled); onUidStateChanged(uid_t uid __unused,int32_t procState __unused,int64_t procStateSeq __unused,int32_t capability __unused)187 void onUidStateChanged(uid_t uid __unused, int32_t procState __unused, 188 int64_t procStateSeq __unused, int32_t capability __unused) {} 189 190 void addOverrideUid(uid_t uid, bool active); 191 void removeOverrideUid(uid_t uid); 192 private: 193 bool isUidActiveLocked(uid_t uid); 194 void updateOverrideUid(uid_t uid, bool active, bool insert); 195 196 Mutex mUidLock; 197 wp<SensorService> mService; 198 std::unordered_set<uid_t> mActiveUids; 199 std::unordered_map<uid_t, bool> mOverrideUids; 200 }; 201 202 bool isUidActive(uid_t uid); 203 204 // Sensor privacy allows a user to disable access to all sensors on the device. When 205 // enabled sensor privacy will prevent all apps, including active apps, from accessing 206 // sensors, they will not receive trigger nor on-change events, flush event behavior 207 // does not change, and recurring events are the same as the first one delivered when 208 // sensor privacy was enabled. All sensor direct connections will be stopped as well 209 // and new direct connections will not be allowed while sensor privacy is enabled. 210 // Once sensor privacy is disabled access to sensors will be restored for active 211 // apps, previously stopped direct connections will be restarted, and new direct 212 // connections will be allowed again. 213 class SensorPrivacyPolicy : public hardware::BnSensorPrivacyListener { 214 public: SensorPrivacyPolicy(wp<SensorService> service)215 explicit SensorPrivacyPolicy(wp<SensorService> service) : mService(service) {} 216 void registerSelf(); 217 void unregisterSelf(); 218 219 bool isSensorPrivacyEnabled(); 220 221 binder::Status onSensorPrivacyChanged(bool enabled); 222 223 private: 224 wp<SensorService> mService; 225 std::atomic_bool mSensorPrivacyEnabled; 226 }; 227 228 enum Mode { 229 // The regular operating mode where any application can register/unregister/call flush on 230 // sensors. 231 NORMAL = 0, 232 // This mode is only used for testing purposes. Not all HALs support this mode. In this mode, 233 // the HAL ignores the sensor data provided by physical sensors and accepts the data that is 234 // injected from the SensorService as if it were the real sensor data. This mode is primarily 235 // used for testing various algorithms like vendor provided SensorFusion, Step Counter and 236 // Step Detector etc. Typically in this mode, there will be a client (a 237 // SensorEventConnection) which will be injecting sensor data into the HAL. Normal apps can 238 // unregister and register for any sensor that supports injection. Registering to sensors 239 // that do not support injection will give an error. TODO(aakella) : Allow exactly one 240 // client to inject sensor data at a time. 241 DATA_INJECTION = 1, 242 // This mode is used only for testing sensors. Each sensor can be tested in isolation with 243 // the required sampling_rate and maxReportLatency parameters without having to think about 244 // the data rates requested by other applications. End user devices are always expected to be 245 // in NORMAL mode. When this mode is first activated, all active sensors from all connections 246 // are disabled. Calling flush() will return an error. In this mode, only the requests from 247 // selected apps whose package names are whitelisted are allowed (typically CTS apps). Only 248 // these apps can register/unregister/call flush() on sensors. If SensorService switches to 249 // NORMAL mode again, all sensors that were previously registered to are activated with the 250 // corresponding paramaters if the application hasn't unregistered for sensors in the mean 251 // time. NOTE: Non whitelisted app whose sensors were previously deactivated may still 252 // receive events if a whitelisted app requests data from the same sensor. 253 RESTRICTED = 2 254 255 // State Transitions supported. 256 // RESTRICTED <--- NORMAL ---> DATA_INJECTION 257 // ---> <--- 258 259 // Shell commands to switch modes in SensorService. 260 // 1) Put SensorService in RESTRICTED mode with packageName .cts. If it is already in 261 // restricted mode it is treated as a NO_OP (and packageName is NOT changed). 262 // 263 // $ adb shell dumpsys sensorservice restrict .cts. 264 // 265 // 2) Put SensorService in DATA_INJECTION mode with packageName .xts. If it is already in 266 // data_injection mode it is treated as a NO_OP (and packageName is NOT changed). 267 // 268 // $ adb shell dumpsys sensorservice data_injection .xts. 269 // 270 // 3) Reset sensorservice back to NORMAL mode. 271 // $ adb shell dumpsys sensorservice enable 272 }; 273 274 static const char* WAKE_LOCK_NAME; getServiceName()275 static char const* getServiceName() ANDROID_API { return "sensorservice"; } 276 SensorService() ANDROID_API; 277 virtual ~SensorService(); 278 279 virtual void onFirstRef(); 280 281 // Thread interface 282 virtual bool threadLoop(); 283 284 // ISensorServer interface 285 virtual Vector<Sensor> getSensorList(const String16& opPackageName); 286 virtual Vector<Sensor> getDynamicSensorList(const String16& opPackageName); 287 virtual sp<ISensorEventConnection> createSensorEventConnection( 288 const String8& packageName, 289 int requestedMode, const String16& opPackageName); 290 virtual int isDataInjectionEnabled(); 291 virtual sp<ISensorEventConnection> createSensorDirectConnection(const String16& opPackageName, 292 uint32_t size, int32_t type, int32_t format, const native_handle *resource); 293 virtual int setOperationParameter( 294 int32_t handle, int32_t type, const Vector<float> &floats, const Vector<int32_t> &ints); 295 virtual status_t dump(int fd, const Vector<String16>& args); 296 status_t dumpProtoLocked(int fd, ConnectionSafeAutolock* connLock) const; 297 String8 getSensorName(int handle) const; 298 bool isVirtualSensor(int handle) const; 299 sp<SensorInterface> getSensorInterfaceFromHandle(int handle) const; 300 bool isWakeUpSensor(int type) const; 301 void recordLastValueLocked(sensors_event_t const* buffer, size_t count); 302 static void sortEventBuffer(sensors_event_t* buffer, size_t count); 303 const Sensor& registerSensor(SensorInterface* sensor, 304 bool isDebug = false, bool isVirtual = false); 305 const Sensor& registerVirtualSensor(SensorInterface* sensor, bool isDebug = false); 306 const Sensor& registerDynamicSensorLocked(SensorInterface* sensor, bool isDebug = false); 307 bool unregisterDynamicSensorLocked(int handle); 308 status_t cleanupWithoutDisable(const sp<SensorEventConnection>& connection, int handle); 309 status_t cleanupWithoutDisableLocked(const sp<SensorEventConnection>& connection, int handle); 310 void cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection, 311 sensors_event_t const* buffer, const int count); 312 static bool canAccessSensor(const Sensor& sensor, const char* operation, 313 const String16& opPackageName); 314 static bool hasPermissionForSensor(const Sensor& sensor); 315 static int getTargetSdkVersion(const String16& opPackageName); 316 // SensorService acquires a partial wakelock for delivering events from wake up sensors. This 317 // method checks whether all the events from these wake up sensors have been delivered to the 318 // corresponding applications, if yes the wakelock is released. 319 void checkWakeLockState(); 320 void checkWakeLockStateLocked(ConnectionSafeAutolock* connLock); 321 bool isWakeLockAcquired(); 322 bool isWakeUpSensorEvent(const sensors_event_t& event) const; 323 324 sp<Looper> getLooper() const; 325 326 // Reset mWakeLockRefCounts for all SensorEventConnections to zero. This may happen if 327 // SensorService did not receive any acknowledgements from apps which have registered for 328 // wake_up sensors. 329 void resetAllWakeLockRefCounts(); 330 331 // Acquire or release wake_lock. If wake_lock is acquired, set the timeout in the looper to 5 332 // seconds and wake the looper. 333 void setWakeLockAcquiredLocked(bool acquire); 334 335 // Send events from the event cache for this particular connection. 336 void sendEventsFromCache(const sp<SensorEventConnection>& connection); 337 338 // If SensorService is operating in RESTRICTED mode, only select whitelisted packages are 339 // allowed to register for or call flush on sensors. Typically only cts test packages are 340 // allowed. 341 bool isWhiteListedPackage(const String8& packageName); 342 343 // Returns true if a connection with the specified opPackageName has no access to sensors 344 // in the RESTRICTED mode (i.e. the service is in RESTRICTED mode, and the package is not 345 // whitelisted). mLock must be held to invoke this method. 346 bool isOperationRestrictedLocked(const String16& opPackageName); 347 348 // Reset the state of SensorService to NORMAL mode. 349 status_t resetToNormalMode(); 350 status_t resetToNormalModeLocked(); 351 352 // Transforms the UUIDs for all the sensors into proper IDs. 353 void makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const; 354 // Gets the appropriate ID from the given UUID. 355 int32_t getIdFromUuid(const Sensor::uuid_t &uuid) const; 356 // Either read from storage or create a new one. 357 static bool initializeHmacKey(); 358 359 // Enable SCHED_FIFO priority for thread 360 void enableSchedFifoMode(); 361 362 // Sets whether the given UID can get sensor data 363 void onUidStateChanged(uid_t uid, UidState state); 364 365 // Returns true if a connection with the given uid and opPackageName 366 // currently has access to sensors. 367 bool hasSensorAccess(uid_t uid, const String16& opPackageName); 368 // Same as hasSensorAccess but with mLock held. 369 bool hasSensorAccessLocked(uid_t uid, const String16& opPackageName); 370 371 // Overrides the UID state as if it is idle 372 status_t handleSetUidState(Vector<String16>& args, int err); 373 // Clears the override for the UID state 374 status_t handleResetUidState(Vector<String16>& args, int err); 375 // Gets the UID state 376 status_t handleGetUidState(Vector<String16>& args, int out, int err); 377 // Prints the shell command help 378 status_t printHelp(int out); 379 380 // temporarily stops all active direct connections and disables all sensors 381 void disableAllSensors(); 382 void disableAllSensorsLocked(ConnectionSafeAutolock* connLock); 383 // restarts the previously stopped direct connections and enables all sensors 384 void enableAllSensors(); 385 void enableAllSensorsLocked(ConnectionSafeAutolock* connLock); 386 387 static uint8_t sHmacGlobalKey[128]; 388 static bool sHmacGlobalKeyIsValid; 389 390 SensorServiceUtil::SensorList mSensors; 391 status_t mInitCheck; 392 393 // Socket buffersize used to initialize BitTube. This size depends on whether batching is 394 // supported or not. 395 uint32_t mSocketBufferSize; 396 sp<Looper> mLooper; 397 sp<SensorEventAckReceiver> mAckReceiver; 398 399 // protected by mLock 400 mutable Mutex mLock; 401 DefaultKeyedVector<int, SensorRecord*> mActiveSensors; 402 std::unordered_set<int> mActiveVirtualSensors; 403 SensorConnectionHolder mConnectionHolder; 404 bool mWakeLockAcquired; 405 sensors_event_t *mSensorEventBuffer, *mSensorEventScratch; 406 // WARNING: these SensorEventConnection instances must not be promoted to sp, except via 407 // modification to add support for them in ConnectionSafeAutolock 408 wp<const SensorEventConnection> * mMapFlushEventsToConnections; 409 std::unordered_map<int, SensorServiceUtil::RecentEventLogger*> mRecentEvent; 410 Mode mCurrentOperatingMode; 411 412 // This packagaName is set when SensorService is in RESTRICTED or DATA_INJECTION mode. Only 413 // applications with this packageName are allowed to activate/deactivate or call flush on 414 // sensors. To run CTS this is can be set to ".cts." and only CTS tests will get access to 415 // sensors. 416 String8 mWhiteListedPackage; 417 418 int mNextSensorRegIndex; 419 Vector<SensorRegistrationInfo> mLastNSensorRegistrations; 420 421 sp<UidPolicy> mUidPolicy; 422 sp<SensorPrivacyPolicy> mSensorPrivacyPolicy; 423 424 static AppOpsManager sAppOpsManager; 425 static std::map<String16, int> sPackageTargetVersion; 426 static Mutex sPackageTargetVersionLock; 427 static String16 sSensorInterfaceDescriptorPrefix; 428 }; 429 430 } // namespace android 431 #endif // ANDROID_SENSOR_SERVICE_H 432