blob: b009829ed6087392bafbc091247af713082bf204 [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
Brian Duddie967ce172019-06-10 11:08:27 -070023#include <android-base/macros.h>
Brian Stack793f4642019-04-18 17:21:34 -070024#include <binder/AppOpsManager.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070025#include <binder/BinderService.h>
Svet Ganove752a5c2018-01-15 17:14:20 -080026#include <binder/IUidObserver.h>
Peng Xu755c4512016-04-07 23:15:14 -070027#include <cutils/compiler.h>
Tanmay Patild33a1822019-04-11 18:38:55 -070028#include <cutils/multiuser.h>
Eric Laurente3f27df2022-01-05 19:20:32 +010029#include <private/android_filesystem_config.h>
Mathias Agopian801ea092017-03-06 15:05:04 -080030#include <sensor/ISensorServer.h>
31#include <sensor/ISensorEventConnection.h>
32#include <sensor/Sensor.h>
Michael Groover5e1f60b2018-12-04 22:34:29 -080033#include "android/hardware/BnSensorPrivacyListener.h"
Mathias Agopianfc328812010-07-14 23:41:37 -070034
Peng Xu755c4512016-04-07 23:15:14 -070035#include <utils/AndroidThreads.h>
36#include <utils/KeyedVector.h>
37#include <utils/Looper.h>
38#include <utils/SortedVector.h>
39#include <utils/String8.h>
40#include <utils/Vector.h>
41#include <utils/threads.h>
42
43#include <stdint.h>
44#include <sys/types.h>
Peng Xu6a2d3a02015-12-21 12:00:23 -080045#include <unordered_map>
Peng Xu755c4512016-04-07 23:15:14 -070046#include <unordered_set>
Brian Duddie967ce172019-06-10 11:08:27 -070047#include <vector>
Mathias Agopianf001c922010-11-11 17:58:51 -080048
Bernhard Rosenkränzer72952ef2014-11-17 21:03:39 +010049#if __clang__
Peng Xueb4d6282015-12-10 18:02:41 -080050// Clang warns about SensorEventConnection::dump hiding BBinder::dump. The cause isn't fixable
51// without changing the API, so let's tell clang this is indeed intentional.
Bernhard Rosenkränzer72952ef2014-11-17 21:03:39 +010052#pragma clang diagnostic ignored "-Woverloaded-virtual"
53#endif
54
Mathias Agopianfc328812010-07-14 23:41:37 -070055// ---------------------------------------------------------------------------
Peng Xuf66684a2015-07-23 11:41:53 -070056#define IGNORE_HARDWARE_FUSION false
Mathias Agopiana1b7db92011-05-27 16:23:58 -070057#define DEBUG_CONNECTIONS false
Aravind Akella56ae4262014-07-10 16:01:10 -070058// Max size is 100 KB which is enough to accept a batch of about 1000 events.
Chih-Hung Hsieha389c7a2016-05-20 11:40:04 -070059#define MAX_SOCKET_BUFFER_SIZE_BATCHED (100 * 1024)
Aravind Akella56ae4262014-07-10 16:01:10 -070060// For older HALs which don't support batching, use a smaller socket buffer size.
Chih-Hung Hsieha389c7a2016-05-20 11:40:04 -070061#define SOCKET_BUFFER_SIZE_NON_BATCHED (4 * 1024)
Mathias Agopiana1b7db92011-05-27 16:23:58 -070062
Peng Xu363b3fd2016-07-07 15:40:08 -070063#define SENSOR_REGISTRATIONS_BUF_SIZE 200
Aravind Akella444f2672015-05-07 12:40:52 -070064
Anh Phamaf91a912021-02-10 14:10:53 +010065// Apps that targets S+ and do not have HIGH_SAMPLING_RATE_SENSORS permission will be capped
Anh Pham5198c992021-02-10 14:15:30 +010066// at 200 Hz. The cap also applies to all requests when the mic toggle is flipped to on, regardless
67// of their target SDKs and permission.
Anh Phamaf91a912021-02-10 14:10:53 +010068// Capped sampling periods for apps that have non-direct sensor connections.
69#define SENSOR_SERVICE_CAPPED_SAMPLING_PERIOD_NS (5 * 1000 * 1000)
70// Capped sampling rate level for apps that have direct sensor connections.
71// The enum SENSOR_DIRECT_RATE_NORMAL corresponds to a rate value of at most 110 Hz.
72#define SENSOR_SERVICE_CAPPED_SAMPLING_RATE_LEVEL SENSOR_DIRECT_RATE_NORMAL
73
Mathias Agopianfc328812010-07-14 23:41:37 -070074namespace android {
75// ---------------------------------------------------------------------------
Peng Xu755c4512016-04-07 23:15:14 -070076class SensorInterface;
Mathias Agopianfc328812010-07-14 23:41:37 -070077
78class SensorService :
79 public BinderService<SensorService>,
80 public BnSensorServer,
81 protected Thread
82{
Peng Xueb4d6282015-12-10 18:02:41 -080083 // nested class/struct for internal use
84 class SensorEventConnection;
Peng Xue36e3472016-11-03 11:57:10 -070085 class SensorDirectConnection;
Peng Xueb4d6282015-12-10 18:02:41 -080086
87public:
Arthur Ishiguro539c27c2020-04-13 09:47:59 -070088 enum UidState {
89 UID_STATE_ACTIVE = 0,
90 UID_STATE_IDLE,
91 };
92
Arthur Ishiguro5e3eaa82021-11-11 18:05:56 +000093 enum Mode {
94 // The regular operating mode where any application can register/unregister/call flush on
95 // sensors.
96 NORMAL = 0,
97 // This mode is only used for testing purposes. Not all HALs support this mode. In this mode,
98 // the HAL ignores the sensor data provided by physical sensors and accepts the data that is
99 // injected from the SensorService as if it were the real sensor data. This mode is primarily
100 // used for testing various algorithms like vendor provided SensorFusion, Step Counter and
101 // Step Detector etc. Typically in this mode, there will be a client (a
102 // SensorEventConnection) which will be injecting sensor data into the HAL. Normal apps can
103 // unregister and register for any sensor that supports injection. Registering to sensors
104 // that do not support injection will give an error. TODO: Allow exactly one
105 // client to inject sensor data at a time.
106 DATA_INJECTION = 1,
107 // This mode is used only for testing sensors. Each sensor can be tested in isolation with
108 // the required sampling_rate and maxReportLatency parameters without having to think about
109 // the data rates requested by other applications. End user devices are always expected to be
110 // in NORMAL mode. When this mode is first activated, all active sensors from all connections
111 // are disabled. Calling flush() will return an error. In this mode, only the requests from
112 // selected apps whose package names are allowlisted are allowed (typically CTS apps). Only
113 // these apps can register/unregister/call flush() on sensors. If SensorService switches to
114 // NORMAL mode again, all sensors that were previously registered to are activated with the
115 // corresponding parameters if the application hasn't unregistered for sensors in the mean
116 // time. NOTE: Non allowlisted app whose sensors were previously deactivated may still
117 // receive events if a allowlisted app requests data from the same sensor.
118 RESTRICTED = 2
119
120 // State Transitions supported.
121 // RESTRICTED <--- NORMAL ---> DATA_INJECTION
122 // ---> <---
123
124 // Shell commands to switch modes in SensorService.
125 // 1) Put SensorService in RESTRICTED mode with packageName .cts. If it is already in
126 // restricted mode it is treated as a NO_OP (and packageName is NOT changed).
127 //
128 // $ adb shell dumpsys sensorservice restrict .cts.
129 //
130 // 2) Put SensorService in DATA_INJECTION mode with packageName .xts. If it is already in
131 // data_injection mode it is treated as a NO_OP (and packageName is NOT changed).
132 //
133 // $ adb shell dumpsys sensorservice data_injection .xts.
134 //
135 // 3) Reset sensorservice back to NORMAL mode.
136 // $ adb shell dumpsys sensorservice enable
137 };
138
Andrew Lehmer3a602572021-03-25 15:19:56 -0700139 class ProximityActiveListener : public virtual RefBase {
140 public:
141 // Note that the callback is invoked from an async thread and can interact with the
142 // SensorService directly.
143 virtual void onProximityActive(bool isActive) = 0;
144 };
145
146 static char const* getServiceName() ANDROID_API { return "sensorservice"; }
147 SensorService() ANDROID_API;
148
Peng Xueb4d6282015-12-10 18:02:41 -0800149 void cleanupConnection(SensorEventConnection* connection);
Peng Xue36e3472016-11-03 11:57:10 -0700150 void cleanupConnection(SensorDirectConnection* c);
Peng Xueb4d6282015-12-10 18:02:41 -0800151
Andrew Lehmer3a602572021-03-25 15:19:56 -0700152 // Call with mLock held.
Chris Kuiperdf11ff22021-10-12 16:30:01 -0700153 void checkAndReportProxStateChangeLocked();
154 void notifyProximityStateLocked(const bool isActive,
155 const std::vector<sp<ProximityActiveListener>>& listeners);
Andrew Lehmer3a602572021-03-25 15:19:56 -0700156
Peng Xueb4d6282015-12-10 18:02:41 -0800157 status_t enable(const sp<SensorEventConnection>& connection, int handle,
158 nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
159 const String16& opPackageName);
160
161 status_t disable(const sp<SensorEventConnection>& connection, int handle);
162
163 status_t setEventRate(const sp<SensorEventConnection>& connection, int handle, nsecs_t ns,
164 const String16& opPackageName);
165
166 status_t flushSensor(const sp<SensorEventConnection>& connection,
167 const String16& opPackageName);
168
Andrew Lehmer3a602572021-03-25 15:19:56 -0700169 status_t addProximityActiveListener(const sp<ProximityActiveListener>& callback) ANDROID_API;
170 status_t removeProximityActiveListener(const sp<ProximityActiveListener>& callback) ANDROID_API;
171
Anh Phamaf91a912021-02-10 14:10:53 +0100172 // Returns true if a sensor should be throttled according to our rate-throttling rules.
173 static bool isSensorInCappedSet(int sensorType);
Svet Ganove752a5c2018-01-15 17:14:20 -0800174
175 virtual status_t shellCommand(int in, int out, int err, Vector<String16>& args);
176
Peng Xueb4d6282015-12-10 18:02:41 -0800177private:
Mathias Agopianb6df7d02013-05-09 14:53:35 -0700178 friend class BinderService<SensorService>;
Mathias Agopianfc328812010-07-14 23:41:37 -0700179
Peng Xueb4d6282015-12-10 18:02:41 -0800180 // nested class/struct for internal use
Brian Duddie967ce172019-06-10 11:08:27 -0700181 class ConnectionSafeAutolock;
182 class SensorConnectionHolder;
Peng Xueb4d6282015-12-10 18:02:41 -0800183 class SensorEventAckReceiver;
Brian Duddie967ce172019-06-10 11:08:27 -0700184 class SensorRecord;
Peng Xu51224682017-03-10 16:57:27 -0800185 class SensorRegistrationInfo;
Peng Xueb4d6282015-12-10 18:02:41 -0800186
Brian Duddie967ce172019-06-10 11:08:27 -0700187 // Promoting a SensorEventConnection or SensorDirectConnection from wp to sp must be done with
188 // mLock held, but destroying that sp must be done unlocked to avoid a race condition that
189 // causes a deadlock (remote dies while we hold a local sp, then our decStrong() call invokes
190 // the dtor -> cleanupConnection() tries to re-lock the mutex). This class ensures safe usage
191 // by wrapping a Mutex::Autolock on SensorService's mLock, plus vectors that hold promoted sp<>
192 // references until the lock is released, when they are safely destroyed.
193 // All read accesses to the connection lists in mConnectionHolder must be done via this class.
194 class ConnectionSafeAutolock final {
195 public:
196 // Returns a list of non-null promoted connection references
197 const std::vector<sp<SensorEventConnection>>& getActiveConnections();
198 const std::vector<sp<SensorDirectConnection>>& getDirectConnections();
199
200 private:
201 // Constructed via SensorConnectionHolder::lock()
202 friend class SensorConnectionHolder;
203 explicit ConnectionSafeAutolock(SensorConnectionHolder& holder, Mutex& mutex);
204 DISALLOW_IMPLICIT_CONSTRUCTORS(ConnectionSafeAutolock);
205
206 // NOTE: Order of these members is important, as the destructor for non-static members
207 // get invoked in the reverse order of their declaration. Here we are relying on the
208 // Autolock to be destroyed *before* the vectors, so the sp<> objects are destroyed without
209 // the lock held, which avoids the deadlock.
210 SensorConnectionHolder& mConnectionHolder;
211 std::vector<std::vector<sp<SensorEventConnection>>> mReferencedActiveConnections;
212 std::vector<std::vector<sp<SensorDirectConnection>>> mReferencedDirectConnections;
213 Mutex::Autolock mAutolock;
214
215 template<typename ConnectionType>
216 const std::vector<sp<ConnectionType>>& getConnectionsHelper(
217 const SortedVector<wp<ConnectionType>>& connectionList,
218 std::vector<std::vector<sp<ConnectionType>>>* referenceHolder);
219 };
220
221 // Encapsulates the collection of active SensorEventConection and SensorDirectConnection
222 // references. Write access is done through this class with mLock held, but all read access
223 // must be routed through ConnectionSafeAutolock.
224 class SensorConnectionHolder {
225 public:
226 void addEventConnectionIfNotPresent(const sp<SensorEventConnection>& connection);
227 void removeEventConnection(const wp<SensorEventConnection>& connection);
228
229 void addDirectConnection(const sp<SensorDirectConnection>& connection);
230 void removeDirectConnection(const wp<SensorDirectConnection>& connection);
231
232 // Pass in the mutex that protects this connection holder; acquires the lock and returns an
233 // object that can be used to safely read the lists of connections
234 ConnectionSafeAutolock lock(Mutex& mutex);
235
236 private:
237 friend class ConnectionSafeAutolock;
238 SortedVector< wp<SensorEventConnection> > mActiveConnections;
239 SortedVector< wp<SensorDirectConnection> > mDirectConnections;
240 };
241
Svet Ganove752a5c2018-01-15 17:14:20 -0800242 // If accessing a sensor we need to make sure the UID has access to it. If
243 // the app UID is idle then it cannot access sensors and gets no trigger
244 // events, no on-change events, flush event behavior does not change, and
245 // recurring events are the same as the first one delivered in idle state
246 // emulating no sensor change. As soon as the app UID transitions to an
247 // active state we will start reporting events as usual and vise versa. This
248 // approach transparently handles observing sensors while the app UID transitions
249 // between idle/active state avoiding to get stuck in a state receiving sensor
250 // data while idle or not receiving sensor data while active.
251 class UidPolicy : public BnUidObserver {
252 public:
253 explicit UidPolicy(wp<SensorService> service)
254 : mService(service) {}
255 void registerSelf();
256 void unregisterSelf();
257
258 bool isUidActive(uid_t uid);
259
260 void onUidGone(uid_t uid, bool disabled);
261 void onUidActive(uid_t uid);
262 void onUidIdle(uid_t uid, bool disabled);
Eric Laurent05595892018-10-18 14:56:24 -0700263 void onUidStateChanged(uid_t uid __unused, int32_t procState __unused,
Hui Yuee03b782019-08-22 14:48:40 -0700264 int64_t procStateSeq __unused, int32_t capability __unused) {}
Svet Ganove752a5c2018-01-15 17:14:20 -0800265
266 void addOverrideUid(uid_t uid, bool active);
267 void removeOverrideUid(uid_t uid);
268 private:
269 bool isUidActiveLocked(uid_t uid);
270 void updateOverrideUid(uid_t uid, bool active, bool insert);
271
272 Mutex mUidLock;
273 wp<SensorService> mService;
274 std::unordered_set<uid_t> mActiveUids;
275 std::unordered_map<uid_t, bool> mOverrideUids;
276 };
277
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700278 bool isUidActive(uid_t uid);
279
Michael Groover5e1f60b2018-12-04 22:34:29 -0800280 // Sensor privacy allows a user to disable access to all sensors on the device. When
281 // enabled sensor privacy will prevent all apps, including active apps, from accessing
282 // sensors, they will not receive trigger nor on-change events, flush event behavior
283 // does not change, and recurring events are the same as the first one delivered when
284 // sensor privacy was enabled. All sensor direct connections will be stopped as well
285 // and new direct connections will not be allowed while sensor privacy is enabled.
286 // Once sensor privacy is disabled access to sensors will be restored for active
287 // apps, previously stopped direct connections will be restarted, and new direct
288 // connections will be allowed again.
289 class SensorPrivacyPolicy : public hardware::BnSensorPrivacyListener {
290 public:
Greg Kaiser17067592021-02-17 22:05:25 -0800291 explicit SensorPrivacyPolicy(wp<SensorService> service)
292 : mService(service), mIsIndividualMic(false), mUserId(0) {}
Michael Groover5e1f60b2018-12-04 22:34:29 -0800293 void registerSelf();
294 void unregisterSelf();
295
Anh Pham5198c992021-02-10 14:15:30 +0100296 status_t registerSelfForIndividual(int userId);
297
Michael Groover5e1f60b2018-12-04 22:34:29 -0800298 bool isSensorPrivacyEnabled();
299
300 binder::Status onSensorPrivacyChanged(bool enabled);
301
302 private:
303 wp<SensorService> mService;
Anh Pham5198c992021-02-10 14:15:30 +0100304 Mutex mSensorPrivacyLock;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800305 std::atomic_bool mSensorPrivacyEnabled;
Anh Pham5198c992021-02-10 14:15:30 +0100306 bool mIsIndividualMic;
307 userid_t mUserId;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800308 };
309
Anh Phamb04658b2021-03-22 18:17:17 +0100310 // A class automatically clearing and restoring binder caller identity inside
311 // a code block (scoped variable).
312 // Declare one systematically before calling SensorPrivacyManager methods so that they are
313 // executed with the same level of privilege as the SensorService process.
314 class AutoCallerClear {
315 public:
316 AutoCallerClear() :
317 mToken(IPCThreadState::self()->clearCallingIdentity()) {}
318 ~AutoCallerClear() {
319 IPCThreadState::self()->restoreCallingIdentity(mToken);
320 }
321
322 private:
323 const int64_t mToken;
324 };
325
Mathias Agopianb6df7d02013-05-09 14:53:35 -0700326 static const char* WAKE_LOCK_NAME;
Mathias Agopianfc328812010-07-14 23:41:37 -0700327 virtual ~SensorService();
328
329 virtual void onFirstRef();
330
331 // Thread interface
332 virtual bool threadLoop();
333
334 // ISensorServer interface
Svetoslavb412f6e2015-04-29 16:50:41 -0700335 virtual Vector<Sensor> getSensorList(const String16& opPackageName);
Peng Xu2576cb62016-01-20 00:22:09 -0800336 virtual Vector<Sensor> getDynamicSensorList(const String16& opPackageName);
Peng Xueb4d6282015-12-10 18:02:41 -0800337 virtual sp<ISensorEventConnection> createSensorEventConnection(
338 const String8& packageName,
Arthur Ishiguro340882c2021-02-18 15:17:44 -0800339 int requestedMode, const String16& opPackageName, const String16& attributionTag);
Aravind Akella5c538052015-06-29 12:37:48 -0700340 virtual int isDataInjectionEnabled();
Peng Xue36e3472016-11-03 11:57:10 -0700341 virtual sp<ISensorEventConnection> createSensorDirectConnection(const String16& opPackageName,
342 uint32_t size, int32_t type, int32_t format, const native_handle *resource);
Peng Xudd5c5cb2017-03-16 17:39:43 -0700343 virtual int setOperationParameter(
Alexey Polyudov88711e82017-05-23 19:54:04 -0700344 int32_t handle, int32_t type, const Vector<float> &floats, const Vector<int32_t> &ints);
Mathias Agopianfc328812010-07-14 23:41:37 -0700345 virtual status_t dump(int fd, const Vector<String16>& args);
Andrew Lehmer3a602572021-03-25 15:19:56 -0700346
Mike Ma24743862020-01-29 00:36:55 -0800347 status_t dumpProtoLocked(int fd, ConnectionSafeAutolock* connLock) const;
Mathias Agopianf001c922010-11-11 17:58:51 -0800348 String8 getSensorName(int handle) const;
Arthur Ishiguro883748c2020-10-28 13:18:02 -0700349 String8 getSensorStringType(int handle) const;
Aravind Akellab4099e72013-10-15 15:43:10 -0700350 bool isVirtualSensor(int handle) const;
Peng Xu755c4512016-04-07 23:15:14 -0700351 sp<SensorInterface> getSensorInterfaceFromHandle(int handle) const;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800352 bool isWakeUpSensor(int type) const;
Aravind Akella0ec20662014-09-14 17:29:48 -0700353 void recordLastValueLocked(sensors_event_t const* buffer, size_t count);
Mathias Agopianf001c922010-11-11 17:58:51 -0800354 static void sortEventBuffer(sensors_event_t* buffer, size_t count);
Peng Xu0cc8f802016-04-05 23:46:03 -0700355 const Sensor& registerSensor(SensorInterface* sensor,
356 bool isDebug = false, bool isVirtual = false);
357 const Sensor& registerVirtualSensor(SensorInterface* sensor, bool isDebug = false);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800358 const Sensor& registerDynamicSensorLocked(SensorInterface* sensor, bool isDebug = false);
359 bool unregisterDynamicSensorLocked(int handle);
Peng Xueb4d6282015-12-10 18:02:41 -0800360 status_t cleanupWithoutDisable(const sp<SensorEventConnection>& connection, int handle);
361 status_t cleanupWithoutDisableLocked(const sp<SensorEventConnection>& connection, int handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800362 void cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Mathias Agopianb6df7d02013-05-09 14:53:35 -0700363 sensors_event_t const* buffer, const int count);
Svetoslavb412f6e2015-04-29 16:50:41 -0700364 static bool canAccessSensor(const Sensor& sensor, const char* operation,
365 const String16& opPackageName);
Brian Stack793f4642019-04-18 17:21:34 -0700366 static bool hasPermissionForSensor(const Sensor& sensor);
367 static int getTargetSdkVersion(const String16& opPackageName);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800368 // SensorService acquires a partial wakelock for delivering events from wake up sensors. This
369 // method checks whether all the events from these wake up sensors have been delivered to the
370 // corresponding applications, if yes the wakelock is released.
371 void checkWakeLockState();
Brian Duddie967ce172019-06-10 11:08:27 -0700372 void checkWakeLockStateLocked(ConnectionSafeAutolock* connLock);
Aravind Akellab4373ac2014-10-29 17:55:20 -0700373 bool isWakeLockAcquired();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800374 bool isWakeUpSensorEvent(const sensors_event_t& event) const;
Aravind Akella56ae4262014-07-10 16:01:10 -0700375
376 sp<Looper> getLooper() const;
377
Aravind Akellab4373ac2014-10-29 17:55:20 -0700378 // Reset mWakeLockRefCounts for all SensorEventConnections to zero. This may happen if
379 // SensorService did not receive any acknowledgements from apps which have registered for
380 // wake_up sensors.
381 void resetAllWakeLockRefCounts();
382
Peng Xueb4d6282015-12-10 18:02:41 -0800383 // Acquire or release wake_lock. If wake_lock is acquired, set the timeout in the looper to 5
384 // seconds and wake the looper.
Aravind Akellab4373ac2014-10-29 17:55:20 -0700385 void setWakeLockAcquiredLocked(bool acquire);
386
387 // Send events from the event cache for this particular connection.
388 void sendEventsFromCache(const sp<SensorEventConnection>& connection);
389
Aravind Akella4949c502015-02-11 15:54:35 -0800390 // If SensorService is operating in RESTRICTED mode, only select whitelisted packages are
391 // allowed to register for or call flush on sensors. Typically only cts test packages are
392 // allowed.
393 bool isWhiteListedPackage(const String8& packageName);
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700394
395 // Returns true if a connection with the specified opPackageName has no access to sensors
396 // in the RESTRICTED mode (i.e. the service is in RESTRICTED mode, and the package is not
397 // whitelisted). mLock must be held to invoke this method.
398 bool isOperationRestrictedLocked(const String16& opPackageName);
Aravind Akella4949c502015-02-11 15:54:35 -0800399
Anh Phamaf91a912021-02-10 14:10:53 +0100400 status_t adjustSamplingPeriodBasedOnMicAndPermission(nsecs_t* requestedPeriodNs,
401 const String16& opPackageName);
402 status_t adjustRateLevelBasedOnMicAndPermission(int* requestedRateLevel,
403 const String16& opPackageName);
404 bool isRateCappedBasedOnPermission(const String16& opPackageName);
405 bool isPackageDebuggable(const String16& opPackageName);
406
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700407 // Reset the state of SensorService to NORMAL mode.
408 status_t resetToNormalMode();
409 status_t resetToNormalModeLocked();
410
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700411 // Transforms the UUIDs for all the sensors into proper IDs.
412 void makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const;
413 // Gets the appropriate ID from the given UUID.
414 int32_t getIdFromUuid(const Sensor::uuid_t &uuid) const;
415 // Either read from storage or create a new one.
416 static bool initializeHmacKey();
417
Peng Xu98d30f62016-08-01 18:12:11 -0700418 // Enable SCHED_FIFO priority for thread
419 void enableSchedFifoMode();
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700420
Svet Ganove752a5c2018-01-15 17:14:20 -0800421 // Sets whether the given UID can get sensor data
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700422 void onUidStateChanged(uid_t uid, UidState state);
Svet Ganove752a5c2018-01-15 17:14:20 -0800423
Arthur Ishiguroe3ed3d22020-04-13 10:29:44 -0700424 // Returns true if a connection with the given uid and opPackageName
425 // currently has access to sensors.
426 bool hasSensorAccess(uid_t uid, const String16& opPackageName);
427 // Same as hasSensorAccess but with mLock held.
428 bool hasSensorAccessLocked(uid_t uid, const String16& opPackageName);
429
Svet Ganove752a5c2018-01-15 17:14:20 -0800430 // Overrides the UID state as if it is idle
431 status_t handleSetUidState(Vector<String16>& args, int err);
432 // Clears the override for the UID state
433 status_t handleResetUidState(Vector<String16>& args, int err);
434 // Gets the UID state
435 status_t handleGetUidState(Vector<String16>& args, int out, int err);
436 // Prints the shell command help
437 status_t printHelp(int out);
438
Michael Groover5e1f60b2018-12-04 22:34:29 -0800439 // temporarily stops all active direct connections and disables all sensors
440 void disableAllSensors();
Brian Duddie967ce172019-06-10 11:08:27 -0700441 void disableAllSensorsLocked(ConnectionSafeAutolock* connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800442 // restarts the previously stopped direct connections and enables all sensors
443 void enableAllSensors();
Brian Duddie967ce172019-06-10 11:08:27 -0700444 void enableAllSensorsLocked(ConnectionSafeAutolock* connLock);
Michael Groover5e1f60b2018-12-04 22:34:29 -0800445
Anh Pham5198c992021-02-10 14:15:30 +0100446 // Caps active direct connections (when the mic toggle is flipped to on)
447 void capRates(userid_t userId);
448 // Removes the capped rate on active direct connections (when the mic toggle is flipped to off)
449 void uncapRates(userid_t userId);
450
Eric Laurente3f27df2022-01-05 19:20:32 +0100451 static inline bool isAudioServerOrSystemServerUid(uid_t uid) {
452 return multiuser_get_app_id(uid) == AID_SYSTEM || uid == AID_AUDIOSERVER;
453 }
454
Greg Kaiser53ca2e02016-06-21 16:11:14 -0700455 static uint8_t sHmacGlobalKey[128];
456 static bool sHmacGlobalKeyIsValid;
457
Andrew Lehmer3a602572021-03-25 15:19:56 -0700458 static std::atomic_uint64_t curProxCallbackSeq;
459 static std::atomic_uint64_t completedCallbackSeq;
460
Brian Stack4baa5be2018-09-18 14:03:13 -0700461 SensorServiceUtil::SensorList mSensors;
Mathias Agopian50df2952010-07-19 19:09:10 -0700462 status_t mInitCheck;
Peng Xueb4d6282015-12-10 18:02:41 -0800463
Aravind Akella5466c3d2014-08-22 16:11:10 -0700464 // Socket buffersize used to initialize BitTube. This size depends on whether batching is
465 // supported or not.
Peng Xu755c4512016-04-07 23:15:14 -0700466 uint32_t mSocketBufferSize;
467 sp<Looper> mLooper;
468 sp<SensorEventAckReceiver> mAckReceiver;
Mathias Agopianfc328812010-07-14 23:41:37 -0700469
470 // protected by mLock
471 mutable Mutex mLock;
Mathias Agopianfc328812010-07-14 23:41:37 -0700472 DefaultKeyedVector<int, SensorRecord*> mActiveSensors;
Peng Xu755c4512016-04-07 23:15:14 -0700473 std::unordered_set<int> mActiveVirtualSensors;
Brian Duddie967ce172019-06-10 11:08:27 -0700474 SensorConnectionHolder mConnectionHolder;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800475 bool mWakeLockAcquired;
Aravind Akella8493b792014-09-08 15:45:47 -0700476 sensors_event_t *mSensorEventBuffer, *mSensorEventScratch;
Brian Duddie967ce172019-06-10 11:08:27 -0700477 // WARNING: these SensorEventConnection instances must not be promoted to sp, except via
478 // modification to add support for them in ConnectionSafeAutolock
Peng Xuded526e2016-08-12 16:39:44 -0700479 wp<const SensorEventConnection> * mMapFlushEventsToConnections;
Brian Stack4baa5be2018-09-18 14:03:13 -0700480 std::unordered_map<int, SensorServiceUtil::RecentEventLogger*> mRecentEvent;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700481 Mode mCurrentOperatingMode;
Peng Xueb4d6282015-12-10 18:02:41 -0800482
Aravind Akella5c538052015-06-29 12:37:48 -0700483 // This packagaName is set when SensorService is in RESTRICTED or DATA_INJECTION mode. Only
484 // applications with this packageName are allowed to activate/deactivate or call flush on
485 // sensors. To run CTS this is can be set to ".cts." and only CTS tests will get access to
486 // sensors.
487 String8 mWhiteListedPackage;
Aravind Akella8493b792014-09-08 15:45:47 -0700488
Aravind Akella18d6d512015-06-18 14:18:28 -0700489 int mNextSensorRegIndex;
490 Vector<SensorRegistrationInfo> mLastNSensorRegistrations;
Svet Ganove752a5c2018-01-15 17:14:20 -0800491
492 sp<UidPolicy> mUidPolicy;
Michael Groover5e1f60b2018-12-04 22:34:29 -0800493 sp<SensorPrivacyPolicy> mSensorPrivacyPolicy;
Brian Stack793f4642019-04-18 17:21:34 -0700494
495 static AppOpsManager sAppOpsManager;
496 static std::map<String16, int> sPackageTargetVersion;
497 static Mutex sPackageTargetVersionLock;
Anthony Stange07eb4212020-08-28 14:50:28 -0400498 static String16 sSensorInterfaceDescriptorPrefix;
Anh Pham5198c992021-02-10 14:15:30 +0100499
500 // Map from user to SensorPrivacyPolicy
501 std::map<userid_t, sp<SensorPrivacyPolicy>> mMicSensorPrivacyPolicies;
502 // Checks if the mic sensor privacy is enabled for the uid
503 bool isMicSensorPrivacyEnabledForUid(uid_t uid);
Andrew Lehmer3a602572021-03-25 15:19:56 -0700504
Chris Kuiperdf11ff22021-10-12 16:30:01 -0700505 // Keeps track of the handles of all proximity sensors in the system.
506 std::vector<int32_t> mProxSensorHandles;
507 // The last proximity sensor active state reported to listeners.
508 bool mLastReportedProxIsActive;
509 // Listeners subscribed to receive updates on the proximity sensor active state.
Andrew Lehmer3a602572021-03-25 15:19:56 -0700510 std::vector<sp<ProximityActiveListener>> mProximityActiveListeners;
Mathias Agopianfc328812010-07-14 23:41:37 -0700511};
512
Peng Xueb4d6282015-12-10 18:02:41 -0800513} // namespace android
Mathias Agopianfc328812010-07-14 23:41:37 -0700514#endif // ANDROID_SENSOR_SERVICE_H