blob: 50769678b7134857de5e217761f9661e5f5713f1 [file] [log] [blame]
Mathias Agopianfc328812010-07-14 23:41:37 -07001/*
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
Peng Xu755c4512016-04-07 23:15:14 -070020#include "SensorList.h"
Peng Xu6a2d3a02015-12-21 12:00:23 -080021#include "RecentEventLogger.h"
Mathias Agopianfc328812010-07-14 23:41:37 -070022
23#include <binder/BinderService.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080024#include <binder/IUidObserver.h>
Peng Xu755c4512016-04-07 23:15:14 -070025#include <cutils/compiler.h>
Tanmay Patild33a1822019-04-11 18:38:55 -070026#include <cutils/multiuser.h>
Mathias Agopian801ea092017-03-06 15:05:04 -080027#include <sensor/ISensorServer.h>
28#include <sensor/ISensorEventConnection.h>
29#include <sensor/Sensor.h>
Michael Groover5e1f60b2018-12-04 22:34:29 -080030#include "android/hardware/BnSensorPrivacyListener.h"
Mathias Agopianfc328812010-07-14 23:41:37 -070031
Peng Xu755c4512016-04-07 23:15:14 -070032#include <utils/AndroidThreads.h>
33#include <utils/KeyedVector.h>
34#include <utils/Looper.h>
35#include <utils/SortedVector.h>
36#include <utils/String8.h>
37#include <utils/Vector.h>
38#include <utils/threads.h>
39
40#include <stdint.h>
41#include <sys/types.h>
Peng Xu6a2d3a02015-12-21 12:00:23 -080042#include <unordered_map>
Peng Xu755c4512016-04-07 23:15:14 -070043#include <unordered_set>
Mathias Agopianf001c922010-11-11 17:58:51 -080044
Bernhard Rosenkränzer72952ef2014-11-17 21:03:39 +010045#if __clang__
Peng Xueb4d6282015-12-10 18:02:41 -080046// Clang warns about SensorEventConnection::dump hiding BBinder::dump. The cause isn't fixable
47// without changing the API, so let's tell clang this is indeed intentional.
Bernhard Rosenkränzer72952ef2014-11-17 21:03:39 +010048#pragma clang diagnostic ignored "-Woverloaded-virtual"
49#endif
50
Mathias Agopianfc328812010-07-14 23:41:37 -070051// ---------------------------------------------------------------------------
Peng Xuf66684a2015-07-23 11:41:53 -070052#define IGNORE_HARDWARE_FUSION false
Mathias Agopiana1b7db92011-05-27 16:23:58 -070053#define DEBUG_CONNECTIONS false
Aravind Akella56ae4262014-07-10 16:01:10 -070054// Max size is 100 KB which is enough to accept a batch of about 1000 events.
Chih-Hung Hsieha389c7a2016-05-20 11:40:04 -070055#define MAX_SOCKET_BUFFER_SIZE_BATCHED (100 * 1024)
Aravind Akella56ae4262014-07-10 16:01:10 -070056// For older HALs which don't support batching, use a smaller socket buffer size.
Chih-Hung Hsieha389c7a2016-05-20 11:40:04 -070057#define SOCKET_BUFFER_SIZE_NON_BATCHED (4 * 1024)
Mathias Agopiana1b7db92011-05-27 16:23:58 -070058
Peng Xu363b3fd2016-07-07 15:40:08 -070059#define SENSOR_REGISTRATIONS_BUF_SIZE 200
Aravind Akella444f2672015-05-07 12:40:52 -070060
Mathias Agopianfc328812010-07-14 23:41:37 -070061namespace android {
62// ---------------------------------------------------------------------------
Peng Xu755c4512016-04-07 23:15:14 -070063class SensorInterface;
Mathias Agopianfc328812010-07-14 23:41:37 -070064
65class SensorService :
66 public BinderService<SensorService>,
67 public BnSensorServer,
68 protected Thread
69{
Peng Xueb4d6282015-12-10 18:02:41 -080070 // nested class/struct for internal use
71 class SensorEventConnection;
Peng Xue36e3472016-11-03 11:57:10 -070072 class SensorDirectConnection;
Peng Xueb4d6282015-12-10 18:02:41 -080073
74public:
75 void cleanupConnection(SensorEventConnection* connection);
Peng Xue36e3472016-11-03 11:57:10 -070076 void cleanupConnection(SensorDirectConnection* c);
Peng Xueb4d6282015-12-10 18:02:41 -080077
78 status_t enable(const sp<SensorEventConnection>& connection, int handle,
79 nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
80 const String16& opPackageName);
81
82 status_t disable(const sp<SensorEventConnection>& connection, int handle);
83
84 status_t setEventRate(const sp<SensorEventConnection>& connection, int handle, nsecs_t ns,
85 const String16& opPackageName);
86
87 status_t flushSensor(const sp<SensorEventConnection>& connection,
88 const String16& opPackageName);
89
Svet Ganove752a5c2018-01-15 17:14:20 -080090
91 virtual status_t shellCommand(int in, int out, int err, Vector<String16>& args);
92
Peng Xueb4d6282015-12-10 18:02:41 -080093private:
Mathias Agopianb6df7d02013-05-09 14:53:35 -070094 friend class BinderService<SensorService>;
Mathias Agopianfc328812010-07-14 23:41:37 -070095
Peng Xueb4d6282015-12-10 18:02:41 -080096 // nested class/struct for internal use
97 class SensorRecord;
98 class SensorEventAckReceiver;
Peng Xu51224682017-03-10 16:57:27 -080099 class SensorRegistrationInfo;
Peng Xueb4d6282015-12-10 18:02:41 -0800100
Svet Ganove752a5c2018-01-15 17:14:20 -0800101 // If accessing a sensor we need to make sure the UID has access to it. If
102 // the app UID is idle then it cannot access sensors and gets no trigger
103 // events, no on-change events, flush event behavior does not change, and
104 // recurring events are the same as the first one delivered in idle state
105 // emulating no sensor change. As soon as the app UID transitions to an
106 // active state we will start reporting events as usual and vise versa. This
107 // approach transparently handles observing sensors while the app UID transitions
108 // between idle/active state avoiding to get stuck in a state receiving sensor
109 // data while idle or not receiving sensor data while active.
110 class UidPolicy : public BnUidObserver {
111 public:
112 explicit UidPolicy(wp<SensorService> service)
113 : mService(service) {}
114 void registerSelf();
115 void unregisterSelf();
116
117 bool isUidActive(uid_t uid);
118
119 void onUidGone(uid_t uid, bool disabled);
120 void onUidActive(uid_t uid);
121 void onUidIdle(uid_t uid, bool disabled);
Eric Laurent05595892018-10-18 14:56:24 -0700122 void onUidStateChanged(uid_t uid __unused, int32_t procState __unused,
123 int64_t procStateSeq __unused) {}
Svet Ganove752a5c2018-01-15 17:14:20 -0800124
125 void addOverrideUid(uid_t uid, bool active);
126 void removeOverrideUid(uid_t uid);
127 private:
128 bool isUidActiveLocked(uid_t uid);
129 void updateOverrideUid(uid_t uid, bool active, bool insert);
130
131 Mutex mUidLock;
132 wp<SensorService> mService;
133 std::unordered_set<uid_t> mActiveUids;
134 std::unordered_map<uid_t, bool> mOverrideUids;
135 };
136
Michael Groover5e1f60b2018-12-04 22:34:29 -0800137 // Sensor privacy allows a user to disable access to all sensors on the device. When
138 // enabled sensor privacy will prevent all apps, including active apps, from accessing
139 // sensors, they will not receive trigger nor on-change events, flush event behavior
140 // does not change, and recurring events are the same as the first one delivered when
141 // sensor privacy was enabled. All sensor direct connections will be stopped as well
142 // and new direct connections will not be allowed while sensor privacy is enabled.
143 // Once sensor privacy is disabled access to sensors will be restored for active
144 // apps, previously stopped direct connections will be restarted, and new direct
145 // connections will be allowed again.
146 class SensorPrivacyPolicy : public hardware::BnSensorPrivacyListener {
147 public:
148 explicit SensorPrivacyPolicy(wp<SensorService> service) : mService(service) {}
149 void registerSelf();
150 void unregisterSelf();
151
152 bool isSensorPrivacyEnabled();
153
154 binder::Status onSensorPrivacyChanged(bool enabled);
155
156 private:
157 wp<SensorService> mService;
158 std::atomic_bool mSensorPrivacyEnabled;
159 };
160
Aravind Akella4949c502015-02-11 15:54:35 -0800161 enum Mode {
162 // The regular operating mode where any application can register/unregister/call flush on
163 // sensors.
164 NORMAL = 0,
Peng Xueb4d6282015-12-10 18:02:41 -0800165 // This mode is only used for testing purposes. Not all HALs support this mode. In this mode,
166 // the HAL ignores the sensor data provided by physical sensors and accepts the data that is
167 // injected from the SensorService as if it were the real sensor data. This mode is primarily
168 // used for testing various algorithms like vendor provided SensorFusion, Step Counter and
169 // Step Detector etc. Typically in this mode, there will be a client (a
170 // SensorEventConnection) which will be injecting sensor data into the HAL. Normal apps can
171 // unregister and register for any sensor that supports injection. Registering to sensors
172 // that do not support injection will give an error. TODO(aakella) : Allow exactly one
173 // client to inject sensor data at a time.
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700174 DATA_INJECTION = 1,
Aravind Akella4949c502015-02-11 15:54:35 -0800175 // This mode is used only for testing sensors. Each sensor can be tested in isolation with
176 // the required sampling_rate and maxReportLatency parameters without having to think about
177 // the data rates requested by other applications. End user devices are always expected to be
178 // in NORMAL mode. When this mode is first activated, all active sensors from all connections
179 // are disabled. Calling flush() will return an error. In this mode, only the requests from
180 // selected apps whose package names are whitelisted are allowed (typically CTS apps). Only
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700181 // these apps can register/unregister/call flush() on sensors. If SensorService switches to
Aravind Akella4949c502015-02-11 15:54:35 -0800182 // NORMAL mode again, all sensors that were previously registered to are activated with the
183 // corresponding paramaters if the application hasn't unregistered for sensors in the mean
Peng Xueb4d6282015-12-10 18:02:41 -0800184 // time. NOTE: Non whitelisted app whose sensors were previously deactivated may still
185 // receive events if a whitelisted app requests data from the same sensor.
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700186 RESTRICTED = 2
187
188 // State Transitions supported.
189 // RESTRICTED <--- NORMAL ---> DATA_INJECTION
190 // ---> <---
Aravind Akella5c538052015-06-29 12:37:48 -0700191
192 // Shell commands to switch modes in SensorService.
193 // 1) Put SensorService in RESTRICTED mode with packageName .cts. If it is already in
194 // restricted mode it is treated as a NO_OP (and packageName is NOT changed).
Peng Xueb4d6282015-12-10 18:02:41 -0800195 //
196 // $ adb shell dumpsys sensorservice restrict .cts.
Aravind Akella5c538052015-06-29 12:37:48 -0700197 //
198 // 2) Put SensorService in DATA_INJECTION mode with packageName .xts. If it is already in
199 // data_injection mode it is treated as a NO_OP (and packageName is NOT changed).
Peng Xueb4d6282015-12-10 18:02:41 -0800200 //
201 // $ adb shell dumpsys sensorservice data_injection .xts.
Aravind Akella5c538052015-06-29 12:37:48 -0700202 //
203 // 3) Reset sensorservice back to NORMAL mode.
Peng Xueb4d6282015-12-10 18:02:41 -0800204 // $ adb shell dumpsys sensorservice enable
Aravind Akella4949c502015-02-11 15:54:35 -0800205 };
206
Mathias Agopianb6df7d02013-05-09 14:53:35 -0700207 static const char* WAKE_LOCK_NAME;
Mathias Agopianb6df7d02013-05-09 14:53:35 -0700208 static char const* getServiceName() ANDROID_API { return "sensorservice"; }
209 SensorService() ANDROID_API;
Mathias Agopianfc328812010-07-14 23:41:37 -0700210 virtual ~SensorService();
211
212 virtual void onFirstRef();
213
214 // Thread interface
215 virtual bool threadLoop();
216
217 // ISensorServer interface
Svetoslavb412f6e2015-04-29 16:50:41 -0700218 virtual Vector<Sensor> getSensorList(const String16& opPackageName);
Peng Xu2576cb62016-01-20 00:22:09 -0800219 virtual Vector<Sensor> getDynamicSensorList(const String16& opPackageName);
Peng Xueb4d6282015-12-10 18:02:41 -0800220 virtual sp<ISensorEventConnection> createSensorEventConnection(
221 const String8& packageName,
222 int requestedMode, const String16& opPackageName);
Aravind Akella5c538052015-06-29 12:37:48 -0700223 virtual int isDataInjectionEnabled();
Peng Xue36e3472016-11-03 11:57:10 -0700224 virtual sp<ISensorEventConnection> createSensorDirectConnection(const String16& opPackageName,
225 uint32_t size, int32_t type, int32_t format, const native_handle *resource);
Peng Xudd5c5cb2017-03-16 17:39:43 -0700226 virtual int setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -0700227 int32_t handle, int32_t type, const Vector<float> &floats, const Vector<int32_t> &ints);
Mathias Agopianfc328812010-07-14 23:41:37 -0700228 virtual status_t dump(int fd, const Vector<String16>& args);
Mathias Agopianf001c922010-11-11 17:58:51 -0800229 String8 getSensorName(int handle) const;
Aravind Akellab4099e72013-10-15 15:43:10 -0700230 bool isVirtualSensor(int handle) const;
Peng Xu755c4512016-04-07 23:15:14 -0700231 sp<SensorInterface> getSensorInterfaceFromHandle(int handle) const;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800232 bool isWakeUpSensor(int type) const;
Aravind Akella0ec20662014-09-14 17:29:48 -0700233 void recordLastValueLocked(sensors_event_t const* buffer, size_t count);
Mathias Agopianf001c922010-11-11 17:58:51 -0800234 static void sortEventBuffer(sensors_event_t* buffer, size_t count);
Peng Xu0cc8f802016-04-05 23:46:03 -0700235 const Sensor& registerSensor(SensorInterface* sensor,
236 bool isDebug = false, bool isVirtual = false);
237 const Sensor& registerVirtualSensor(SensorInterface* sensor, bool isDebug = false);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800238 const Sensor& registerDynamicSensorLocked(SensorInterface* sensor, bool isDebug = false);
239 bool unregisterDynamicSensorLocked(int handle);
Peng Xueb4d6282015-12-10 18:02:41 -0800240 status_t cleanupWithoutDisable(const sp<SensorEventConnection>& connection, int handle);
241 status_t cleanupWithoutDisableLocked(const sp<SensorEventConnection>& connection, int handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800242 void cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Mathias Agopianb6df7d02013-05-09 14:53:35 -0700243 sensors_event_t const* buffer, const int count);
Svetoslavb412f6e2015-04-29 16:50:41 -0700244 static bool canAccessSensor(const Sensor& sensor, const char* operation,
245 const String16& opPackageName);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800246 // SensorService acquires a partial wakelock for delivering events from wake up sensors. This
247 // method checks whether all the events from these wake up sensors have been delivered to the
248 // corresponding applications, if yes the wakelock is released.
249 void checkWakeLockState();
250 void checkWakeLockStateLocked();
Aravind Akellab4373ac2014-10-29 17:55:20 -0700251 bool isWakeLockAcquired();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800252 bool isWakeUpSensorEvent(const sensors_event_t& event) const;
Aravind Akella56ae4262014-07-10 16:01:10 -0700253
254 sp<Looper> getLooper() const;
255
Aravind Akellab4373ac2014-10-29 17:55:20 -0700256 // Reset mWakeLockRefCounts for all SensorEventConnections to zero. This may happen if
257 // SensorService did not receive any acknowledgements from apps which have registered for
258 // wake_up sensors.
259 void resetAllWakeLockRefCounts();
260
Peng Xueb4d6282015-12-10 18:02:41 -0800261 // Acquire or release wake_lock. If wake_lock is acquired, set the timeout in the looper to 5
262 // seconds and wake the looper.
Aravind Akellab4373ac2014-10-29 17:55:20 -0700263 void setWakeLockAcquiredLocked(bool acquire);
264
265 // Send events from the event cache for this particular connection.
266 void sendEventsFromCache(const sp<SensorEventConnection>& connection);
267
268 // Promote all weak referecences in mActiveConnections vector to strong references and add them
269 // to the output vector.
Peng Xueb4d6282015-12-10 18:02:41 -0800270 void populateActiveConnections( SortedVector< sp<SensorEventConnection> >* activeConnections);
Aravind Akellab4373ac2014-10-29 17:55:20 -0700271
Aravind Akella4949c502015-02-11 15:54:35 -0800272 // If SensorService is operating in RESTRICTED mode, only select whitelisted packages are
273 // allowed to register for or call flush on sensors. Typically only cts test packages are
274 // allowed.
275 bool isWhiteListedPackage(const String8& packageName);
Brian Stack5180e462019-03-08 17:15:19 -0800276 bool isOperationPermitted(const String16& opPackageName);
Aravind Akella4949c502015-02-11 15:54:35 -0800277
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700278 // Reset the state of SensorService to NORMAL mode.
279 status_t resetToNormalMode();
280 status_t resetToNormalModeLocked();
281
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700282 // Transforms the UUIDs for all the sensors into proper IDs.
283 void makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const;
284 // Gets the appropriate ID from the given UUID.
285 int32_t getIdFromUuid(const Sensor::uuid_t &uuid) const;
286 // Either read from storage or create a new one.
287 static bool initializeHmacKey();
288
Peng Xu98d30f62016-08-01 18:12:11 -0700289 // Enable SCHED_FIFO priority for thread
290 void enableSchedFifoMode();
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700291
Svet Ganove752a5c2018-01-15 17:14:20 -0800292 // Sets whether the given UID can get sensor data
293 void setSensorAccess(uid_t uid, bool hasAccess);
294
295 // Overrides the UID state as if it is idle
296 status_t handleSetUidState(Vector<String16>& args, int err);
297 // Clears the override for the UID state
298 status_t handleResetUidState(Vector<String16>& args, int err);
299 // Gets the UID state
300 status_t handleGetUidState(Vector<String16>& args, int out, int err);
301 // Prints the shell command help
302 status_t printHelp(int out);
303
Michael Groover5e1f60b2018-12-04 22:34:29 -0800304 // temporarily stops all active direct connections and disables all sensors
305 void disableAllSensors();
306 void disableAllSensorsLocked();
307 // restarts the previously stopped direct connections and enables all sensors
308 void enableAllSensors();
309 void enableAllSensorsLocked();
310
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700311 static uint8_t sHmacGlobalKey[128];
312 static bool sHmacGlobalKeyIsValid;
313
Brian Stack4baa5be2018-09-18 14:03:13 -0700314 SensorServiceUtil::SensorList mSensors;
Mathias Agopian50df2952010-07-19 19:09:10 -0700315 status_t mInitCheck;
Peng Xueb4d6282015-12-10 18:02:41 -0800316
Aravind Akella5466c3d2014-08-22 16:11:10 -0700317 // Socket buffersize used to initialize BitTube. This size depends on whether batching is
318 // supported or not.
Peng Xu755c4512016-04-07 23:15:14 -0700319 uint32_t mSocketBufferSize;
320 sp<Looper> mLooper;
321 sp<SensorEventAckReceiver> mAckReceiver;
Mathias Agopianfc328812010-07-14 23:41:37 -0700322
323 // protected by mLock
324 mutable Mutex mLock;
Mathias Agopianfc328812010-07-14 23:41:37 -0700325 DefaultKeyedVector<int, SensorRecord*> mActiveSensors;
Peng Xu755c4512016-04-07 23:15:14 -0700326 std::unordered_set<int> mActiveVirtualSensors;
Mathias Agopianfc328812010-07-14 23:41:37 -0700327 SortedVector< wp<SensorEventConnection> > mActiveConnections;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800328 bool mWakeLockAcquired;
Aravind Akella8493b792014-09-08 15:45:47 -0700329 sensors_event_t *mSensorEventBuffer, *mSensorEventScratch;
Peng Xuded526e2016-08-12 16:39:44 -0700330 wp<const SensorEventConnection> * mMapFlushEventsToConnections;
Brian Stack4baa5be2018-09-18 14:03:13 -0700331 std::unordered_map<int, SensorServiceUtil::RecentEventLogger*> mRecentEvent;
Peng Xue36e3472016-11-03 11:57:10 -0700332 SortedVector< wp<SensorDirectConnection> > mDirectConnections;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700333 Mode mCurrentOperatingMode;
Peng Xueb4d6282015-12-10 18:02:41 -0800334
Aravind Akella5c538052015-06-29 12:37:48 -0700335 // This packagaName is set when SensorService is in RESTRICTED or DATA_INJECTION mode. Only
336 // applications with this packageName are allowed to activate/deactivate or call flush on
337 // sensors. To run CTS this is can be set to ".cts." and only CTS tests will get access to
338 // sensors.
339 String8 mWhiteListedPackage;
Aravind Akella8493b792014-09-08 15:45:47 -0700340
Aravind Akella18d6d512015-06-18 14:18:28 -0700341 int mNextSensorRegIndex;
342 Vector<SensorRegistrationInfo> mLastNSensorRegistrations;
Svet Ganove752a5c2018-01-15 17:14:20 -0800343
344 sp<UidPolicy> mUidPolicy;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800345 sp<SensorPrivacyPolicy> mSensorPrivacyPolicy;
Mathias Agopianfc328812010-07-14 23:41:37 -0700346};
347
Peng Xueb4d6282015-12-10 18:02:41 -0800348} // namespace android
Mathias Agopianfc328812010-07-14 23:41:37 -0700349#endif // ANDROID_SENSOR_SERVICE_H