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 #define LOG_TAG "Sensors"
18 
19 #include <sensor/SensorManager.h>
20 
21 #include <stdint.h>
22 #include <sys/types.h>
23 
24 #include <cutils/native_handle.h>
25 #include <utils/Errors.h>
26 #include <utils/RefBase.h>
27 #include <utils/Singleton.h>
28 
29 #include <android/companion/virtualnative/IVirtualDeviceManagerNative.h>
30 
31 #include <binder/IBinder.h>
32 #include <binder/IPermissionController.h>
33 #include <binder/IServiceManager.h>
34 
35 #include <sensor/ISensorServer.h>
36 #include <sensor/ISensorEventConnection.h>
37 #include <sensor/Sensor.h>
38 #include <sensor/SensorEventQueue.h>
39 
40 #include <com_android_hardware_libsensor_flags.h>
41 
42 // ----------------------------------------------------------------------------
43 namespace android {
44 // ----------------------------------------------------------------------------
45 
46 namespace {
47 
48 using ::android::companion::virtualnative::IVirtualDeviceManagerNative;
49 
50 static constexpr int DEVICE_ID_DEFAULT = 0;
51 
52 // Returns the deviceId of the device where this uid is observed. If the uid is present on more than
53 // one devices, return the default deviceId.
getDeviceIdForUid(uid_t uid)54 int getDeviceIdForUid(uid_t uid) {
55     sp<IBinder> binder =
56             defaultServiceManager()->checkService(String16("virtualdevice_native"));
57     if (binder != nullptr) {
58         auto vdm = interface_cast<IVirtualDeviceManagerNative>(binder);
59         std::vector<int> deviceIds;
60         vdm->getDeviceIdsForUid(uid, &deviceIds);
61         // If the UID is associated with multiple virtual devices, use the default device's
62         // sensors as we cannot disambiguate here. This effectively means that the app has
63         // activities on different devices at the same time, so it must handle the device
64         // awareness by itself.
65         if (deviceIds.size() == 1) {
66             const int deviceId = deviceIds.at(0);
67             int devicePolicy = IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT;
68             vdm->getDevicePolicy(deviceId,
69                                  IVirtualDeviceManagerNative::POLICY_TYPE_SENSORS,
70                                  &devicePolicy);
71             if (devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_CUSTOM) {
72                 return deviceId;
73             }
74         }
75     } else {
76         ALOGW("Cannot get virtualdevice_native service");
77     }
78     return DEVICE_ID_DEFAULT;
79 }
80 
81 }  // namespace
82 
83 Mutex SensorManager::sLock;
84 std::map<String16, SensorManager*> SensorManager::sPackageInstances;
85 
getInstanceForPackage(const String16 & packageName)86 SensorManager& SensorManager::getInstanceForPackage(const String16& packageName) {
87     waitForSensorService(nullptr);
88 
89     Mutex::Autolock _l(sLock);
90     SensorManager* sensorManager;
91     auto iterator = sPackageInstances.find(packageName);
92 
93     const uid_t uid = IPCThreadState::self()->getCallingUid();
94     const int deviceId = getDeviceIdForUid(uid);
95 
96     // Return the cached instance if the device association of the package has not changed.
97     if (iterator != sPackageInstances.end()) {
98         sensorManager = iterator->second;
99         if (sensorManager->mDeviceId == deviceId) {
100             return *sensorManager;
101         }
102     }
103 
104     // It is possible that the calling code has no access to the package name.
105     // In this case we will get the packages for the calling UID and pick the
106     // first one for attributing the app op. This will work correctly for
107     // runtime permissions as for legacy apps we will toggle the app op for
108     // all packages in the UID. The caveat is that the operation may be attributed
109     // to the wrong package and stats based on app ops may be slightly off.
110     String16 opPackageName = packageName;
111     if (opPackageName.size() <= 0) {
112         sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
113         if (binder != nullptr) {
114             Vector<String16> packages;
115             interface_cast<IPermissionController>(binder)->getPackagesForUid(uid, packages);
116             if (!packages.isEmpty()) {
117                 opPackageName = packages[0];
118             } else {
119                 ALOGE("No packages for calling UID");
120             }
121         } else {
122             ALOGE("Cannot get permission service");
123         }
124     }
125 
126     sensorManager = new SensorManager(opPackageName, deviceId);
127 
128     // If we had no package name, we looked it up from the UID and the sensor
129     // manager instance we created should also be mapped to the empty package
130     // name, to avoid looking up the packages for a UID and get the same result.
131     if (packageName.size() <= 0) {
132         sPackageInstances.insert(std::make_pair(String16(), sensorManager));
133     }
134 
135     // Stash the per package sensor manager.
136     sPackageInstances.insert(std::make_pair(opPackageName, sensorManager));
137 
138     return *sensorManager;
139 }
140 
removeInstanceForPackage(const String16 & packageName)141 void SensorManager::removeInstanceForPackage(const String16& packageName) {
142     Mutex::Autolock _l(sLock);
143     auto iterator = sPackageInstances.find(packageName);
144     if (iterator != sPackageInstances.end()) {
145         SensorManager* sensorManager = iterator->second;
146         delete sensorManager;
147         sPackageInstances.erase(iterator);
148     }
149 }
150 
SensorManager(const String16 & opPackageName,int deviceId)151 SensorManager::SensorManager(const String16& opPackageName, int deviceId)
152     : mSensorList(nullptr), mOpPackageName(opPackageName), mDeviceId(deviceId),
153         mDirectConnectionHandle(1) {
154     Mutex::Autolock _l(mLock);
155     assertStateLocked();
156 }
157 
~SensorManager()158 SensorManager::~SensorManager() {
159     free(mSensorList);
160     free(mDynamicSensorList);
161 }
162 
waitForSensorService(sp<ISensorServer> * server)163 status_t SensorManager::waitForSensorService(sp<ISensorServer> *server) {
164     // try for 300 seconds (60*5(getService() tries for 5 seconds)) before giving up ...
165     sp<ISensorServer> s;
166     const String16 name("sensorservice");
167     for (int i = 0; i < 60; i++) {
168         status_t err = getService(name, &s);
169         switch (err) {
170             case NAME_NOT_FOUND:
171                 sleep(1);
172                 continue;
173             case NO_ERROR:
174                 if (server != nullptr) {
175                     *server = s;
176                 }
177                 return NO_ERROR;
178             default:
179                 return err;
180         }
181     }
182     return TIMED_OUT;
183 }
184 
sensorManagerDied()185 void SensorManager::sensorManagerDied() {
186     Mutex::Autolock _l(mLock);
187     mSensorServer.clear();
188     free(mSensorList);
189     mSensorList = nullptr;
190     mSensors.clear();
191     free(mDynamicSensorList);
192     mDynamicSensorList = nullptr;
193     mDynamicSensors.clear();
194 }
195 
assertStateLocked()196 status_t SensorManager::assertStateLocked() {
197 #if COM_ANDROID_HARDWARE_LIBSENSOR_FLAGS(SENSORMANAGER_PING_BINDER)
198     if (mSensorServer == nullptr) {
199 #else
200     bool initSensorManager = false;
201     if (mSensorServer == nullptr) {
202         initSensorManager = true;
203     } else {
204         // Ping binder to check if sensorservice is alive.
205         status_t err = IInterface::asBinder(mSensorServer)->pingBinder();
206         if (err != NO_ERROR) {
207             initSensorManager = true;
208         }
209     }
210     if (initSensorManager) {
211 #endif
212         waitForSensorService(&mSensorServer);
213         LOG_ALWAYS_FATAL_IF(mSensorServer == nullptr, "getService(SensorService) NULL");
214 
215         class DeathObserver : public IBinder::DeathRecipient {
216             SensorManager& mSensorManager;
217             virtual void binderDied(const wp<IBinder>& who) {
218                 ALOGW("sensorservice died [%p]", static_cast<void*>(who.unsafe_get()));
219                 mSensorManager.sensorManagerDied();
220             }
221         public:
222             explicit DeathObserver(SensorManager& mgr) : mSensorManager(mgr) { }
223         };
224 
225         mDeathObserver = new DeathObserver(*const_cast<SensorManager *>(this));
226         IInterface::asBinder(mSensorServer)->linkToDeath(mDeathObserver);
227 
228         if (mDeviceId == DEVICE_ID_DEFAULT) {
229             mSensors = mSensorServer->getSensorList(mOpPackageName);
230         } else {
231             mSensors = mSensorServer->getRuntimeSensorList(mOpPackageName, mDeviceId);
232         }
233 
234         size_t count = mSensors.size();
235         // If count is 0, mSensorList will be non-null. This is old
236         // existing behavior and callers expect this.
237         mSensorList =
238                 static_cast<Sensor const**>(malloc(count * sizeof(Sensor*)));
239         LOG_ALWAYS_FATAL_IF(mSensorList == nullptr, "mSensorList NULL");
240 
241         for (size_t i=0 ; i<count ; i++) {
242             mSensorList[i] = mSensors.array() + i;
243         }
244     }
245 
246     return NO_ERROR;
247 }
248 
249 ssize_t SensorManager::getSensorList(Sensor const* const** list) {
250     Mutex::Autolock _l(mLock);
251     status_t err = assertStateLocked();
252     if (err < 0) {
253         return static_cast<ssize_t>(err);
254     }
255     *list = mSensorList;
256     return static_cast<ssize_t>(mSensors.size());
257 }
258 
259 ssize_t SensorManager::getDefaultDeviceSensorList(Vector<Sensor> & list) {
260     Mutex::Autolock _l(mLock);
261     status_t err = assertStateLocked();
262     if (err < 0) {
263         return static_cast<ssize_t>(err);
264     }
265 
266     if (mDeviceId == DEVICE_ID_DEFAULT) {
267         list = mSensors;
268     } else {
269         list = mSensorServer->getSensorList(mOpPackageName);
270     }
271 
272     return static_cast<ssize_t>(list.size());
273 }
274 
275 ssize_t SensorManager::getDynamicSensorList(Vector<Sensor> & dynamicSensors) {
276     Mutex::Autolock _l(mLock);
277     status_t err = assertStateLocked();
278     if (err < 0) {
279         return static_cast<ssize_t>(err);
280     }
281 
282     dynamicSensors = mSensorServer->getDynamicSensorList(mOpPackageName);
283     size_t count = dynamicSensors.size();
284 
285     return static_cast<ssize_t>(count);
286 }
287 
288 ssize_t SensorManager::getRuntimeSensorList(int deviceId, Vector<Sensor>& runtimeSensors) {
289     Mutex::Autolock _l(mLock);
290     status_t err = assertStateLocked();
291     if (err < 0) {
292         return static_cast<ssize_t>(err);
293     }
294 
295     runtimeSensors = mSensorServer->getRuntimeSensorList(mOpPackageName, deviceId);
296     size_t count = runtimeSensors.size();
297 
298     return static_cast<ssize_t>(count);
299 }
300 
301 ssize_t SensorManager::getDynamicSensorList(Sensor const* const** list) {
302     Mutex::Autolock _l(mLock);
303     status_t err = assertStateLocked();
304     if (err < 0) {
305         return static_cast<ssize_t>(err);
306     }
307 
308     free(mDynamicSensorList);
309     mDynamicSensorList = nullptr;
310     mDynamicSensors = mSensorServer->getDynamicSensorList(mOpPackageName);
311     size_t dynamicCount = mDynamicSensors.size();
312     if (dynamicCount > 0) {
313         mDynamicSensorList = static_cast<Sensor const**>(
314                 malloc(dynamicCount * sizeof(Sensor*)));
315         if (mDynamicSensorList == nullptr) {
316           ALOGE("Failed to allocate dynamic sensor list for %zu sensors.",
317                 dynamicCount);
318           return static_cast<ssize_t>(NO_MEMORY);
319         }
320 
321         for (size_t i = 0; i < dynamicCount; i++) {
322             mDynamicSensorList[i] = mDynamicSensors.array() + i;
323         }
324     }
325 
326     *list = mDynamicSensorList;
327     return static_cast<ssize_t>(mDynamicSensors.size());
328 }
329 
330 Sensor const* SensorManager::getDefaultSensor(int type)
331 {
332     Mutex::Autolock _l(mLock);
333     if (assertStateLocked() == NO_ERROR) {
334         bool wakeUpSensor = false;
335         // For the following sensor types, return a wake-up sensor. These types are by default
336         // defined as wake-up sensors. For the rest of the sensor types defined in sensors.h return
337         // a non_wake-up version.
338         if (type == SENSOR_TYPE_PROXIMITY || type == SENSOR_TYPE_SIGNIFICANT_MOTION ||
339             type == SENSOR_TYPE_TILT_DETECTOR || type == SENSOR_TYPE_WAKE_GESTURE ||
340             type == SENSOR_TYPE_GLANCE_GESTURE || type == SENSOR_TYPE_PICK_UP_GESTURE ||
341             type == SENSOR_TYPE_WRIST_TILT_GESTURE ||
342             type == SENSOR_TYPE_LOW_LATENCY_OFFBODY_DETECT || type == SENSOR_TYPE_HINGE_ANGLE) {
343             wakeUpSensor = true;
344         }
345         // For now we just return the first sensor of that type we find.
346         // in the future it will make sense to let the SensorService make
347         // that decision.
348         for (size_t i=0 ; i<mSensors.size() ; i++) {
349             if (mSensorList[i]->getType() == type &&
350                 mSensorList[i]->isWakeUpSensor() == wakeUpSensor) {
351                 return mSensorList[i];
352             }
353         }
354     }
355     return nullptr;
356 }
357 
358 sp<SensorEventQueue> SensorManager::createEventQueue(
359     String8 packageName, int mode, String16 attributionTag) {
360     sp<SensorEventQueue> queue;
361 
362     Mutex::Autolock _l(mLock);
363     while (assertStateLocked() == NO_ERROR) {
364         sp<ISensorEventConnection> connection = mSensorServer->createSensorEventConnection(
365             packageName, mode, mOpPackageName, attributionTag);
366         if (connection == nullptr) {
367             // SensorService just died or the app doesn't have required permissions.
368             ALOGE("createEventQueue: connection is NULL.");
369             return nullptr;
370         }
371         queue = new SensorEventQueue(connection);
372         break;
373     }
374     return queue;
375 }
376 
377 bool SensorManager::isDataInjectionEnabled() {
378     Mutex::Autolock _l(mLock);
379     if (assertStateLocked() == NO_ERROR) {
380         return mSensorServer->isDataInjectionEnabled();
381     }
382     return false;
383 }
384 
385 bool SensorManager::isReplayDataInjectionEnabled() {
386     Mutex::Autolock _l(mLock);
387     if (assertStateLocked() == NO_ERROR) {
388         return mSensorServer->isReplayDataInjectionEnabled();
389     }
390     return false;
391 }
392 
393 bool SensorManager::isHalBypassReplayDataInjectionEnabled() {
394     Mutex::Autolock _l(mLock);
395     if (assertStateLocked() == NO_ERROR) {
396         return mSensorServer->isHalBypassReplayDataInjectionEnabled();
397     }
398     return false;
399 }
400 
401 int SensorManager::createDirectChannel(
402         size_t size, int channelType, const native_handle_t *resourceHandle) {
403     static constexpr int DEFAULT_DEVICE_ID = 0;
404     return createDirectChannel(DEFAULT_DEVICE_ID, size, channelType, resourceHandle);
405 }
406 
407 int SensorManager::createDirectChannel(
408         int deviceId, size_t size, int channelType, const native_handle_t *resourceHandle) {
409     Mutex::Autolock _l(mLock);
410     if (assertStateLocked() != NO_ERROR) {
411         return NO_INIT;
412     }
413 
414     if (channelType != SENSOR_DIRECT_MEM_TYPE_ASHMEM
415             && channelType != SENSOR_DIRECT_MEM_TYPE_GRALLOC) {
416         ALOGE("Bad channel shared memory type %d", channelType);
417         return BAD_VALUE;
418     }
419 
420     sp<ISensorEventConnection> conn =
421               mSensorServer->createSensorDirectConnection(mOpPackageName, deviceId,
422                   static_cast<uint32_t>(size),
423                   static_cast<int32_t>(channelType),
424                   SENSOR_DIRECT_FMT_SENSORS_EVENT, resourceHandle);
425     if (conn == nullptr) {
426         return NO_MEMORY;
427     }
428 
429     int nativeHandle = mDirectConnectionHandle++;
430     mDirectConnection.emplace(nativeHandle, conn);
431     return nativeHandle;
432 }
433 
434 void SensorManager::destroyDirectChannel(int channelNativeHandle) {
435     Mutex::Autolock _l(mLock);
436     if (assertStateLocked() == NO_ERROR) {
437         mDirectConnection.erase(channelNativeHandle);
438     }
439 }
440 
441 int SensorManager::configureDirectChannel(int channelNativeHandle, int sensorHandle, int rateLevel) {
442     Mutex::Autolock _l(mLock);
443     if (assertStateLocked() != NO_ERROR) {
444         return NO_INIT;
445     }
446 
447     auto i = mDirectConnection.find(channelNativeHandle);
448     if (i == mDirectConnection.end()) {
449         ALOGE("Cannot find the handle in client direct connection table");
450         return BAD_VALUE;
451     }
452 
453     int ret;
454     ret = i->second->configureChannel(sensorHandle, rateLevel);
455     ALOGE_IF(ret < 0, "SensorManager::configureChannel (%d, %d) returns %d",
456             static_cast<int>(sensorHandle), static_cast<int>(rateLevel),
457             static_cast<int>(ret));
458     return ret;
459 }
460 
461 int SensorManager::setOperationParameter(
462         int handle, int type,
463         const Vector<float> &floats, const Vector<int32_t> &ints) {
464     Mutex::Autolock _l(mLock);
465     if (assertStateLocked() != NO_ERROR) {
466         return NO_INIT;
467     }
468     return mSensorServer->setOperationParameter(handle, type, floats, ints);
469 }
470 
471 // ----------------------------------------------------------------------------
472 }; // namespace android
473