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 <binder/BinderService.h>
24 #include <binder/IUidObserver.h>
25 #include <cutils/compiler.h>
26 #include <sensor/ISensorServer.h>
27 #include <sensor/ISensorEventConnection.h>
28 #include <sensor/Sensor.h>
29 
30 #include <utils/AndroidThreads.h>
31 #include <utils/KeyedVector.h>
32 #include <utils/Looper.h>
33 #include <utils/SortedVector.h>
34 #include <utils/String8.h>
35 #include <utils/Vector.h>
36 #include <utils/threads.h>
37 
38 #include <stdint.h>
39 #include <sys/types.h>
40 #include <unordered_map>
41 #include <unordered_set>
42 
43 #if __clang__
44 // Clang warns about SensorEventConnection::dump hiding BBinder::dump. The cause isn't fixable
45 // without changing the API, so let's tell clang this is indeed intentional.
46 #pragma clang diagnostic ignored "-Woverloaded-virtual"
47 #endif
48 
49 // ---------------------------------------------------------------------------
50 #define IGNORE_HARDWARE_FUSION  false
51 #define DEBUG_CONNECTIONS   false
52 // Max size is 100 KB which is enough to accept a batch of about 1000 events.
53 #define MAX_SOCKET_BUFFER_SIZE_BATCHED (100 * 1024)
54 // For older HALs which don't support batching, use a smaller socket buffer size.
55 #define SOCKET_BUFFER_SIZE_NON_BATCHED (4 * 1024)
56 
57 #define SENSOR_REGISTRATIONS_BUF_SIZE 200
58 
59 namespace android {
60 // ---------------------------------------------------------------------------
61 class SensorInterface;
62 using namespace SensorServiceUtil;
63 
64 class SensorService :
65         public BinderService<SensorService>,
66         public BnSensorServer,
67         protected Thread
68 {
69     // nested class/struct for internal use
70     class SensorEventConnection;
71     class SensorDirectConnection;
72 
73 public:
74     void cleanupConnection(SensorEventConnection* connection);
75     void cleanupConnection(SensorDirectConnection* c);
76 
77     status_t enable(const sp<SensorEventConnection>& connection, int handle,
78                     nsecs_t samplingPeriodNs,  nsecs_t maxBatchReportLatencyNs, int reservedFlags,
79                     const String16& opPackageName);
80 
81     status_t disable(const sp<SensorEventConnection>& connection, int handle);
82 
83     status_t setEventRate(const sp<SensorEventConnection>& connection, int handle, nsecs_t ns,
84                           const String16& opPackageName);
85 
86     status_t flushSensor(const sp<SensorEventConnection>& connection,
87                          const String16& opPackageName);
88 
89 
90     virtual status_t shellCommand(int in, int out, int err, Vector<String16>& args);
91 
92 private:
93     friend class BinderService<SensorService>;
94 
95     // nested class/struct for internal use
96     class SensorRecord;
97     class SensorEventAckReceiver;
98     class SensorRegistrationInfo;
99 
100     // If accessing a sensor we need to make sure the UID has access to it. If
101     // the app UID is idle then it cannot access sensors and gets no trigger
102     // events, no on-change events, flush event behavior does not change, and
103     // recurring events are the same as the first one delivered in idle state
104     // emulating no sensor change. As soon as the app UID transitions to an
105     // active state we will start reporting events as usual and vise versa. This
106     // approach transparently handles observing sensors while the app UID transitions
107     // between idle/active state avoiding to get stuck in a state receiving sensor
108     // data while idle or not receiving sensor data while active.
109     class UidPolicy : public BnUidObserver {
110         public:
UidPolicy(wp<SensorService> service)111             explicit UidPolicy(wp<SensorService> service)
112                     : mService(service) {}
113             void registerSelf();
114             void unregisterSelf();
115 
116             bool isUidActive(uid_t uid);
117 
118             void onUidGone(uid_t uid, bool disabled);
119             void onUidActive(uid_t uid);
120             void onUidIdle(uid_t uid, bool disabled);
121 
122             void addOverrideUid(uid_t uid, bool active);
123             void removeOverrideUid(uid_t uid);
124         private:
125             bool isUidActiveLocked(uid_t uid);
126             void updateOverrideUid(uid_t uid, bool active, bool insert);
127 
128             Mutex mUidLock;
129             wp<SensorService> mService;
130             std::unordered_set<uid_t> mActiveUids;
131             std::unordered_map<uid_t, bool> mOverrideUids;
132     };
133 
134     enum Mode {
135        // The regular operating mode where any application can register/unregister/call flush on
136        // sensors.
137        NORMAL = 0,
138        // This mode is only used for testing purposes. Not all HALs support this mode. In this mode,
139        // the HAL ignores the sensor data provided by physical sensors and accepts the data that is
140        // injected from the SensorService as if it were the real sensor data. This mode is primarily
141        // used for testing various algorithms like vendor provided SensorFusion, Step Counter and
142        // Step Detector etc. Typically in this mode, there will be a client (a
143        // SensorEventConnection) which will be injecting sensor data into the HAL. Normal apps can
144        // unregister and register for any sensor that supports injection. Registering to sensors
145        // that do not support injection will give an error.  TODO(aakella) : Allow exactly one
146        // client to inject sensor data at a time.
147        DATA_INJECTION = 1,
148        // This mode is used only for testing sensors. Each sensor can be tested in isolation with
149        // the required sampling_rate and maxReportLatency parameters without having to think about
150        // the data rates requested by other applications. End user devices are always expected to be
151        // in NORMAL mode. When this mode is first activated, all active sensors from all connections
152        // are disabled. Calling flush() will return an error. In this mode, only the requests from
153        // selected apps whose package names are whitelisted are allowed (typically CTS apps).  Only
154        // these apps can register/unregister/call flush() on sensors. If SensorService switches to
155        // NORMAL mode again, all sensors that were previously registered to are activated with the
156        // corresponding paramaters if the application hasn't unregistered for sensors in the mean
157        // time.  NOTE: Non whitelisted app whose sensors were previously deactivated may still
158        // receive events if a whitelisted app requests data from the same sensor.
159        RESTRICTED = 2
160 
161       // State Transitions supported.
162       //     RESTRICTED   <---  NORMAL   ---> DATA_INJECTION
163       //                  --->           <---
164 
165       // Shell commands to switch modes in SensorService.
166       // 1) Put SensorService in RESTRICTED mode with packageName .cts. If it is already in
167       // restricted mode it is treated as a NO_OP (and packageName is NOT changed).
168       //
169       //     $ adb shell dumpsys sensorservice restrict .cts.
170       //
171       // 2) Put SensorService in DATA_INJECTION mode with packageName .xts. If it is already in
172       // data_injection mode it is treated as a NO_OP (and packageName is NOT changed).
173       //
174       //     $ adb shell dumpsys sensorservice data_injection .xts.
175       //
176       // 3) Reset sensorservice back to NORMAL mode.
177       //     $ adb shell dumpsys sensorservice enable
178     };
179 
180     static const char* WAKE_LOCK_NAME;
getServiceName()181     static char const* getServiceName() ANDROID_API { return "sensorservice"; }
182     SensorService() ANDROID_API;
183     virtual ~SensorService();
184 
185     virtual void onFirstRef();
186 
187     // Thread interface
188     virtual bool threadLoop();
189 
190     // ISensorServer interface
191     virtual Vector<Sensor> getSensorList(const String16& opPackageName);
192     virtual Vector<Sensor> getDynamicSensorList(const String16& opPackageName);
193     virtual sp<ISensorEventConnection> createSensorEventConnection(
194             const String8& packageName,
195             int requestedMode, const String16& opPackageName);
196     virtual int isDataInjectionEnabled();
197     virtual sp<ISensorEventConnection> createSensorDirectConnection(const String16& opPackageName,
198             uint32_t size, int32_t type, int32_t format, const native_handle *resource);
199     virtual int setOperationParameter(
200             int32_t handle, int32_t type, const Vector<float> &floats, const Vector<int32_t> &ints);
201     virtual status_t dump(int fd, const Vector<String16>& args);
202     String8 getSensorName(int handle) const;
203     bool isVirtualSensor(int handle) const;
204     sp<SensorInterface> getSensorInterfaceFromHandle(int handle) const;
205     bool isWakeUpSensor(int type) const;
206     void recordLastValueLocked(sensors_event_t const* buffer, size_t count);
207     static void sortEventBuffer(sensors_event_t* buffer, size_t count);
208     const Sensor& registerSensor(SensorInterface* sensor,
209                                  bool isDebug = false, bool isVirtual = false);
210     const Sensor& registerVirtualSensor(SensorInterface* sensor, bool isDebug = false);
211     const Sensor& registerDynamicSensorLocked(SensorInterface* sensor, bool isDebug = false);
212     bool unregisterDynamicSensorLocked(int handle);
213     status_t cleanupWithoutDisable(const sp<SensorEventConnection>& connection, int handle);
214     status_t cleanupWithoutDisableLocked(const sp<SensorEventConnection>& connection, int handle);
215     void cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
216             sensors_event_t const* buffer, const int count);
217     static bool canAccessSensor(const Sensor& sensor, const char* operation,
218             const String16& opPackageName);
219     // SensorService acquires a partial wakelock for delivering events from wake up sensors. This
220     // method checks whether all the events from these wake up sensors have been delivered to the
221     // corresponding applications, if yes the wakelock is released.
222     void checkWakeLockState();
223     void checkWakeLockStateLocked();
224     bool isWakeLockAcquired();
225     bool isWakeUpSensorEvent(const sensors_event_t& event) const;
226 
227     sp<Looper> getLooper() const;
228 
229     // Reset mWakeLockRefCounts for all SensorEventConnections to zero. This may happen if
230     // SensorService did not receive any acknowledgements from apps which have registered for
231     // wake_up sensors.
232     void resetAllWakeLockRefCounts();
233 
234     // Acquire or release wake_lock. If wake_lock is acquired, set the timeout in the looper to 5
235     // seconds and wake the looper.
236     void setWakeLockAcquiredLocked(bool acquire);
237 
238     // Send events from the event cache for this particular connection.
239     void sendEventsFromCache(const sp<SensorEventConnection>& connection);
240 
241     // Promote all weak referecences in mActiveConnections vector to strong references and add them
242     // to the output vector.
243     void populateActiveConnections( SortedVector< sp<SensorEventConnection> >* activeConnections);
244 
245     // If SensorService is operating in RESTRICTED mode, only select whitelisted packages are
246     // allowed to register for or call flush on sensors. Typically only cts test packages are
247     // allowed.
248     bool isWhiteListedPackage(const String8& packageName);
249     bool isOperationRestricted(const String16& opPackageName);
250 
251     // Reset the state of SensorService to NORMAL mode.
252     status_t resetToNormalMode();
253     status_t resetToNormalModeLocked();
254 
255     // Transforms the UUIDs for all the sensors into proper IDs.
256     void makeUuidsIntoIdsForSensorList(Vector<Sensor> &sensorList) const;
257     // Gets the appropriate ID from the given UUID.
258     int32_t getIdFromUuid(const Sensor::uuid_t &uuid) const;
259     // Either read from storage or create a new one.
260     static bool initializeHmacKey();
261 
262     // Enable SCHED_FIFO priority for thread
263     void enableSchedFifoMode();
264 
265     // Sets whether the given UID can get sensor data
266     void setSensorAccess(uid_t uid, bool hasAccess);
267 
268     // Overrides the UID state as if it is idle
269     status_t handleSetUidState(Vector<String16>& args, int err);
270     // Clears the override for the UID state
271     status_t handleResetUidState(Vector<String16>& args, int err);
272     // Gets the UID state
273     status_t handleGetUidState(Vector<String16>& args, int out, int err);
274     // Prints the shell command help
275     status_t printHelp(int out);
276 
277     static uint8_t sHmacGlobalKey[128];
278     static bool sHmacGlobalKeyIsValid;
279 
280     SensorList mSensors;
281     status_t mInitCheck;
282 
283     // Socket buffersize used to initialize BitTube. This size depends on whether batching is
284     // supported or not.
285     uint32_t mSocketBufferSize;
286     sp<Looper> mLooper;
287     sp<SensorEventAckReceiver> mAckReceiver;
288 
289     // protected by mLock
290     mutable Mutex mLock;
291     DefaultKeyedVector<int, SensorRecord*> mActiveSensors;
292     std::unordered_set<int> mActiveVirtualSensors;
293     SortedVector< wp<SensorEventConnection> > mActiveConnections;
294     bool mWakeLockAcquired;
295     sensors_event_t *mSensorEventBuffer, *mSensorEventScratch;
296     wp<const SensorEventConnection> * mMapFlushEventsToConnections;
297     std::unordered_map<int, RecentEventLogger*> mRecentEvent;
298     SortedVector< wp<SensorDirectConnection> > mDirectConnections;
299     Mode mCurrentOperatingMode;
300 
301     // This packagaName is set when SensorService is in RESTRICTED or DATA_INJECTION mode. Only
302     // applications with this packageName are allowed to activate/deactivate or call flush on
303     // sensors. To run CTS this is can be set to ".cts." and only CTS tests will get access to
304     // sensors.
305     String8 mWhiteListedPackage;
306 
307     int mNextSensorRegIndex;
308     Vector<SensorRegistrationInfo> mLastNSensorRegistrations;
309 
310     sp<UidPolicy> mUidPolicy;
311 };
312 
313 } // namespace android
314 #endif // ANDROID_SENSOR_SERVICE_H
315