1 /*
2  * Copyright (C) 2008 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 "CameraService"
18 #define ATRACE_TAG ATRACE_TAG_CAMERA
19 //#define LOG_NDEBUG 0
20 
21 #include <algorithm>
22 #include <climits>
23 #include <stdio.h>
24 #include <cstring>
25 #include <ctime>
26 #include <string>
27 #include <sys/types.h>
28 #include <inttypes.h>
29 #include <pthread.h>
30 
31 #include <android/hardware/ICamera.h>
32 #include <android/hardware/ICameraClient.h>
33 
34 #include <android-base/macros.h>
35 #include <android-base/parseint.h>
36 #include <android-base/stringprintf.h>
37 #include <binder/ActivityManager.h>
38 #include <binder/AppOpsManager.h>
39 #include <binder/IPCThreadState.h>
40 #include <binder/IServiceManager.h>
41 #include <binder/MemoryBase.h>
42 #include <binder/MemoryHeapBase.h>
43 #include <binder/PermissionController.h>
44 #include <binder/ProcessInfoService.h>
45 #include <binder/IResultReceiver.h>
46 #include <binderthreadstate/CallerUtils.h>
47 #include <cutils/atomic.h>
48 #include <cutils/properties.h>
49 #include <cutils/misc.h>
50 #include <gui/Surface.h>
51 #include <hardware/hardware.h>
52 #include "hidl/HidlCameraService.h"
53 #include <hidl/HidlTransportSupport.h>
54 #include <hwbinder/IPCThreadState.h>
55 #include <memunreachable/memunreachable.h>
56 #include <media/AudioSystem.h>
57 #include <media/IMediaHTTPService.h>
58 #include <media/mediaplayer.h>
59 #include <mediautils/BatteryNotifier.h>
60 #include <utils/Errors.h>
61 #include <utils/Log.h>
62 #include <utils/String16.h>
63 #include <utils/SystemClock.h>
64 #include <utils/Trace.h>
65 #include <private/android_filesystem_config.h>
66 #include <system/camera_vendor_tags.h>
67 #include <system/camera_metadata.h>
68 
69 #include <system/camera.h>
70 
71 #include "CameraService.h"
72 #include "api1/CameraClient.h"
73 #include "api1/Camera2Client.h"
74 #include "api2/CameraDeviceClient.h"
75 #include "utils/CameraTraces.h"
76 #include "utils/TagMonitor.h"
77 #include "utils/CameraThreadState.h"
78 
79 namespace {
80     const char* kPermissionServiceName = "permission";
81 }; // namespace anonymous
82 
83 namespace android {
84 
85 using base::StringPrintf;
86 using binder::Status;
87 using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
88 using hardware::ICamera;
89 using hardware::ICameraClient;
90 using hardware::ICameraServiceProxy;
91 using hardware::ICameraServiceListener;
92 using hardware::camera::common::V1_0::CameraDeviceStatus;
93 using hardware::camera::common::V1_0::TorchModeStatus;
94 
95 // ----------------------------------------------------------------------------
96 // Logging support -- this is for debugging only
97 // Use "adb shell dumpsys media.camera -v 1" to change it.
98 volatile int32_t gLogLevel = 0;
99 
100 #define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
101 #define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
102 
setLogLevel(int level)103 static void setLogLevel(int level) {
104     android_atomic_write(level, &gLogLevel);
105 }
106 
107 // Convenience methods for constructing binder::Status objects for error returns
108 
109 #define STATUS_ERROR(errorCode, errorString) \
110     binder::Status::fromServiceSpecificError(errorCode, \
111             String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
112 
113 #define STATUS_ERROR_FMT(errorCode, errorString, ...) \
114     binder::Status::fromServiceSpecificError(errorCode, \
115             String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
116                     __VA_ARGS__))
117 
118 // ----------------------------------------------------------------------------
119 
120 static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
121 static const String16 sCameraOpenCloseListenerPermission(
122         "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
123 
124 // Matches with PERCEPTIBLE_APP_ADJ in ProcessList.java
125 static constexpr int32_t kVendorClientScore = 200;
126 // Matches with PROCESS_STATE_PERSISTENT_UI in ActivityManager.java
127 static constexpr int32_t kVendorClientState = 1;
128 
129 Mutex CameraService::sProxyMutex;
130 sp<hardware::ICameraServiceProxy> CameraService::sCameraServiceProxy;
131 
CameraService()132 CameraService::CameraService() :
133         mEventLog(DEFAULT_EVENT_LOG_LENGTH),
134         mNumberOfCameras(0),
135         mSoundRef(0), mInitialized(false) {
136     ALOGI("CameraService started (pid=%d)", getpid());
137     mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
138 }
139 
onFirstRef()140 void CameraService::onFirstRef()
141 {
142     ALOGI("CameraService process starting");
143 
144     BnCameraService::onFirstRef();
145 
146     // Update battery life tracking if service is restarting
147     BatteryNotifier& notifier(BatteryNotifier::getInstance());
148     notifier.noteResetCamera();
149     notifier.noteResetFlashlight();
150 
151     status_t res = INVALID_OPERATION;
152 
153     res = enumerateProviders();
154     if (res == OK) {
155         mInitialized = true;
156     }
157 
158     mUidPolicy = new UidPolicy(this);
159     mUidPolicy->registerSelf();
160     mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
161     mSensorPrivacyPolicy->registerSelf();
162     sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
163     if (hcs->registerAsService() != android::OK) {
164         ALOGE("%s: Failed to register default android.frameworks.cameraservice.service@1.0",
165               __FUNCTION__);
166     }
167 
168     // This needs to be last call in this function, so that it's as close to
169     // ServiceManager::addService() as possible.
170     CameraService::pingCameraServiceProxy();
171     ALOGI("CameraService pinged cameraservice proxy");
172 }
173 
enumerateProviders()174 status_t CameraService::enumerateProviders() {
175     status_t res;
176 
177     std::vector<std::string> deviceIds;
178     {
179         Mutex::Autolock l(mServiceLock);
180 
181         if (nullptr == mCameraProviderManager.get()) {
182             mCameraProviderManager = new CameraProviderManager();
183             res = mCameraProviderManager->initialize(this);
184             if (res != OK) {
185                 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
186                         __FUNCTION__, strerror(-res), res);
187                 return res;
188             }
189         }
190 
191 
192         // Setup vendor tags before we call get_camera_info the first time
193         // because HAL might need to setup static vendor keys in get_camera_info
194         // TODO: maybe put this into CameraProviderManager::initialize()?
195         mCameraProviderManager->setUpVendorTags();
196 
197         if (nullptr == mFlashlight.get()) {
198             mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
199         }
200 
201         res = mFlashlight->findFlashUnits();
202         if (res != OK) {
203             ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
204         }
205 
206         deviceIds = mCameraProviderManager->getCameraDeviceIds();
207     }
208 
209 
210     for (auto& cameraId : deviceIds) {
211         String8 id8 = String8(cameraId.c_str());
212         if (getCameraState(id8) == nullptr) {
213             onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
214         }
215     }
216 
217     return OK;
218 }
219 
getCameraServiceProxy()220 sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
221 #ifndef __BRILLO__
222     Mutex::Autolock al(sProxyMutex);
223     if (sCameraServiceProxy == nullptr) {
224         sp<IServiceManager> sm = defaultServiceManager();
225         // Use checkService because cameraserver normally starts before the
226         // system server and the proxy service. So the long timeout that getService
227         // has before giving up is inappropriate.
228         sp<IBinder> binder = sm->checkService(String16("media.camera.proxy"));
229         if (binder != nullptr) {
230             sCameraServiceProxy = interface_cast<ICameraServiceProxy>(binder);
231         }
232     }
233 #endif
234     return sCameraServiceProxy;
235 }
236 
pingCameraServiceProxy()237 void CameraService::pingCameraServiceProxy() {
238     sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
239     if (proxyBinder == nullptr) return;
240     proxyBinder->pingForUserUpdate();
241 }
242 
broadcastTorchModeStatus(const String8 & cameraId,TorchModeStatus status)243 void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status) {
244     Mutex::Autolock lock(mStatusListenerLock);
245 
246     for (auto& i : mListenerList) {
247         i.second->getListener()->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
248     }
249 }
250 
~CameraService()251 CameraService::~CameraService() {
252     VendorTagDescriptor::clearGlobalVendorTagDescriptor();
253     mUidPolicy->unregisterSelf();
254     mSensorPrivacyPolicy->unregisterSelf();
255 }
256 
onNewProviderRegistered()257 void CameraService::onNewProviderRegistered() {
258     enumerateProviders();
259 }
260 
isPublicallyHiddenSecureCamera(const String8 & cameraId)261 bool CameraService::isPublicallyHiddenSecureCamera(const String8& cameraId) {
262     auto state = getCameraState(cameraId);
263     if (state != nullptr) {
264         return state->isPublicallyHiddenSecureCamera();
265     }
266     // Hidden physical camera ids won't have CameraState
267     return mCameraProviderManager->isPublicallyHiddenSecureCamera(cameraId.c_str());
268 }
269 
updateCameraNumAndIds()270 void CameraService::updateCameraNumAndIds() {
271     Mutex::Autolock l(mServiceLock);
272     mNumberOfCameras = mCameraProviderManager->getCameraCount();
273     mNormalDeviceIds =
274             mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
275 }
276 
addStates(const String8 id)277 void CameraService::addStates(const String8 id) {
278     std::string cameraId(id.c_str());
279     hardware::camera::common::V1_0::CameraResourceCost cost;
280     status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
281     if (res != OK) {
282         ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
283         return;
284     }
285     bool isPublicallyHiddenSecureCamera =
286             mCameraProviderManager->isPublicallyHiddenSecureCamera(id.string());
287     std::set<String8> conflicting;
288     for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
289         conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
290     }
291 
292     {
293         Mutex::Autolock lock(mCameraStatesLock);
294         mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
295                                                                 conflicting,
296                                                                 isPublicallyHiddenSecureCamera));
297     }
298 
299     if (mFlashlight->hasFlashUnit(id)) {
300         Mutex::Autolock al(mTorchStatusMutex);
301         mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
302 
303         broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF);
304     }
305 
306     updateCameraNumAndIds();
307     logDeviceAdded(id, "Device added");
308 }
309 
removeStates(const String8 id)310 void CameraService::removeStates(const String8 id) {
311     updateCameraNumAndIds();
312     if (mFlashlight->hasFlashUnit(id)) {
313         Mutex::Autolock al(mTorchStatusMutex);
314         mTorchStatusMap.removeItem(id);
315     }
316 
317     {
318         Mutex::Autolock lock(mCameraStatesLock);
319         mCameraStates.erase(id);
320     }
321 }
322 
onDeviceStatusChanged(const String8 & id,CameraDeviceStatus newHalStatus)323 void CameraService::onDeviceStatusChanged(const String8& id,
324         CameraDeviceStatus newHalStatus) {
325     ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
326             id.string(), newHalStatus);
327 
328     StatusInternal newStatus = mapToInternal(newHalStatus);
329 
330     std::shared_ptr<CameraState> state = getCameraState(id);
331 
332     if (state == nullptr) {
333         if (newStatus == StatusInternal::PRESENT) {
334             ALOGI("%s: Unknown camera ID %s, a new camera is added",
335                     __FUNCTION__, id.string());
336 
337             // First add as absent to make sure clients are notified below
338             addStates(id);
339 
340             updateStatus(newStatus, id);
341         } else {
342             ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
343         }
344         return;
345     }
346 
347     StatusInternal oldStatus = state->getStatus();
348 
349     if (oldStatus == newStatus) {
350         ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
351         return;
352     }
353 
354     if (newStatus == StatusInternal::NOT_PRESENT) {
355         logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
356                 newStatus));
357 
358         // Set the device status to NOT_PRESENT, clients will no longer be able to connect
359         // to this device until the status changes
360         updateStatus(StatusInternal::NOT_PRESENT, id);
361 
362         sp<BasicClient> clientToDisconnect;
363         {
364             // Don't do this in updateStatus to avoid deadlock over mServiceLock
365             Mutex::Autolock lock(mServiceLock);
366 
367             // Remove cached shim parameters
368             state->setShimParams(CameraParameters());
369 
370             // Remove the client from the list of active clients, if there is one
371             clientToDisconnect = removeClientLocked(id);
372         }
373 
374         // Disconnect client
375         if (clientToDisconnect.get() != nullptr) {
376             ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
377                     __FUNCTION__, id.string());
378             // Notify the client of disconnection
379             clientToDisconnect->notifyError(
380                     hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
381                     CaptureResultExtras{});
382             clientToDisconnect->disconnect();
383         }
384 
385         removeStates(id);
386     } else {
387         if (oldStatus == StatusInternal::NOT_PRESENT) {
388             logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
389                     newStatus));
390         }
391         updateStatus(newStatus, id);
392     }
393 
394 }
395 
onTorchStatusChanged(const String8 & cameraId,TorchModeStatus newStatus)396 void CameraService::onTorchStatusChanged(const String8& cameraId,
397         TorchModeStatus newStatus) {
398     Mutex::Autolock al(mTorchStatusMutex);
399     onTorchStatusChangedLocked(cameraId, newStatus);
400 }
401 
onTorchStatusChangedLocked(const String8 & cameraId,TorchModeStatus newStatus)402 void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
403         TorchModeStatus newStatus) {
404     ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
405             __FUNCTION__, cameraId.string(), newStatus);
406 
407     TorchModeStatus status;
408     status_t res = getTorchStatusLocked(cameraId, &status);
409     if (res) {
410         ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
411                 __FUNCTION__, cameraId.string(), strerror(-res), res);
412         return;
413     }
414     if (status == newStatus) {
415         return;
416     }
417 
418     res = setTorchStatusLocked(cameraId, newStatus);
419     if (res) {
420         ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
421                 (uint32_t)newStatus, strerror(-res), res);
422         return;
423     }
424 
425     {
426         // Update battery life logging for flashlight
427         Mutex::Autolock al(mTorchUidMapMutex);
428         auto iter = mTorchUidMap.find(cameraId);
429         if (iter != mTorchUidMap.end()) {
430             int oldUid = iter->second.second;
431             int newUid = iter->second.first;
432             BatteryNotifier& notifier(BatteryNotifier::getInstance());
433             if (oldUid != newUid) {
434                 // If the UID has changed, log the status and update current UID in mTorchUidMap
435                 if (status == TorchModeStatus::AVAILABLE_ON) {
436                     notifier.noteFlashlightOff(cameraId, oldUid);
437                 }
438                 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
439                     notifier.noteFlashlightOn(cameraId, newUid);
440                 }
441                 iter->second.second = newUid;
442             } else {
443                 // If the UID has not changed, log the status
444                 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
445                     notifier.noteFlashlightOn(cameraId, oldUid);
446                 } else {
447                     notifier.noteFlashlightOff(cameraId, oldUid);
448                 }
449             }
450         }
451     }
452 
453     broadcastTorchModeStatus(cameraId, newStatus);
454 }
455 
getNumberOfCameras(int32_t type,int32_t * numCameras)456 Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
457     ATRACE_CALL();
458     Mutex::Autolock l(mServiceLock);
459     switch (type) {
460         case CAMERA_TYPE_BACKWARD_COMPATIBLE:
461             *numCameras = static_cast<int>(mNormalDeviceIds.size());
462             break;
463         case CAMERA_TYPE_ALL:
464             *numCameras = mNumberOfCameras;
465             break;
466         default:
467             ALOGW("%s: Unknown camera type %d",
468                     __FUNCTION__, type);
469             return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
470                     "Unknown camera type %d", type);
471     }
472     return Status::ok();
473 }
474 
getCameraInfo(int cameraId,CameraInfo * cameraInfo)475 Status CameraService::getCameraInfo(int cameraId,
476         CameraInfo* cameraInfo) {
477     ATRACE_CALL();
478     Mutex::Autolock l(mServiceLock);
479 
480     if (!mInitialized) {
481         return STATUS_ERROR(ERROR_DISCONNECTED,
482                 "Camera subsystem is not available");
483     }
484 
485     if (cameraId < 0 || cameraId >= mNumberOfCameras) {
486         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
487                 "CameraId is not valid");
488     }
489 
490     Status ret = Status::ok();
491     status_t err = mCameraProviderManager->getCameraInfo(
492             cameraIdIntToStrLocked(cameraId), cameraInfo);
493     if (err != OK) {
494         ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
495                 "Error retrieving camera info from device %d: %s (%d)", cameraId,
496                 strerror(-err), err);
497     }
498 
499     return ret;
500 }
501 
cameraIdIntToStrLocked(int cameraIdInt)502 std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
503     if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(mNormalDeviceIds.size())) {
504         ALOGE("%s: input id %d invalid: valid range  (0, %zu)",
505                 __FUNCTION__, cameraIdInt, mNormalDeviceIds.size());
506         return std::string{};
507     }
508 
509     return mNormalDeviceIds[cameraIdInt];
510 }
511 
cameraIdIntToStr(int cameraIdInt)512 String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
513     Mutex::Autolock lock(mServiceLock);
514     return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
515 }
516 
getCameraCharacteristics(const String16 & cameraId,CameraMetadata * cameraInfo)517 Status CameraService::getCameraCharacteristics(const String16& cameraId,
518         CameraMetadata* cameraInfo) {
519     ATRACE_CALL();
520     if (!cameraInfo) {
521         ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
522         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
523     }
524 
525     if (!mInitialized) {
526         ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
527         return STATUS_ERROR(ERROR_DISCONNECTED,
528                 "Camera subsystem is not available");;
529     }
530 
531     if (shouldRejectHiddenCameraConnection(String8(cameraId))) {
532         ALOGW("Attempting to retrieve characteristics for system-only camera id %s, rejected",
533               String8(cameraId).string());
534         return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
535                                 "No camera device with ID \"%s\" currently available",
536                                 String8(cameraId).string());
537 
538     }
539 
540     Status ret{};
541     status_t res = mCameraProviderManager->getCameraCharacteristics(
542             String8(cameraId).string(), cameraInfo);
543     if (res != OK) {
544         return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
545                 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
546                 strerror(-res), res);
547     }
548 
549     int callingPid = CameraThreadState::getCallingPid();
550     int callingUid = CameraThreadState::getCallingUid();
551     std::vector<int32_t> tagsRemoved;
552     // If it's not calling from cameraserver, check the permission.
553     if ((callingPid != getpid()) &&
554             !checkPermission(String16("android.permission.CAMERA"), callingPid, callingUid)) {
555         res = cameraInfo->removePermissionEntries(
556                 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
557                 &tagsRemoved);
558         if (res != OK) {
559             cameraInfo->clear();
560             return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
561                     " characteristics needing camera permission for device %s: %s (%d)",
562                     String8(cameraId).string(), strerror(-res), res);
563         }
564     }
565 
566     if (!tagsRemoved.empty()) {
567         res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
568                 tagsRemoved.data(), tagsRemoved.size());
569         if (res != OK) {
570             cameraInfo->clear();
571             return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
572                     "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
573                     strerror(-res), res);
574         }
575     }
576 
577     return ret;
578 }
579 
getFormattedCurrentTime()580 String8 CameraService::getFormattedCurrentTime() {
581     time_t now = time(nullptr);
582     char formattedTime[64];
583     strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
584     return String8(formattedTime);
585 }
586 
getCameraVendorTagDescriptor(hardware::camera2::params::VendorTagDescriptor * desc)587 Status CameraService::getCameraVendorTagDescriptor(
588         /*out*/
589         hardware::camera2::params::VendorTagDescriptor* desc) {
590     ATRACE_CALL();
591     if (!mInitialized) {
592         ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
593         return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
594     }
595     sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
596     if (globalDescriptor != nullptr) {
597         *desc = *(globalDescriptor.get());
598     }
599     return Status::ok();
600 }
601 
getCameraVendorTagCache(hardware::camera2::params::VendorTagDescriptorCache * cache)602 Status CameraService::getCameraVendorTagCache(
603         /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
604     ATRACE_CALL();
605     if (!mInitialized) {
606         ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
607         return STATUS_ERROR(ERROR_DISCONNECTED,
608                 "Camera subsystem not available");
609     }
610     sp<VendorTagDescriptorCache> globalCache =
611             VendorTagDescriptorCache::getGlobalVendorTagCache();
612     if (globalCache != nullptr) {
613         *cache = *(globalCache.get());
614     }
615     return Status::ok();
616 }
617 
getDeviceVersion(const String8 & cameraId,int * facing)618 int CameraService::getDeviceVersion(const String8& cameraId, int* facing) {
619     ATRACE_CALL();
620 
621     int deviceVersion = 0;
622 
623     status_t res;
624     hardware::hidl_version maxVersion{0,0};
625     res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
626             &maxVersion);
627     if (res != OK) return -1;
628     deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
629 
630     hardware::CameraInfo info;
631     if (facing) {
632         res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
633         if (res != OK) return -1;
634         *facing = info.facing;
635     }
636 
637     return deviceVersion;
638 }
639 
filterGetInfoErrorCode(status_t err)640 Status CameraService::filterGetInfoErrorCode(status_t err) {
641     switch(err) {
642         case NO_ERROR:
643             return Status::ok();
644         case BAD_VALUE:
645             return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
646                     "CameraId is not valid for HAL module");
647         case NO_INIT:
648             return STATUS_ERROR(ERROR_DISCONNECTED,
649                     "Camera device not available");
650         default:
651             return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
652                     "Camera HAL encountered error %d: %s",
653                     err, strerror(-err));
654     }
655 }
656 
makeClient(const sp<CameraService> & cameraService,const sp<IInterface> & cameraCb,const String16 & packageName,const String8 & cameraId,int api1CameraId,int facing,int clientPid,uid_t clientUid,int servicePid,int halVersion,int deviceVersion,apiLevel effectiveApiLevel,sp<BasicClient> * client)657 Status CameraService::makeClient(const sp<CameraService>& cameraService,
658         const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
659         int api1CameraId, int facing, int clientPid, uid_t clientUid, int servicePid,
660         int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
661         /*out*/sp<BasicClient>* client) {
662 
663     if (halVersion < 0 || halVersion == deviceVersion) {
664         // Default path: HAL version is unspecified by caller, create CameraClient
665         // based on device version reported by the HAL.
666         switch(deviceVersion) {
667           case CAMERA_DEVICE_API_VERSION_1_0:
668             if (effectiveApiLevel == API_1) {  // Camera1 API route
669                 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
670                 *client = new CameraClient(cameraService, tmp, packageName,
671                         api1CameraId, facing, clientPid, clientUid,
672                         getpid());
673             } else { // Camera2 API route
674                 ALOGW("Camera using old HAL version: %d", deviceVersion);
675                 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
676                         "Camera device \"%s\" HAL version %d does not support camera2 API",
677                         cameraId.string(), deviceVersion);
678             }
679             break;
680           case CAMERA_DEVICE_API_VERSION_3_0:
681           case CAMERA_DEVICE_API_VERSION_3_1:
682           case CAMERA_DEVICE_API_VERSION_3_2:
683           case CAMERA_DEVICE_API_VERSION_3_3:
684           case CAMERA_DEVICE_API_VERSION_3_4:
685           case CAMERA_DEVICE_API_VERSION_3_5:
686             if (effectiveApiLevel == API_1) { // Camera1 API route
687                 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
688                 *client = new Camera2Client(cameraService, tmp, packageName,
689                         cameraId, api1CameraId,
690                         facing, clientPid, clientUid,
691                         servicePid);
692             } else { // Camera2 API route
693                 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
694                         static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
695                 *client = new CameraDeviceClient(cameraService, tmp, packageName, cameraId,
696                         facing, clientPid, clientUid, servicePid);
697             }
698             break;
699           default:
700             // Should not be reachable
701             ALOGE("Unknown camera device HAL version: %d", deviceVersion);
702             return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
703                     "Camera device \"%s\" has unknown HAL version %d",
704                     cameraId.string(), deviceVersion);
705         }
706     } else {
707         // A particular HAL version is requested by caller. Create CameraClient
708         // based on the requested HAL version.
709         if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
710             halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
711             // Only support higher HAL version device opened as HAL1.0 device.
712             sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
713             *client = new CameraClient(cameraService, tmp, packageName,
714                     api1CameraId, facing, clientPid, clientUid,
715                     servicePid);
716         } else {
717             // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
718             ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
719                     " opened as HAL %x device", halVersion, deviceVersion,
720                     CAMERA_DEVICE_API_VERSION_1_0);
721             return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
722                     "Camera device \"%s\" (HAL version %d) cannot be opened as HAL version %d",
723                     cameraId.string(), deviceVersion, halVersion);
724         }
725     }
726     return Status::ok();
727 }
728 
toString(std::set<userid_t> intSet)729 String8 CameraService::toString(std::set<userid_t> intSet) {
730     String8 s("");
731     bool first = true;
732     for (userid_t i : intSet) {
733         if (first) {
734             s.appendFormat("%d", i);
735             first = false;
736         } else {
737             s.appendFormat(", %d", i);
738         }
739     }
740     return s;
741 }
742 
mapToInterface(TorchModeStatus status)743 int32_t CameraService::mapToInterface(TorchModeStatus status) {
744     int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
745     switch (status) {
746         case TorchModeStatus::NOT_AVAILABLE:
747             serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
748             break;
749         case TorchModeStatus::AVAILABLE_OFF:
750             serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
751             break;
752         case TorchModeStatus::AVAILABLE_ON:
753             serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
754             break;
755         default:
756             ALOGW("Unknown new flash status: %d", status);
757     }
758     return serviceStatus;
759 }
760 
mapToInternal(CameraDeviceStatus status)761 CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
762     StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
763     switch (status) {
764         case CameraDeviceStatus::NOT_PRESENT:
765             serviceStatus = StatusInternal::NOT_PRESENT;
766             break;
767         case CameraDeviceStatus::PRESENT:
768             serviceStatus = StatusInternal::PRESENT;
769             break;
770         case CameraDeviceStatus::ENUMERATING:
771             serviceStatus = StatusInternal::ENUMERATING;
772             break;
773         default:
774             ALOGW("Unknown new HAL device status: %d", status);
775     }
776     return serviceStatus;
777 }
778 
mapToInterface(StatusInternal status)779 int32_t CameraService::mapToInterface(StatusInternal status) {
780     int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
781     switch (status) {
782         case StatusInternal::NOT_PRESENT:
783             serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
784             break;
785         case StatusInternal::PRESENT:
786             serviceStatus = ICameraServiceListener::STATUS_PRESENT;
787             break;
788         case StatusInternal::ENUMERATING:
789             serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
790             break;
791         case StatusInternal::NOT_AVAILABLE:
792             serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
793             break;
794         case StatusInternal::UNKNOWN:
795             serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
796             break;
797         default:
798             ALOGW("Unknown new internal device status: %d", status);
799     }
800     return serviceStatus;
801 }
802 
initializeShimMetadata(int cameraId)803 Status CameraService::initializeShimMetadata(int cameraId) {
804     int uid = CameraThreadState::getCallingUid();
805 
806     String16 internalPackageName("cameraserver");
807     String8 id = String8::format("%d", cameraId);
808     Status ret = Status::ok();
809     sp<Client> tmp = nullptr;
810     if (!(ret = connectHelper<ICameraClient,Client>(
811             sp<ICameraClient>{nullptr}, id, cameraId,
812             static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED),
813             internalPackageName, uid, USE_CALLING_PID,
814             API_1, /*shimUpdateOnly*/ true, /*out*/ tmp)
815             ).isOk()) {
816         ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
817     }
818     return ret;
819 }
820 
getLegacyParametersLazy(int cameraId,CameraParameters * parameters)821 Status CameraService::getLegacyParametersLazy(int cameraId,
822         /*out*/
823         CameraParameters* parameters) {
824 
825     ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
826 
827     Status ret = Status::ok();
828 
829     if (parameters == NULL) {
830         ALOGE("%s: parameters must not be null", __FUNCTION__);
831         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
832     }
833 
834     String8 id = String8::format("%d", cameraId);
835 
836     // Check if we already have parameters
837     {
838         // Scope for service lock
839         Mutex::Autolock lock(mServiceLock);
840         auto cameraState = getCameraState(id);
841         if (cameraState == nullptr) {
842             ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
843             return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
844                     "Invalid camera ID: %s", id.string());
845         }
846         CameraParameters p = cameraState->getShimParams();
847         if (!p.isEmpty()) {
848             *parameters = p;
849             return ret;
850         }
851     }
852 
853     int64_t token = CameraThreadState::clearCallingIdentity();
854     ret = initializeShimMetadata(cameraId);
855     CameraThreadState::restoreCallingIdentity(token);
856     if (!ret.isOk()) {
857         // Error already logged by callee
858         return ret;
859     }
860 
861     // Check for parameters again
862     {
863         // Scope for service lock
864         Mutex::Autolock lock(mServiceLock);
865         auto cameraState = getCameraState(id);
866         if (cameraState == nullptr) {
867             ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
868             return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
869                     "Invalid camera ID: %s", id.string());
870         }
871         CameraParameters p = cameraState->getShimParams();
872         if (!p.isEmpty()) {
873             *parameters = p;
874             return ret;
875         }
876     }
877 
878     ALOGE("%s: Parameters were not initialized, or were empty.  Device may not be present.",
879             __FUNCTION__);
880     return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
881 }
882 
883 // Can camera service trust the caller based on the calling UID?
isTrustedCallingUid(uid_t uid)884 static bool isTrustedCallingUid(uid_t uid) {
885     switch (uid) {
886         case AID_MEDIA:        // mediaserver
887         case AID_CAMERASERVER: // cameraserver
888         case AID_RADIO:        // telephony
889             return true;
890         default:
891             return false;
892     }
893 }
894 
getUidForPackage(String16 packageName,int userId,uid_t & uid,int err)895 static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
896     PermissionController pc;
897     uid = pc.getPackageUid(packageName, 0);
898     if (uid <= 0) {
899         ALOGE("Unknown package: '%s'", String8(packageName).string());
900         dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
901         return BAD_VALUE;
902     }
903 
904     if (userId < 0) {
905         ALOGE("Invalid user: %d", userId);
906         dprintf(err, "Invalid user: %d\n", userId);
907         return BAD_VALUE;
908     }
909 
910     uid = multiuser_get_uid(userId, uid);
911     return NO_ERROR;
912 }
913 
validateConnectLocked(const String8 & cameraId,const String8 & clientName8,int & clientUid,int & clientPid,int & originalClientPid) const914 Status CameraService::validateConnectLocked(const String8& cameraId,
915         const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
916         /*out*/int& originalClientPid) const {
917 
918 #ifdef __BRILLO__
919     UNUSED(clientName8);
920     UNUSED(clientUid);
921     UNUSED(clientPid);
922     UNUSED(originalClientPid);
923 #else
924     Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
925             originalClientPid);
926     if (!allowed.isOk()) {
927         return allowed;
928     }
929 #endif  // __BRILLO__
930 
931     int callingPid = CameraThreadState::getCallingPid();
932 
933     if (!mInitialized) {
934         ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
935                 callingPid);
936         return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
937                 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
938     }
939 
940     if (getCameraState(cameraId) == nullptr) {
941         ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
942                 cameraId.string());
943         return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
944                 "No camera device with ID \"%s\" available", cameraId.string());
945     }
946 
947     status_t err = checkIfDeviceIsUsable(cameraId);
948     if (err != NO_ERROR) {
949         switch(err) {
950             case -ENODEV:
951             case -EBUSY:
952                 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
953                         "No camera device with ID \"%s\" currently available", cameraId.string());
954             default:
955                 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
956                         "Unknown error connecting to ID \"%s\"", cameraId.string());
957         }
958     }
959     return Status::ok();
960 }
961 
validateClientPermissionsLocked(const String8 & cameraId,const String8 & clientName8,int & clientUid,int & clientPid,int & originalClientPid) const962 Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
963         const String8& clientName8, int& clientUid, int& clientPid,
964         /*out*/int& originalClientPid) const {
965     int callingPid = CameraThreadState::getCallingPid();
966     int callingUid = CameraThreadState::getCallingUid();
967 
968     // Check if we can trust clientUid
969     if (clientUid == USE_CALLING_UID) {
970         clientUid = callingUid;
971     } else if (!isTrustedCallingUid(callingUid)) {
972         ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
973                 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
974         return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
975                 "Untrusted caller (calling PID %d, UID %d) trying to "
976                 "forward camera access to camera %s for client %s (PID %d, UID %d)",
977                 callingPid, callingUid, cameraId.string(),
978                 clientName8.string(), clientUid, clientPid);
979     }
980 
981     // Check if we can trust clientPid
982     if (clientPid == USE_CALLING_PID) {
983         clientPid = callingPid;
984     } else if (!isTrustedCallingUid(callingUid)) {
985         ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
986                 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
987         return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
988                 "Untrusted caller (calling PID %d, UID %d) trying to "
989                 "forward camera access to camera %s for client %s (PID %d, UID %d)",
990                 callingPid, callingUid, cameraId.string(),
991                 clientName8.string(), clientUid, clientPid);
992     }
993 
994     // If it's not calling from cameraserver, check the permission.
995     if (callingPid != getpid() &&
996             !checkPermission(String16("android.permission.CAMERA"), clientPid, clientUid)) {
997         ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
998         return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
999                 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1000                 clientName8.string(), clientUid, clientPid, cameraId.string());
1001     }
1002 
1003     // Make sure the UID is in an active state to use the camera
1004     if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
1005         int32_t procState = mUidPolicy->getProcState(callingUid);
1006         ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1007             clientPid, clientUid);
1008         return STATUS_ERROR_FMT(ERROR_DISABLED,
1009                 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1010                 "calling UID %d proc state %" PRId32 ")",
1011                 clientName8.string(), clientUid, clientPid, cameraId.string(),
1012                 callingUid, procState);
1013     }
1014 
1015     // If sensor privacy is enabled then prevent access to the camera
1016     if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1017         ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1018         return STATUS_ERROR_FMT(ERROR_DISABLED,
1019                 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1020                 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1021     }
1022 
1023     // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1024     // connected to camera service directly.
1025     originalClientPid = clientPid;
1026     clientPid = callingPid;
1027 
1028     userid_t clientUserId = multiuser_get_user_id(clientUid);
1029 
1030     // Only allow clients who are being used by the current foreground device user, unless calling
1031     // from our own process OR the caller is using the cameraserver's HIDL interface.
1032     if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
1033             (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
1034         ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1035                 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1036                 toString(mAllowedUsers).string());
1037         return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1038                 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1039                 clientUserId, cameraId.string());
1040     }
1041 
1042     return Status::ok();
1043 }
1044 
checkIfDeviceIsUsable(const String8 & cameraId) const1045 status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1046     auto cameraState = getCameraState(cameraId);
1047     int callingPid = CameraThreadState::getCallingPid();
1048     if (cameraState == nullptr) {
1049         ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1050                 cameraId.string());
1051         return -ENODEV;
1052     }
1053 
1054     StatusInternal currentStatus = cameraState->getStatus();
1055     if (currentStatus == StatusInternal::NOT_PRESENT) {
1056         ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1057                 callingPid, cameraId.string());
1058         return -ENODEV;
1059     } else if (currentStatus == StatusInternal::ENUMERATING) {
1060         ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1061                 callingPid, cameraId.string());
1062         return -EBUSY;
1063     }
1064 
1065     return NO_ERROR;
1066 }
1067 
finishConnectLocked(const sp<BasicClient> & client,const CameraService::DescriptorPtr & desc)1068 void CameraService::finishConnectLocked(const sp<BasicClient>& client,
1069         const CameraService::DescriptorPtr& desc) {
1070 
1071     // Make a descriptor for the incoming client
1072     auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
1073     auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1074 
1075     logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1076             String8(client->getPackageName()));
1077 
1078     if (evicted.size() > 0) {
1079         // This should never happen - clients should already have been removed in disconnect
1080         for (auto& i : evicted) {
1081             ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1082                     __FUNCTION__, i->getKey().string());
1083         }
1084 
1085         LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1086                 __FUNCTION__);
1087     }
1088 
1089     // And register a death notification for the client callback. Do
1090     // this last to avoid Binder policy where a nested Binder
1091     // transaction might be pre-empted to service the client death
1092     // notification if the client process dies before linkToDeath is
1093     // invoked.
1094     sp<IBinder> remoteCallback = client->getRemote();
1095     if (remoteCallback != nullptr) {
1096         remoteCallback->linkToDeath(this);
1097     }
1098 }
1099 
handleEvictionsLocked(const String8 & cameraId,int clientPid,apiLevel effectiveApiLevel,const sp<IBinder> & remoteCallback,const String8 & packageName,sp<BasicClient> * client,std::shared_ptr<resource_policy::ClientDescriptor<String8,sp<BasicClient>>> * partial)1100 status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1101         apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
1102         /*out*/
1103         sp<BasicClient>* client,
1104         std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
1105     ATRACE_CALL();
1106     status_t ret = NO_ERROR;
1107     std::vector<DescriptorPtr> evictedClients;
1108     DescriptorPtr clientDescriptor;
1109     {
1110         if (effectiveApiLevel == API_1) {
1111             // If we are using API1, any existing client for this camera ID with the same remote
1112             // should be returned rather than evicted to allow MediaRecorder to work properly.
1113 
1114             auto current = mActiveClientManager.get(cameraId);
1115             if (current != nullptr) {
1116                 auto clientSp = current->getValue();
1117                 if (clientSp.get() != nullptr) { // should never be needed
1118                     if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1119                         ALOGW("CameraService connect called from same client, but with a different"
1120                                 " API level, evicting prior client...");
1121                     } else if (clientSp->getRemote() == remoteCallback) {
1122                         ALOGI("CameraService::connect X (PID %d) (second call from same"
1123                                 " app binder, returning the same client)", clientPid);
1124                         *client = clientSp;
1125                         return NO_ERROR;
1126                     }
1127                 }
1128             }
1129         }
1130 
1131         // Get current active client PIDs
1132         std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1133         ownerPids.push_back(clientPid);
1134 
1135         std::vector<int> priorityScores(ownerPids.size());
1136         std::vector<int> states(ownerPids.size());
1137 
1138         // Get priority scores of all active PIDs
1139         status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1140                 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1141                 /*out*/&priorityScores[0]);
1142         if (err != OK) {
1143             ALOGE("%s: Priority score query failed: %d",
1144                   __FUNCTION__, err);
1145             return err;
1146         }
1147 
1148         // Update all active clients' priorities
1149         std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
1150         for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1151             pidToPriorityMap.emplace(ownerPids[i],
1152                     resource_policy::ClientPriority(priorityScores[i], states[i],
1153                             /* isVendorClient won't get copied over*/ false));
1154         }
1155         mActiveClientManager.updatePriorities(pidToPriorityMap);
1156 
1157         // Get state for the given cameraId
1158         auto state = getCameraState(cameraId);
1159         if (state == nullptr) {
1160             ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1161                 clientPid, cameraId.string());
1162             // Should never get here because validateConnectLocked should have errored out
1163             return BAD_VALUE;
1164         }
1165 
1166         // Make descriptor for incoming client
1167         clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1168                 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1169                 state->getConflicting(),
1170                 priorityScores[priorityScores.size() - 1],
1171                 clientPid,
1172                 states[states.size() - 1]);
1173 
1174         resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1175 
1176         // Find clients that would be evicted
1177         auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1178 
1179         // If the incoming client was 'evicted,' higher priority clients have the camera in the
1180         // background, so we cannot do evictions
1181         if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1182             ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1183                     " priority).", clientPid);
1184 
1185             sp<BasicClient> clientSp = clientDescriptor->getValue();
1186             String8 curTime = getFormattedCurrentTime();
1187             auto incompatibleClients =
1188                     mActiveClientManager.getIncompatibleClients(clientDescriptor);
1189 
1190             String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
1191                     "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
1192                     cameraId.string(), packageName.string(), clientPid,
1193                     clientPriority.getScore(), clientPriority.getState());
1194 
1195             for (auto& i : incompatibleClients) {
1196                 msg.appendFormat("\n   - Blocked by existing device %s client for package %s"
1197                         "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1198                         i->getKey().string(),
1199                         String8{i->getValue()->getPackageName()}.string(),
1200                         i->getOwnerId(), i->getPriority().getScore(),
1201                         i->getPriority().getState());
1202                 ALOGE("   Conflicts with: Device %s, client package %s (PID %"
1203                         PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
1204                         String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1205                         i->getPriority().getScore(), i->getPriority().getState());
1206             }
1207 
1208             // Log the client's attempt
1209             Mutex::Autolock l(mLogLock);
1210             mEventLog.add(msg);
1211 
1212             return -EBUSY;
1213         }
1214 
1215         for (auto& i : evicted) {
1216             sp<BasicClient> clientSp = i->getValue();
1217             if (clientSp.get() == nullptr) {
1218                 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1219 
1220                 // TODO: Remove this
1221                 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1222                         __FUNCTION__);
1223                 mActiveClientManager.remove(i);
1224                 continue;
1225             }
1226 
1227             ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1228                     i->getKey().string());
1229             evictedClients.push_back(i);
1230 
1231             // Log the clients evicted
1232             logEvent(String8::format("EVICT device %s client held by package %s (PID"
1233                     " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1234                     " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
1235                     i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1236                     i->getOwnerId(), i->getPriority().getScore(),
1237                     i->getPriority().getState(), cameraId.string(),
1238                     packageName.string(), clientPid, clientPriority.getScore(),
1239                     clientPriority.getState()));
1240 
1241             // Notify the client of disconnection
1242             clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1243                     CaptureResultExtras());
1244         }
1245     }
1246 
1247     // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1248     // other clients from connecting in mServiceLockWrapper if held
1249     mServiceLock.unlock();
1250 
1251     // Clear caller identity temporarily so client disconnect PID checks work correctly
1252     int64_t token = CameraThreadState::clearCallingIdentity();
1253 
1254     // Destroy evicted clients
1255     for (auto& i : evictedClients) {
1256         // Disconnect is blocking, and should only have returned when HAL has cleaned up
1257         i->getValue()->disconnect(); // Clients will remove themselves from the active client list
1258     }
1259 
1260     CameraThreadState::restoreCallingIdentity(token);
1261 
1262     for (const auto& i : evictedClients) {
1263         ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1264                 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1265         ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1266         if (ret == TIMED_OUT) {
1267             ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1268                     "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1269                     mActiveClientManager.toString().string());
1270             return -EBUSY;
1271         }
1272         if (ret != NO_ERROR) {
1273             ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1274                     "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1275                     ret, mActiveClientManager.toString().string());
1276             return ret;
1277         }
1278     }
1279 
1280     evictedClients.clear();
1281 
1282     // Once clients have been disconnected, relock
1283     mServiceLock.lock();
1284 
1285     // Check again if the device was unplugged or something while we weren't holding mServiceLock
1286     if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1287         return ret;
1288     }
1289 
1290     *partial = clientDescriptor;
1291     return NO_ERROR;
1292 }
1293 
connect(const sp<ICameraClient> & cameraClient,int api1CameraId,const String16 & clientPackageName,int clientUid,int clientPid,sp<ICamera> * device)1294 Status CameraService::connect(
1295         const sp<ICameraClient>& cameraClient,
1296         int api1CameraId,
1297         const String16& clientPackageName,
1298         int clientUid,
1299         int clientPid,
1300         /*out*/
1301         sp<ICamera>* device) {
1302 
1303     ATRACE_CALL();
1304     Status ret = Status::ok();
1305 
1306     String8 id = cameraIdIntToStr(api1CameraId);
1307     sp<Client> client = nullptr;
1308     ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
1309             CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, clientPid, API_1,
1310             /*shimUpdateOnly*/ false, /*out*/client);
1311 
1312     if(!ret.isOk()) {
1313         logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
1314                 ret.toString8());
1315         return ret;
1316     }
1317 
1318     *device = client;
1319     return ret;
1320 }
1321 
connectLegacy(const sp<ICameraClient> & cameraClient,int api1CameraId,int halVersion,const String16 & clientPackageName,int clientUid,sp<ICamera> * device)1322 Status CameraService::connectLegacy(
1323         const sp<ICameraClient>& cameraClient,
1324         int api1CameraId, int halVersion,
1325         const String16& clientPackageName,
1326         int clientUid,
1327         /*out*/
1328         sp<ICamera>* device) {
1329 
1330     ATRACE_CALL();
1331     String8 id = cameraIdIntToStr(api1CameraId);
1332 
1333     Status ret = Status::ok();
1334     sp<Client> client = nullptr;
1335     ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId, halVersion,
1336             clientPackageName, clientUid, USE_CALLING_PID, API_1, /*shimUpdateOnly*/ false,
1337             /*out*/client);
1338 
1339     if(!ret.isOk()) {
1340         logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
1341                 ret.toString8());
1342         return ret;
1343     }
1344 
1345     *device = client;
1346     return ret;
1347 }
1348 
shouldRejectHiddenCameraConnection(const String8 & cameraId)1349 bool CameraService::shouldRejectHiddenCameraConnection(const String8 & cameraId) {
1350     // If the thread serving this call is not a hwbinder thread and the caller
1351     // isn't the cameraserver itself, and the camera id being requested is to be
1352     // publically hidden, we should reject the connection.
1353     if (getCurrentServingCall() != BinderCallType::HWBINDER &&
1354             CameraThreadState::getCallingPid() != getpid() &&
1355             isPublicallyHiddenSecureCamera(cameraId)) {
1356         return true;
1357     }
1358     return false;
1359 }
1360 
connectDevice(const sp<hardware::camera2::ICameraDeviceCallbacks> & cameraCb,const String16 & cameraId,const String16 & clientPackageName,int clientUid,sp<hardware::camera2::ICameraDeviceUser> * device)1361 Status CameraService::connectDevice(
1362         const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
1363         const String16& cameraId,
1364         const String16& clientPackageName,
1365         int clientUid,
1366         /*out*/
1367         sp<hardware::camera2::ICameraDeviceUser>* device) {
1368 
1369     ATRACE_CALL();
1370     Status ret = Status::ok();
1371     String8 id = String8(cameraId);
1372     sp<CameraDeviceClient> client = nullptr;
1373     String16 clientPackageNameAdj = clientPackageName;
1374 
1375     if (getCurrentServingCall() == BinderCallType::HWBINDER) {
1376         std::string vendorClient =
1377                 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1378         clientPackageNameAdj = String16(vendorClient.c_str());
1379     }
1380     ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
1381             /*api1CameraId*/-1,
1382             CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageNameAdj,
1383             clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, /*out*/client);
1384 
1385     if(!ret.isOk()) {
1386         logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageNameAdj),
1387                 ret.toString8());
1388         return ret;
1389     }
1390 
1391     *device = client;
1392     return ret;
1393 }
1394 
1395 template<class CALLBACK, class CLIENT>
connectHelper(const sp<CALLBACK> & cameraCb,const String8 & cameraId,int api1CameraId,int halVersion,const String16 & clientPackageName,int clientUid,int clientPid,apiLevel effectiveApiLevel,bool shimUpdateOnly,sp<CLIENT> & device)1396 Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
1397         int api1CameraId, int halVersion, const String16& clientPackageName, int clientUid,
1398         int clientPid, apiLevel effectiveApiLevel, bool shimUpdateOnly,
1399         /*out*/sp<CLIENT>& device) {
1400     binder::Status ret = binder::Status::ok();
1401 
1402     String8 clientName8(clientPackageName);
1403 
1404     int originalClientPid = 0;
1405 
1406     ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
1407             "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
1408             (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
1409             static_cast<int>(effectiveApiLevel));
1410 
1411     if (shouldRejectHiddenCameraConnection(cameraId)) {
1412         ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1413               cameraId.c_str());
1414         return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1415                                 "No camera device with ID \"%s\" currently available",
1416                                 cameraId.string());
1417 
1418     }
1419     sp<CLIENT> client = nullptr;
1420     {
1421         // Acquire mServiceLock and prevent other clients from connecting
1422         std::unique_ptr<AutoConditionLock> lock =
1423                 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1424 
1425         if (lock == nullptr) {
1426             ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1427                     , clientPid);
1428             return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1429                     "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1430                     cameraId.string(), clientName8.string(), clientPid);
1431         }
1432 
1433         // Enforce client permissions and do basic sanity checks
1434         if(!(ret = validateConnectLocked(cameraId, clientName8,
1435                 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1436             return ret;
1437         }
1438 
1439         // Check the shim parameters after acquiring lock, if they have already been updated and
1440         // we were doing a shim update, return immediately
1441         if (shimUpdateOnly) {
1442             auto cameraState = getCameraState(cameraId);
1443             if (cameraState != nullptr) {
1444                 if (!cameraState->getShimParams().isEmpty()) return ret;
1445             }
1446         }
1447 
1448         status_t err;
1449 
1450         sp<BasicClient> clientTmp = nullptr;
1451         std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1452         if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
1453                 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
1454                 /*out*/&partial)) != NO_ERROR) {
1455             switch (err) {
1456                 case -ENODEV:
1457                     return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1458                             "No camera device with ID \"%s\" currently available",
1459                             cameraId.string());
1460                 case -EBUSY:
1461                     return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1462                             "Higher-priority client using camera, ID \"%s\" currently unavailable",
1463                             cameraId.string());
1464                 default:
1465                     return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1466                             "Unexpected error %s (%d) opening camera \"%s\"",
1467                             strerror(-err), err, cameraId.string());
1468             }
1469         }
1470 
1471         if (clientTmp.get() != nullptr) {
1472             // Handle special case for API1 MediaRecorder where the existing client is returned
1473             device = static_cast<CLIENT*>(clientTmp.get());
1474             return ret;
1475         }
1476 
1477         // give flashlight a chance to close devices if necessary.
1478         mFlashlight->prepareDeviceOpen(cameraId);
1479 
1480         int facing = -1;
1481         int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing);
1482         if (facing == -1) {
1483             ALOGE("%s: Unable to get camera device \"%s\"  facing", __FUNCTION__, cameraId.string());
1484             return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1485                     "Unable to get camera device \"%s\" facing", cameraId.string());
1486         }
1487 
1488         sp<BasicClient> tmp = nullptr;
1489         if(!(ret = makeClient(this, cameraCb, clientPackageName,
1490                 cameraId, api1CameraId, facing,
1491                 clientPid, clientUid, getpid(),
1492                 halVersion, deviceVersion, effectiveApiLevel,
1493                 /*out*/&tmp)).isOk()) {
1494             return ret;
1495         }
1496         client = static_cast<CLIENT*>(tmp.get());
1497 
1498         LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1499                 __FUNCTION__);
1500 
1501         err = client->initialize(mCameraProviderManager, mMonitorTags);
1502         if (err != OK) {
1503             ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
1504             // Errors could be from the HAL module open call or from AppOpsManager
1505             switch(err) {
1506                 case BAD_VALUE:
1507                     return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1508                             "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1509                 case -EBUSY:
1510                     return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1511                             "Camera \"%s\" is already open", cameraId.string());
1512                 case -EUSERS:
1513                     return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1514                             "Too many cameras already open, cannot open camera \"%s\"",
1515                             cameraId.string());
1516                 case PERMISSION_DENIED:
1517                     return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1518                             "No permission to open camera \"%s\"", cameraId.string());
1519                 case -EACCES:
1520                     return STATUS_ERROR_FMT(ERROR_DISABLED,
1521                             "Camera \"%s\" disabled by policy", cameraId.string());
1522                 case -ENODEV:
1523                 default:
1524                     return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1525                             "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1526                             strerror(-err), err);
1527             }
1528         }
1529 
1530         // Update shim paremeters for legacy clients
1531         if (effectiveApiLevel == API_1) {
1532             // Assume we have always received a Client subclass for API1
1533             sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1534             String8 rawParams = shimClient->getParameters();
1535             CameraParameters params(rawParams);
1536 
1537             auto cameraState = getCameraState(cameraId);
1538             if (cameraState != nullptr) {
1539                 cameraState->setShimParams(params);
1540             } else {
1541                 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1542                         __FUNCTION__, cameraId.string());
1543             }
1544         }
1545 
1546         if (shimUpdateOnly) {
1547             // If only updating legacy shim parameters, immediately disconnect client
1548             mServiceLock.unlock();
1549             client->disconnect();
1550             mServiceLock.lock();
1551         } else {
1552             // Otherwise, add client to active clients list
1553             finishConnectLocked(client, partial);
1554         }
1555     } // lock is destroyed, allow further connect calls
1556 
1557     // Important: release the mutex here so the client can call back into the service from its
1558     // destructor (can be at the end of the call)
1559     device = client;
1560     return ret;
1561 }
1562 
setTorchMode(const String16 & cameraId,bool enabled,const sp<IBinder> & clientBinder)1563 Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
1564         const sp<IBinder>& clientBinder) {
1565     Mutex::Autolock lock(mServiceLock);
1566 
1567     ATRACE_CALL();
1568     if (enabled && clientBinder == nullptr) {
1569         ALOGE("%s: torch client binder is NULL", __FUNCTION__);
1570         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1571                 "Torch client Binder is null");
1572     }
1573 
1574     String8 id = String8(cameraId.string());
1575     int uid = CameraThreadState::getCallingUid();
1576 
1577     // verify id is valid.
1578     auto state = getCameraState(id);
1579     if (state == nullptr) {
1580         ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
1581         return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1582                 "Camera ID \"%s\" is a not valid camera ID", id.string());
1583     }
1584 
1585     StatusInternal cameraStatus = state->getStatus();
1586     if (cameraStatus != StatusInternal::PRESENT &&
1587             cameraStatus != StatusInternal::NOT_AVAILABLE) {
1588         ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
1589         return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1590                 "Camera ID \"%s\" is a not valid camera ID", id.string());
1591     }
1592 
1593     {
1594         Mutex::Autolock al(mTorchStatusMutex);
1595         TorchModeStatus status;
1596         status_t err = getTorchStatusLocked(id, &status);
1597         if (err != OK) {
1598             if (err == NAME_NOT_FOUND) {
1599                 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1600                         "Camera \"%s\" does not have a flash unit", id.string());
1601             }
1602             ALOGE("%s: getting current torch status failed for camera %s",
1603                     __FUNCTION__, id.string());
1604             return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1605                     "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
1606                     strerror(-err), err);
1607         }
1608 
1609         if (status == TorchModeStatus::NOT_AVAILABLE) {
1610             if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
1611                 ALOGE("%s: torch mode of camera %s is not available because "
1612                         "camera is in use", __FUNCTION__, id.string());
1613                 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1614                         "Torch for camera \"%s\" is not available due to an existing camera user",
1615                         id.string());
1616             } else {
1617                 ALOGE("%s: torch mode of camera %s is not available due to "
1618                         "insufficient resources", __FUNCTION__, id.string());
1619                 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1620                         "Torch for camera \"%s\" is not available due to insufficient resources",
1621                         id.string());
1622             }
1623         }
1624     }
1625 
1626     {
1627         // Update UID map - this is used in the torch status changed callbacks, so must be done
1628         // before setTorchMode
1629         Mutex::Autolock al(mTorchUidMapMutex);
1630         if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1631             mTorchUidMap[id].first = uid;
1632             mTorchUidMap[id].second = uid;
1633         } else {
1634             // Set the pending UID
1635             mTorchUidMap[id].first = uid;
1636         }
1637     }
1638 
1639     status_t err = mFlashlight->setTorchMode(id, enabled);
1640 
1641     if (err != OK) {
1642         int32_t errorCode;
1643         String8 msg;
1644         switch (err) {
1645             case -ENOSYS:
1646                 msg = String8::format("Camera \"%s\" has no flashlight",
1647                     id.string());
1648                 errorCode = ERROR_ILLEGAL_ARGUMENT;
1649                 break;
1650             default:
1651                 msg = String8::format(
1652                     "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
1653                     id.string(), enabled, strerror(-err), err);
1654                 errorCode = ERROR_INVALID_OPERATION;
1655         }
1656         ALOGE("%s: %s", __FUNCTION__, msg.string());
1657         return STATUS_ERROR(errorCode, msg.string());
1658     }
1659 
1660     {
1661         // update the link to client's death
1662         Mutex::Autolock al(mTorchClientMapMutex);
1663         ssize_t index = mTorchClientMap.indexOfKey(id);
1664         if (enabled) {
1665             if (index == NAME_NOT_FOUND) {
1666                 mTorchClientMap.add(id, clientBinder);
1667             } else {
1668                 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
1669                 mTorchClientMap.replaceValueAt(index, clientBinder);
1670             }
1671             clientBinder->linkToDeath(this);
1672         } else if (index != NAME_NOT_FOUND) {
1673             mTorchClientMap.valueAt(index)->unlinkToDeath(this);
1674         }
1675     }
1676 
1677     int clientPid = CameraThreadState::getCallingPid();
1678     const char *id_cstr = id.c_str();
1679     const char *torchState = enabled ? "on" : "off";
1680     ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
1681     logTorchEvent(id_cstr, torchState , clientPid);
1682     return Status::ok();
1683 }
1684 
notifySystemEvent(int32_t eventId,const std::vector<int32_t> & args)1685 Status CameraService::notifySystemEvent(int32_t eventId,
1686         const std::vector<int32_t>& args) {
1687     const int pid = CameraThreadState::getCallingPid();
1688     const int selfPid = getpid();
1689 
1690     // Permission checks
1691     if (pid != selfPid) {
1692         // Ensure we're being called by system_server, or similar process with
1693         // permissions to notify the camera service about system events
1694         if (!checkCallingPermission(
1695                 String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
1696             const int uid = CameraThreadState::getCallingUid();
1697             ALOGE("Permission Denial: cannot send updates to camera service about system"
1698                     " events from pid=%d, uid=%d", pid, uid);
1699             return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1700                     "No permission to send updates to camera service about system events"
1701                     " from pid=%d, uid=%d", pid, uid);
1702         }
1703     }
1704 
1705     ATRACE_CALL();
1706 
1707     switch(eventId) {
1708         case ICameraService::EVENT_USER_SWITCHED: {
1709             // Try to register for UID and sensor privacy policy updates, in case we're recovering
1710             // from a system server crash
1711             mUidPolicy->registerSelf();
1712             mSensorPrivacyPolicy->registerSelf();
1713             doUserSwitch(/*newUserIds*/ args);
1714             break;
1715         }
1716         case ICameraService::EVENT_NONE:
1717         default: {
1718             ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1719                     eventId);
1720             break;
1721         }
1722     }
1723     return Status::ok();
1724 }
1725 
notifyMonitoredUids()1726 void CameraService::notifyMonitoredUids() {
1727     Mutex::Autolock lock(mStatusListenerLock);
1728 
1729     for (const auto& it : mListenerList) {
1730         auto ret = it.second->getListener()->onCameraAccessPrioritiesChanged();
1731         if (!ret.isOk()) {
1732             ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
1733                     ret.exceptionCode());
1734         }
1735     }
1736 }
1737 
notifyDeviceStateChange(int64_t newState)1738 Status CameraService::notifyDeviceStateChange(int64_t newState) {
1739     const int pid = CameraThreadState::getCallingPid();
1740     const int selfPid = getpid();
1741 
1742     // Permission checks
1743     if (pid != selfPid) {
1744         // Ensure we're being called by system_server, or similar process with
1745         // permissions to notify the camera service about system events
1746         if (!checkCallingPermission(
1747                 String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
1748             const int uid = CameraThreadState::getCallingUid();
1749             ALOGE("Permission Denial: cannot send updates to camera service about device"
1750                     " state changes from pid=%d, uid=%d", pid, uid);
1751             return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1752                     "No permission to send updates to camera service about device state"
1753                     " changes from pid=%d, uid=%d", pid, uid);
1754         }
1755     }
1756 
1757     ATRACE_CALL();
1758 
1759     using hardware::camera::provider::V2_5::DeviceState;
1760     hardware::hidl_bitfield<DeviceState> newDeviceState{};
1761     if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
1762         newDeviceState |= DeviceState::BACK_COVERED;
1763     }
1764     if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
1765         newDeviceState |= DeviceState::FRONT_COVERED;
1766     }
1767     if (newState & ICameraService::DEVICE_STATE_FOLDED) {
1768         newDeviceState |= DeviceState::FOLDED;
1769     }
1770     // Only map vendor bits directly
1771     uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
1772     newDeviceState |= vendorBits;
1773 
1774     ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
1775     Mutex::Autolock l(mServiceLock);
1776     mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
1777 
1778     return Status::ok();
1779 }
1780 
addListener(const sp<ICameraServiceListener> & listener,std::vector<hardware::CameraStatus> * cameraStatuses)1781 Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
1782         /*out*/
1783         std::vector<hardware::CameraStatus> *cameraStatuses) {
1784     return addListenerHelper(listener, cameraStatuses);
1785 }
1786 
addListenerHelper(const sp<ICameraServiceListener> & listener,std::vector<hardware::CameraStatus> * cameraStatuses,bool isVendorListener)1787 Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
1788         /*out*/
1789         std::vector<hardware::CameraStatus> *cameraStatuses,
1790         bool isVendorListener) {
1791 
1792     ATRACE_CALL();
1793 
1794     ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
1795 
1796     if (listener == nullptr) {
1797         ALOGE("%s: Listener must not be null", __FUNCTION__);
1798         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
1799     }
1800 
1801     Mutex::Autolock lock(mServiceLock);
1802 
1803     {
1804         Mutex::Autolock lock(mStatusListenerLock);
1805         for (const auto &it : mListenerList) {
1806             if (IInterface::asBinder(it.second->getListener()) == IInterface::asBinder(listener)) {
1807                 ALOGW("%s: Tried to add listener %p which was already subscribed",
1808                       __FUNCTION__, listener.get());
1809                 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
1810             }
1811         }
1812 
1813         auto clientUid = CameraThreadState::getCallingUid();
1814         auto clientPid = CameraThreadState::getCallingPid();
1815         bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
1816                 clientPid, clientUid);
1817         sp<ServiceListener> serviceListener = new ServiceListener(this, listener,
1818                 clientUid, clientPid, openCloseCallbackAllowed);
1819         auto ret = serviceListener->initialize();
1820         if (ret != NO_ERROR) {
1821             String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
1822                     strerror(-ret), ret);
1823             ALOGE("%s: %s", __FUNCTION__, msg.string());
1824             return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1825         }
1826         mListenerList.emplace_back(isVendorListener, serviceListener);
1827         mUidPolicy->registerMonitorUid(clientUid);
1828     }
1829 
1830     /* Collect current devices and status */
1831     {
1832         Mutex::Autolock lock(mCameraStatesLock);
1833         for (auto& i : mCameraStates) {
1834             cameraStatuses->emplace_back(i.first, mapToInterface(i.second->getStatus()));
1835         }
1836     }
1837 
1838     // Remove the camera statuses that should be hidden from the client, we do
1839     // this after collecting the states in order to avoid holding
1840     // mCameraStatesLock and mInterfaceLock (held in
1841     // isPublicallyHiddenSecureCamera()) at the same time.
1842     cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
1843                 [this, &isVendorListener](const hardware::CameraStatus& s) {
1844                     bool ret = !isVendorListener && isPublicallyHiddenSecureCamera(s.cameraId);
1845                     if (ret) {
1846                         ALOGV("Cannot add public listener for hidden system-only %s for pid %d",
1847                                 s.cameraId.c_str(), CameraThreadState::getCallingPid());
1848                     }
1849                     return ret;
1850                 }),
1851                 cameraStatuses->end());
1852 
1853     /*
1854      * Immediately signal current torch status to this listener only
1855      * This may be a subset of all the devices, so don't include it in the response directly
1856      */
1857     {
1858         Mutex::Autolock al(mTorchStatusMutex);
1859         for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
1860             String16 id = String16(mTorchStatusMap.keyAt(i).string());
1861             listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
1862         }
1863     }
1864 
1865     return Status::ok();
1866 }
1867 
removeListener(const sp<ICameraServiceListener> & listener)1868 Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
1869     ATRACE_CALL();
1870 
1871     ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1872 
1873     if (listener == 0) {
1874         ALOGE("%s: Listener must not be null", __FUNCTION__);
1875         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
1876     }
1877 
1878     Mutex::Autolock lock(mServiceLock);
1879 
1880     {
1881         Mutex::Autolock lock(mStatusListenerLock);
1882         for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
1883             if (IInterface::asBinder(it->second->getListener()) == IInterface::asBinder(listener)) {
1884                 mUidPolicy->unregisterMonitorUid(it->second->getListenerUid());
1885                 IInterface::asBinder(listener)->unlinkToDeath(it->second);
1886                 mListenerList.erase(it);
1887                 return Status::ok();
1888             }
1889         }
1890     }
1891 
1892     ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1893           __FUNCTION__, listener.get());
1894 
1895     return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
1896 }
1897 
getLegacyParameters(int cameraId,String16 * parameters)1898 Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
1899 
1900     ATRACE_CALL();
1901     ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1902 
1903     if (parameters == NULL) {
1904         ALOGE("%s: parameters must not be null", __FUNCTION__);
1905         return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
1906     }
1907 
1908     Status ret = Status::ok();
1909 
1910     CameraParameters shimParams;
1911     if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
1912         // Error logged by caller
1913         return ret;
1914     }
1915 
1916     String8 shimParamsString8 = shimParams.flatten();
1917     String16 shimParamsString16 = String16(shimParamsString8);
1918 
1919     *parameters = shimParamsString16;
1920 
1921     return ret;
1922 }
1923 
supportsCameraApi(const String16 & cameraId,int apiVersion,bool * isSupported)1924 Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
1925         /*out*/ bool *isSupported) {
1926     ATRACE_CALL();
1927 
1928     const String8 id = String8(cameraId);
1929 
1930     ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
1931 
1932     switch (apiVersion) {
1933         case API_VERSION_1:
1934         case API_VERSION_2:
1935             break;
1936         default:
1937             String8 msg = String8::format("Unknown API version %d", apiVersion);
1938             ALOGE("%s: %s", __FUNCTION__, msg.string());
1939             return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1940     }
1941 
1942     int deviceVersion = getDeviceVersion(id);
1943     switch (deviceVersion) {
1944         case CAMERA_DEVICE_API_VERSION_1_0:
1945         case CAMERA_DEVICE_API_VERSION_3_0:
1946         case CAMERA_DEVICE_API_VERSION_3_1:
1947             if (apiVersion == API_VERSION_2) {
1948                 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
1949                         __FUNCTION__, id.string(), deviceVersion);
1950                 *isSupported = false;
1951             } else { // if (apiVersion == API_VERSION_1) {
1952                 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
1953                         __FUNCTION__, id.string());
1954                 *isSupported = true;
1955             }
1956             break;
1957         case CAMERA_DEVICE_API_VERSION_3_2:
1958         case CAMERA_DEVICE_API_VERSION_3_3:
1959         case CAMERA_DEVICE_API_VERSION_3_4:
1960         case CAMERA_DEVICE_API_VERSION_3_5:
1961             ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
1962                     __FUNCTION__, id.string());
1963             *isSupported = true;
1964             break;
1965         case -1: {
1966             String8 msg = String8::format("Unknown camera ID %s", id.string());
1967             ALOGE("%s: %s", __FUNCTION__, msg.string());
1968             return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1969         }
1970         default: {
1971             String8 msg = String8::format("Unknown device version %x for device %s",
1972                     deviceVersion, id.string());
1973             ALOGE("%s: %s", __FUNCTION__, msg.string());
1974             return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
1975         }
1976     }
1977 
1978     return Status::ok();
1979 }
1980 
isHiddenPhysicalCamera(const String16 & cameraId,bool * isSupported)1981 Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
1982         /*out*/ bool *isSupported) {
1983     ATRACE_CALL();
1984 
1985     const String8 id = String8(cameraId);
1986 
1987     ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
1988     *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
1989 
1990     return Status::ok();
1991 }
1992 
removeByClient(const BasicClient * client)1993 void CameraService::removeByClient(const BasicClient* client) {
1994     Mutex::Autolock lock(mServiceLock);
1995     for (auto& i : mActiveClientManager.getAll()) {
1996         auto clientSp = i->getValue();
1997         if (clientSp.get() == client) {
1998             mActiveClientManager.remove(i);
1999         }
2000     }
2001 }
2002 
evictClientIdByRemote(const wp<IBinder> & remote)2003 bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
2004     bool ret = false;
2005     {
2006         // Acquire mServiceLock and prevent other clients from connecting
2007         std::unique_ptr<AutoConditionLock> lock =
2008                 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2009 
2010 
2011         std::vector<sp<BasicClient>> evicted;
2012         for (auto& i : mActiveClientManager.getAll()) {
2013             auto clientSp = i->getValue();
2014             if (clientSp.get() == nullptr) {
2015                 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2016                 mActiveClientManager.remove(i);
2017                 continue;
2018             }
2019             if (remote == clientSp->getRemote()) {
2020                 mActiveClientManager.remove(i);
2021                 evicted.push_back(clientSp);
2022 
2023                 // Notify the client of disconnection
2024                 clientSp->notifyError(
2025                         hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
2026                         CaptureResultExtras());
2027             }
2028         }
2029 
2030         // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2031         // other clients from connecting in mServiceLockWrapper if held
2032         mServiceLock.unlock();
2033 
2034         // Do not clear caller identity, remote caller should be client proccess
2035 
2036         for (auto& i : evicted) {
2037             if (i.get() != nullptr) {
2038                 i->disconnect();
2039                 ret = true;
2040             }
2041         }
2042 
2043         // Reacquire mServiceLock
2044         mServiceLock.lock();
2045 
2046     } // lock is destroyed, allow further connect calls
2047 
2048     return ret;
2049 }
2050 
getCameraState(const String8 & cameraId) const2051 std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2052         const String8& cameraId) const {
2053     std::shared_ptr<CameraState> state;
2054     {
2055         Mutex::Autolock lock(mCameraStatesLock);
2056         auto iter = mCameraStates.find(cameraId);
2057         if (iter != mCameraStates.end()) {
2058             state = iter->second;
2059         }
2060     }
2061     return state;
2062 }
2063 
removeClientLocked(const String8 & cameraId)2064 sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2065     // Remove from active clients list
2066     auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2067     if (clientDescriptorPtr == nullptr) {
2068         ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2069                 cameraId.string());
2070         return sp<BasicClient>{nullptr};
2071     }
2072 
2073     return clientDescriptorPtr->getValue();
2074 }
2075 
doUserSwitch(const std::vector<int32_t> & newUserIds)2076 void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
2077     // Acquire mServiceLock and prevent other clients from connecting
2078     std::unique_ptr<AutoConditionLock> lock =
2079             AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2080 
2081     std::set<userid_t> newAllowedUsers;
2082     for (size_t i = 0; i < newUserIds.size(); i++) {
2083         if (newUserIds[i] < 0) {
2084             ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
2085                     __FUNCTION__, newUserIds[i]);
2086             return;
2087         }
2088         newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
2089     }
2090 
2091 
2092     if (newAllowedUsers == mAllowedUsers) {
2093         ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2094         return;
2095     }
2096 
2097     logUserSwitch(mAllowedUsers, newAllowedUsers);
2098 
2099     mAllowedUsers = std::move(newAllowedUsers);
2100 
2101     // Current user has switched, evict all current clients.
2102     std::vector<sp<BasicClient>> evicted;
2103     for (auto& i : mActiveClientManager.getAll()) {
2104         auto clientSp = i->getValue();
2105 
2106         if (clientSp.get() == nullptr) {
2107             ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2108             continue;
2109         }
2110 
2111         // Don't evict clients that are still allowed.
2112         uid_t clientUid = clientSp->getClientUid();
2113         userid_t clientUserId = multiuser_get_user_id(clientUid);
2114         if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2115             continue;
2116         }
2117 
2118         evicted.push_back(clientSp);
2119 
2120         String8 curTime = getFormattedCurrentTime();
2121 
2122         ALOGE("Evicting conflicting client for camera ID %s due to user change",
2123                 i->getKey().string());
2124 
2125         // Log the clients evicted
2126         logEvent(String8::format("EVICT device %s client held by package %s (PID %"
2127                 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n   - Evicted due"
2128                 " to user switch.", i->getKey().string(),
2129                 String8{clientSp->getPackageName()}.string(),
2130                 i->getOwnerId(), i->getPriority().getScore(),
2131                 i->getPriority().getState()));
2132 
2133     }
2134 
2135     // Do not hold mServiceLock while disconnecting clients, but retain the condition
2136     // blocking other clients from connecting in mServiceLockWrapper if held.
2137     mServiceLock.unlock();
2138 
2139     // Clear caller identity temporarily so client disconnect PID checks work correctly
2140     int64_t token = CameraThreadState::clearCallingIdentity();
2141 
2142     for (auto& i : evicted) {
2143         i->disconnect();
2144     }
2145 
2146     CameraThreadState::restoreCallingIdentity(token);
2147 
2148     // Reacquire mServiceLock
2149     mServiceLock.lock();
2150 }
2151 
logEvent(const char * event)2152 void CameraService::logEvent(const char* event) {
2153     String8 curTime = getFormattedCurrentTime();
2154     Mutex::Autolock l(mLogLock);
2155     mEventLog.add(String8::format("%s : %s", curTime.string(), event));
2156 }
2157 
logDisconnected(const char * cameraId,int clientPid,const char * clientPackage)2158 void CameraService::logDisconnected(const char* cameraId, int clientPid,
2159         const char* clientPackage) {
2160     // Log the clients evicted
2161     logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
2162             clientPackage, clientPid));
2163 }
2164 
logConnected(const char * cameraId,int clientPid,const char * clientPackage)2165 void CameraService::logConnected(const char* cameraId, int clientPid,
2166         const char* clientPackage) {
2167     // Log the clients evicted
2168     logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
2169             clientPackage, clientPid));
2170 }
2171 
logRejected(const char * cameraId,int clientPid,const char * clientPackage,const char * reason)2172 void CameraService::logRejected(const char* cameraId, int clientPid,
2173         const char* clientPackage, const char* reason) {
2174     // Log the client rejected
2175     logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
2176             cameraId, clientPackage, clientPid, reason));
2177 }
2178 
logTorchEvent(const char * cameraId,const char * torchState,int clientPid)2179 void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2180     // Log torch event
2181     logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2182             torchState, clientPid));
2183 }
2184 
logUserSwitch(const std::set<userid_t> & oldUserIds,const std::set<userid_t> & newUserIds)2185 void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2186         const std::set<userid_t>& newUserIds) {
2187     String8 newUsers = toString(newUserIds);
2188     String8 oldUsers = toString(oldUserIds);
2189     if (oldUsers.size() == 0) {
2190         oldUsers = "<None>";
2191     }
2192     // Log the new and old users
2193     logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
2194             oldUsers.string(), newUsers.string()));
2195 }
2196 
logDeviceRemoved(const char * cameraId,const char * reason)2197 void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2198     // Log the device removal
2199     logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2200 }
2201 
logDeviceAdded(const char * cameraId,const char * reason)2202 void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2203     // Log the device removal
2204     logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2205 }
2206 
logClientDied(int clientPid,const char * reason)2207 void CameraService::logClientDied(int clientPid, const char* reason) {
2208     // Log the device removal
2209     logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
2210 }
2211 
logServiceError(const char * msg,int errorCode)2212 void CameraService::logServiceError(const char* msg, int errorCode) {
2213     String8 curTime = getFormattedCurrentTime();
2214     logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
2215 }
2216 
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)2217 status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2218         uint32_t flags) {
2219 
2220     // Permission checks
2221     switch (code) {
2222         case SHELL_COMMAND_TRANSACTION: {
2223             int in = data.readFileDescriptor();
2224             int out = data.readFileDescriptor();
2225             int err = data.readFileDescriptor();
2226             int argc = data.readInt32();
2227             Vector<String16> args;
2228             for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2229                args.add(data.readString16());
2230             }
2231             sp<IBinder> unusedCallback;
2232             sp<IResultReceiver> resultReceiver;
2233             status_t status;
2234             if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2235                 return status;
2236             }
2237             if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2238                 return status;
2239             }
2240             status = shellCommand(in, out, err, args);
2241             if (resultReceiver != nullptr) {
2242                 resultReceiver->send(status);
2243             }
2244             return NO_ERROR;
2245         }
2246     }
2247 
2248     return BnCameraService::onTransact(code, data, reply, flags);
2249 }
2250 
2251 // We share the media players for shutter and recording sound for all clients.
2252 // A reference count is kept to determine when we will actually release the
2253 // media players.
2254 
newMediaPlayer(const char * file)2255 sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2256     sp<MediaPlayer> mp = new MediaPlayer();
2257     status_t error;
2258     if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
2259         mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
2260         error = mp->prepare();
2261     }
2262     if (error != NO_ERROR) {
2263         ALOGE("Failed to load CameraService sounds: %s", file);
2264         mp->disconnect();
2265         mp.clear();
2266         return nullptr;
2267     }
2268     return mp;
2269 }
2270 
increaseSoundRef()2271 void CameraService::increaseSoundRef() {
2272     Mutex::Autolock lock(mSoundLock);
2273     mSoundRef++;
2274 }
2275 
loadSoundLocked(sound_kind kind)2276 void CameraService::loadSoundLocked(sound_kind kind) {
2277     ATRACE_CALL();
2278 
2279     LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2280     if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2281         mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2282         if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2283             mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2284         }
2285     } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] ==  NULL) {
2286         mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2287         if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2288             mSoundPlayer[SOUND_RECORDING_START] =
2289                 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
2290         }
2291     } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2292         mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2293         if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2294             mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2295         }
2296     }
2297 }
2298 
decreaseSoundRef()2299 void CameraService::decreaseSoundRef() {
2300     Mutex::Autolock lock(mSoundLock);
2301     LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
2302     if (--mSoundRef) return;
2303 
2304     for (int i = 0; i < NUM_SOUNDS; i++) {
2305         if (mSoundPlayer[i] != 0) {
2306             mSoundPlayer[i]->disconnect();
2307             mSoundPlayer[i].clear();
2308         }
2309     }
2310 }
2311 
playSound(sound_kind kind)2312 void CameraService::playSound(sound_kind kind) {
2313     ATRACE_CALL();
2314 
2315     LOG1("playSound(%d)", kind);
2316     Mutex::Autolock lock(mSoundLock);
2317     loadSoundLocked(kind);
2318     sp<MediaPlayer> player = mSoundPlayer[kind];
2319     if (player != 0) {
2320         player->seekTo(0);
2321         player->start();
2322     }
2323 }
2324 
2325 // ----------------------------------------------------------------------------
2326 
Client(const sp<CameraService> & cameraService,const sp<ICameraClient> & cameraClient,const String16 & clientPackageName,const String8 & cameraIdStr,int api1CameraId,int cameraFacing,int clientPid,uid_t clientUid,int servicePid)2327 CameraService::Client::Client(const sp<CameraService>& cameraService,
2328         const sp<ICameraClient>& cameraClient,
2329         const String16& clientPackageName,
2330         const String8& cameraIdStr,
2331         int api1CameraId, int cameraFacing,
2332         int clientPid, uid_t clientUid,
2333         int servicePid) :
2334         CameraService::BasicClient(cameraService,
2335                 IInterface::asBinder(cameraClient),
2336                 clientPackageName,
2337                 cameraIdStr, cameraFacing,
2338                 clientPid, clientUid,
2339                 servicePid),
2340         mCameraId(api1CameraId)
2341 {
2342     int callingPid = CameraThreadState::getCallingPid();
2343     LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
2344 
2345     mRemoteCallback = cameraClient;
2346 
2347     cameraService->increaseSoundRef();
2348 
2349     LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
2350 }
2351 
2352 // tear down the client
~Client()2353 CameraService::Client::~Client() {
2354     ALOGV("~Client");
2355     mDestructionStarted = true;
2356 
2357     sCameraService->decreaseSoundRef();
2358     // unconditionally disconnect. function is idempotent
2359     Client::disconnect();
2360 }
2361 
2362 sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
2363 
BasicClient(const sp<CameraService> & cameraService,const sp<IBinder> & remoteCallback,const String16 & clientPackageName,const String8 & cameraIdStr,int cameraFacing,int clientPid,uid_t clientUid,int servicePid)2364 CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
2365         const sp<IBinder>& remoteCallback,
2366         const String16& clientPackageName,
2367         const String8& cameraIdStr, int cameraFacing,
2368         int clientPid, uid_t clientUid,
2369         int servicePid):
2370         mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing),
2371         mClientPackageName(clientPackageName), mClientPid(clientPid), mClientUid(clientUid),
2372         mServicePid(servicePid),
2373         mDisconnected(false),
2374         mRemoteBinder(remoteCallback)
2375 {
2376     if (sCameraService == nullptr) {
2377         sCameraService = cameraService;
2378     }
2379     mOpsActive = false;
2380     mDestructionStarted = false;
2381 
2382     // In some cases the calling code has no access to the package it runs under.
2383     // For example, NDK camera API.
2384     // In this case we will get the packages for the calling UID and pick the first one
2385     // for attributing the app op. This will work correctly for runtime permissions
2386     // as for legacy apps we will toggle the app op for all packages in the UID.
2387     // The caveat is that the operation may be attributed to the wrong package and
2388     // stats based on app ops may be slightly off.
2389     if (mClientPackageName.size() <= 0) {
2390         sp<IServiceManager> sm = defaultServiceManager();
2391         sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
2392         if (binder == 0) {
2393             ALOGE("Cannot get permission service");
2394             // Leave mClientPackageName unchanged (empty) and the further interaction
2395             // with camera will fail in BasicClient::startCameraOps
2396             return;
2397         }
2398 
2399         sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2400         Vector<String16> packages;
2401 
2402         permCtrl->getPackagesForUid(mClientUid, packages);
2403 
2404         if (packages.isEmpty()) {
2405             ALOGE("No packages for calling UID");
2406             // Leave mClientPackageName unchanged (empty) and the further interaction
2407             // with camera will fail in BasicClient::startCameraOps
2408             return;
2409         }
2410         mClientPackageName = packages[0];
2411     }
2412     if (getCurrentServingCall() != BinderCallType::HWBINDER) {
2413         mAppOpsManager = std::make_unique<AppOpsManager>();
2414     }
2415 }
2416 
~BasicClient()2417 CameraService::BasicClient::~BasicClient() {
2418     ALOGV("~BasicClient");
2419     mDestructionStarted = true;
2420 }
2421 
disconnect()2422 binder::Status CameraService::BasicClient::disconnect() {
2423     binder::Status res = Status::ok();
2424     if (mDisconnected) {
2425         return res;
2426     }
2427     mDisconnected = true;
2428 
2429     sCameraService->removeByClient(this);
2430     sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
2431     sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
2432             mCameraIdStr.c_str());
2433 
2434     sp<IBinder> remote = getRemote();
2435     if (remote != nullptr) {
2436         remote->unlinkToDeath(sCameraService);
2437     }
2438 
2439     finishCameraOps();
2440     // Notify flashlight that a camera device is closed.
2441     sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
2442     ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
2443             mClientPid);
2444 
2445     // client shouldn't be able to call into us anymore
2446     mClientPid = 0;
2447 
2448     return res;
2449 }
2450 
dump(int,const Vector<String16> &)2451 status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
2452     // No dumping of clients directly over Binder,
2453     // must go through CameraService::dump
2454     android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
2455             CameraThreadState::getCallingUid(), NULL, 0);
2456     return OK;
2457 }
2458 
getPackageName() const2459 String16 CameraService::BasicClient::getPackageName() const {
2460     return mClientPackageName;
2461 }
2462 
2463 
getClientPid() const2464 int CameraService::BasicClient::getClientPid() const {
2465     return mClientPid;
2466 }
2467 
getClientUid() const2468 uid_t CameraService::BasicClient::getClientUid() const {
2469     return mClientUid;
2470 }
2471 
canCastToApiClient(apiLevel level) const2472 bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
2473     // Defaults to API2.
2474     return level == API_2;
2475 }
2476 
startCameraOps()2477 status_t CameraService::BasicClient::startCameraOps() {
2478     ATRACE_CALL();
2479 
2480     {
2481         ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
2482               __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
2483     }
2484     if (mAppOpsManager != nullptr) {
2485         // Notify app ops that the camera is not available
2486         mOpsCallback = new OpsCallback(this);
2487         int32_t res;
2488         mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
2489                 mClientPackageName, mOpsCallback);
2490         res = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA,
2491                 mClientUid, mClientPackageName, /*startIfModeDefault*/ false);
2492 
2493         if (res == AppOpsManager::MODE_ERRORED) {
2494             ALOGI("Camera %s: Access for \"%s\" has been revoked",
2495                     mCameraIdStr.string(), String8(mClientPackageName).string());
2496             return PERMISSION_DENIED;
2497         }
2498 
2499         if (res == AppOpsManager::MODE_IGNORED) {
2500             ALOGI("Camera %s: Access for \"%s\" has been restricted",
2501                     mCameraIdStr.string(), String8(mClientPackageName).string());
2502             // Return the same error as for device policy manager rejection
2503             return -EACCES;
2504         }
2505     }
2506 
2507     mOpsActive = true;
2508 
2509     // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
2510     sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
2511 
2512     int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2513     if (canCastToApiClient(API_2)) {
2514         apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2515     }
2516     // Transition device state to OPEN
2517     sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
2518             mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
2519 
2520     sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
2521 
2522     // Notify listeners of camera open/close status
2523     sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
2524 
2525     return OK;
2526 }
2527 
finishCameraOps()2528 status_t CameraService::BasicClient::finishCameraOps() {
2529     ATRACE_CALL();
2530 
2531     // Check if startCameraOps succeeded, and if so, finish the camera op
2532     if (mOpsActive) {
2533         // Notify app ops that the camera is available again
2534         if (mAppOpsManager != nullptr) {
2535             mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
2536                     mClientPackageName);
2537             mOpsActive = false;
2538         }
2539         // This function is called when a client disconnects. This should
2540         // release the camera, but actually only if it was in a proper
2541         // functional state, i.e. with status NOT_AVAILABLE
2542         std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
2543                 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
2544 
2545         // Transition to PRESENT if the camera is not in either of the rejected states
2546         sCameraService->updateStatus(StatusInternal::PRESENT,
2547                 mCameraIdStr, rejected);
2548 
2549         int apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_1;
2550         if (canCastToApiClient(API_2)) {
2551             apiLevel = hardware::ICameraServiceProxy::CAMERA_API_LEVEL_2;
2552         }
2553         // Transition device state to CLOSED
2554         sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
2555                 mCameraIdStr, mCameraFacing, mClientPackageName, apiLevel);
2556     }
2557     // Always stop watching, even if no camera op is active
2558     if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
2559         mAppOpsManager->stopWatchingMode(mOpsCallback);
2560     }
2561     mOpsCallback.clear();
2562 
2563     sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
2564 
2565     // Notify listeners of camera open/close status
2566     sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
2567 
2568     return OK;
2569 }
2570 
opChanged(int32_t op,const String16 &)2571 void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
2572     ATRACE_CALL();
2573     if (mAppOpsManager == nullptr) {
2574         return;
2575     }
2576     if (op != AppOpsManager::OP_CAMERA) {
2577         ALOGW("Unexpected app ops notification received: %d", op);
2578         return;
2579     }
2580 
2581     int32_t res;
2582     res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
2583             mClientUid, mClientPackageName);
2584     ALOGV("checkOp returns: %d, %s ", res,
2585             res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2586             res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2587             res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2588             "UNKNOWN");
2589 
2590     if (res != AppOpsManager::MODE_ALLOWED) {
2591         ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
2592               String8(mClientPackageName).string());
2593         block();
2594     }
2595 }
2596 
block()2597 void CameraService::BasicClient::block() {
2598     ATRACE_CALL();
2599 
2600     // Reset the client PID to allow server-initiated disconnect,
2601     // and to prevent further calls by client.
2602     mClientPid = CameraThreadState::getCallingPid();
2603     CaptureResultExtras resultExtras; // a dummy result (invalid)
2604     notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
2605     disconnect();
2606 }
2607 
2608 // ----------------------------------------------------------------------------
2609 
notifyError(int32_t errorCode,const CaptureResultExtras & resultExtras)2610 void CameraService::Client::notifyError(int32_t errorCode,
2611         const CaptureResultExtras& resultExtras) {
2612     (void) resultExtras;
2613     if (mRemoteCallback != NULL) {
2614         int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
2615         if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
2616             api1ErrorCode = CAMERA_ERROR_DISABLED;
2617         }
2618         mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
2619     } else {
2620         ALOGE("mRemoteCallback is NULL!!");
2621     }
2622 }
2623 
2624 // NOTE: function is idempotent
disconnect()2625 binder::Status CameraService::Client::disconnect() {
2626     ALOGV("Client::disconnect");
2627     return BasicClient::disconnect();
2628 }
2629 
canCastToApiClient(apiLevel level) const2630 bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2631     return level == API_1;
2632 }
2633 
OpsCallback(wp<BasicClient> client)2634 CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2635         mClient(client) {
2636 }
2637 
opChanged(int32_t op,const String16 & packageName)2638 void CameraService::Client::OpsCallback::opChanged(int32_t op,
2639         const String16& packageName) {
2640     sp<BasicClient> client = mClient.promote();
2641     if (client != NULL) {
2642         client->opChanged(op, packageName);
2643     }
2644 }
2645 
2646 // ----------------------------------------------------------------------------
2647 //                  UidPolicy
2648 // ----------------------------------------------------------------------------
2649 
registerSelf()2650 void CameraService::UidPolicy::registerSelf() {
2651     Mutex::Autolock _l(mUidLock);
2652 
2653     if (mRegistered) return;
2654     status_t res = mAm.linkToDeath(this);
2655     mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
2656             | ActivityManager::UID_OBSERVER_IDLE
2657             | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
2658             ActivityManager::PROCESS_STATE_UNKNOWN,
2659             String16("cameraserver"));
2660     if (res == OK) {
2661         mRegistered = true;
2662         ALOGV("UidPolicy: Registered with ActivityManager");
2663     }
2664 }
2665 
unregisterSelf()2666 void CameraService::UidPolicy::unregisterSelf() {
2667     Mutex::Autolock _l(mUidLock);
2668 
2669     mAm.unregisterUidObserver(this);
2670     mAm.unlinkToDeath(this);
2671     mRegistered = false;
2672     mActiveUids.clear();
2673     ALOGV("UidPolicy: Unregistered with ActivityManager");
2674 }
2675 
onUidGone(uid_t uid,bool disabled)2676 void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
2677     onUidIdle(uid, disabled);
2678 }
2679 
onUidActive(uid_t uid)2680 void CameraService::UidPolicy::onUidActive(uid_t uid) {
2681     Mutex::Autolock _l(mUidLock);
2682     mActiveUids.insert(uid);
2683 }
2684 
onUidIdle(uid_t uid,bool)2685 void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
2686     bool deleted = false;
2687     {
2688         Mutex::Autolock _l(mUidLock);
2689         if (mActiveUids.erase(uid) > 0) {
2690             deleted = true;
2691         }
2692     }
2693     if (deleted) {
2694         sp<CameraService> service = mService.promote();
2695         if (service != nullptr) {
2696             service->blockClientsForUid(uid);
2697         }
2698     }
2699 }
2700 
onUidStateChanged(uid_t uid,int32_t procState,int64_t)2701 void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
2702         int64_t /*procStateSeq*/) {
2703     bool procStateChange = false;
2704     {
2705         Mutex::Autolock _l(mUidLock);
2706         if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
2707                 (mMonitoredUids[uid].first != procState)) {
2708             mMonitoredUids[uid].first = procState;
2709             procStateChange = true;
2710         }
2711     }
2712 
2713     if (procStateChange) {
2714         sp<CameraService> service = mService.promote();
2715         if (service != nullptr) {
2716             service->notifyMonitoredUids();
2717         }
2718     }
2719 }
2720 
registerMonitorUid(uid_t uid)2721 void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
2722     Mutex::Autolock _l(mUidLock);
2723     auto it = mMonitoredUids.find(uid);
2724     if (it != mMonitoredUids.end()) {
2725         it->second.second++;
2726     } else {
2727         mMonitoredUids.emplace(
2728                 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
2729                     std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
2730     }
2731 }
2732 
unregisterMonitorUid(uid_t uid)2733 void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
2734     Mutex::Autolock _l(mUidLock);
2735     auto it = mMonitoredUids.find(uid);
2736     if (it != mMonitoredUids.end()) {
2737         it->second.second--;
2738         if (it->second.second == 0) {
2739             mMonitoredUids.erase(it);
2740         }
2741     } else {
2742         ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
2743     }
2744 }
2745 
isUidActive(uid_t uid,String16 callingPackage)2746 bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
2747     Mutex::Autolock _l(mUidLock);
2748     return isUidActiveLocked(uid, callingPackage);
2749 }
2750 
2751 static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
2752 static const int64_t kPollUidActiveTimeoutMillis = 50;
2753 
isUidActiveLocked(uid_t uid,String16 callingPackage)2754 bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
2755     // Non-app UIDs are considered always active
2756     // If activity manager is unreachable, assume everything is active
2757     if (uid < FIRST_APPLICATION_UID || !mRegistered) {
2758         return true;
2759     }
2760     auto it = mOverrideUids.find(uid);
2761     if (it != mOverrideUids.end()) {
2762         return it->second;
2763     }
2764     bool active = mActiveUids.find(uid) != mActiveUids.end();
2765     if (!active) {
2766         // We want active UIDs to always access camera with their first attempt since
2767         // there is no guarantee the app is robustly written and would retry getting
2768         // the camera on failure. The inverse case is not a problem as we would take
2769         // camera away soon once we get the callback that the uid is no longer active.
2770         ActivityManager am;
2771         // Okay to access with a lock held as UID changes are dispatched without
2772         // a lock and we are a higher level component.
2773         int64_t startTimeMillis = 0;
2774         do {
2775             // TODO: Fix this b/109950150!
2776             // Okay this is a hack. There is a race between the UID turning active and
2777             // activity being resumed. The proper fix is very risky, so we temporary add
2778             // some polling which should happen pretty rarely anyway as the race is hard
2779             // to hit.
2780             active = mActiveUids.find(uid) != mActiveUids.end();
2781             if (!active) active = am.isUidActive(uid, callingPackage);
2782             if (active) {
2783                 break;
2784             }
2785             if (startTimeMillis <= 0) {
2786                 startTimeMillis = uptimeMillis();
2787             }
2788             int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
2789             int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
2790             if (remainingTimeMillis <= 0) {
2791                 break;
2792             }
2793             remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
2794 
2795             mUidLock.unlock();
2796             usleep(remainingTimeMillis * 1000);
2797             mUidLock.lock();
2798         } while (true);
2799 
2800         if (active) {
2801             // Now that we found out the UID is actually active, cache that
2802             mActiveUids.insert(uid);
2803         }
2804     }
2805     return active;
2806 }
2807 
getProcState(uid_t uid)2808 int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
2809     Mutex::Autolock _l(mUidLock);
2810     return getProcStateLocked(uid);
2811 }
2812 
getProcStateLocked(uid_t uid)2813 int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
2814     int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
2815     if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
2816         procState = mMonitoredUids[uid].first;
2817     }
2818     return procState;
2819 }
2820 
addOverrideUid(uid_t uid,String16 callingPackage,bool active)2821 void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
2822         String16 callingPackage, bool active) {
2823     updateOverrideUid(uid, callingPackage, active, true);
2824 }
2825 
removeOverrideUid(uid_t uid,String16 callingPackage)2826 void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
2827     updateOverrideUid(uid, callingPackage, false, false);
2828 }
2829 
binderDied(const wp<IBinder> &)2830 void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
2831     Mutex::Autolock _l(mUidLock);
2832     ALOGV("UidPolicy: ActivityManager has died");
2833     mRegistered = false;
2834     mActiveUids.clear();
2835 }
2836 
updateOverrideUid(uid_t uid,String16 callingPackage,bool active,bool insert)2837 void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
2838         bool active, bool insert) {
2839     bool wasActive = false;
2840     bool isActive = false;
2841     {
2842         Mutex::Autolock _l(mUidLock);
2843         wasActive = isUidActiveLocked(uid, callingPackage);
2844         mOverrideUids.erase(uid);
2845         if (insert) {
2846             mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
2847         }
2848         isActive = isUidActiveLocked(uid, callingPackage);
2849     }
2850     if (wasActive != isActive && !isActive) {
2851         sp<CameraService> service = mService.promote();
2852         if (service != nullptr) {
2853             service->blockClientsForUid(uid);
2854         }
2855     }
2856 }
2857 
2858 // ----------------------------------------------------------------------------
2859 //                  SensorPrivacyPolicy
2860 // ----------------------------------------------------------------------------
registerSelf()2861 void CameraService::SensorPrivacyPolicy::registerSelf() {
2862     Mutex::Autolock _l(mSensorPrivacyLock);
2863     if (mRegistered) {
2864         return;
2865     }
2866     mSpm.addSensorPrivacyListener(this);
2867     mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
2868     status_t res = mSpm.linkToDeath(this);
2869     if (res == OK) {
2870         mRegistered = true;
2871         ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
2872     }
2873 }
2874 
unregisterSelf()2875 void CameraService::SensorPrivacyPolicy::unregisterSelf() {
2876     Mutex::Autolock _l(mSensorPrivacyLock);
2877     mSpm.removeSensorPrivacyListener(this);
2878     mSpm.unlinkToDeath(this);
2879     mRegistered = false;
2880     ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
2881 }
2882 
isSensorPrivacyEnabled()2883 bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
2884     Mutex::Autolock _l(mSensorPrivacyLock);
2885     return mSensorPrivacyEnabled;
2886 }
2887 
onSensorPrivacyChanged(bool enabled)2888 binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
2889     {
2890         Mutex::Autolock _l(mSensorPrivacyLock);
2891         mSensorPrivacyEnabled = enabled;
2892     }
2893     // if sensor privacy is enabled then block all clients from accessing the camera
2894     if (enabled) {
2895         sp<CameraService> service = mService.promote();
2896         if (service != nullptr) {
2897             service->blockAllClients();
2898         }
2899     }
2900     return binder::Status::ok();
2901 }
2902 
binderDied(const wp<IBinder> &)2903 void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
2904     Mutex::Autolock _l(mSensorPrivacyLock);
2905     ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
2906     mRegistered = false;
2907 }
2908 
2909 // ----------------------------------------------------------------------------
2910 //                  CameraState
2911 // ----------------------------------------------------------------------------
2912 
CameraState(const String8 & id,int cost,const std::set<String8> & conflicting,bool isHidden)2913 CameraService::CameraState::CameraState(const String8& id, int cost,
2914         const std::set<String8>& conflicting, bool isHidden) : mId(id),
2915         mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
2916         mIsPublicallyHiddenSecureCamera(isHidden) {}
2917 
~CameraState()2918 CameraService::CameraState::~CameraState() {}
2919 
getStatus() const2920 CameraService::StatusInternal CameraService::CameraState::getStatus() const {
2921     Mutex::Autolock lock(mStatusLock);
2922     return mStatus;
2923 }
2924 
getShimParams() const2925 CameraParameters CameraService::CameraState::getShimParams() const {
2926     return mShimParams;
2927 }
2928 
setShimParams(const CameraParameters & params)2929 void CameraService::CameraState::setShimParams(const CameraParameters& params) {
2930     mShimParams = params;
2931 }
2932 
getCost() const2933 int CameraService::CameraState::getCost() const {
2934     return mCost;
2935 }
2936 
getConflicting() const2937 std::set<String8> CameraService::CameraState::getConflicting() const {
2938     return mConflicting;
2939 }
2940 
getId() const2941 String8 CameraService::CameraState::getId() const {
2942     return mId;
2943 }
2944 
isPublicallyHiddenSecureCamera() const2945 bool CameraService::CameraState::isPublicallyHiddenSecureCamera() const {
2946     return mIsPublicallyHiddenSecureCamera;
2947 }
2948 
2949 // ----------------------------------------------------------------------------
2950 //                  ClientEventListener
2951 // ----------------------------------------------------------------------------
2952 
onClientAdded(const resource_policy::ClientDescriptor<String8,sp<CameraService::BasicClient>> & descriptor)2953 void CameraService::ClientEventListener::onClientAdded(
2954         const resource_policy::ClientDescriptor<String8,
2955         sp<CameraService::BasicClient>>& descriptor) {
2956     const auto& basicClient = descriptor.getValue();
2957     if (basicClient.get() != nullptr) {
2958         BatteryNotifier& notifier(BatteryNotifier::getInstance());
2959         notifier.noteStartCamera(descriptor.getKey(),
2960                 static_cast<int>(basicClient->getClientUid()));
2961     }
2962 }
2963 
onClientRemoved(const resource_policy::ClientDescriptor<String8,sp<CameraService::BasicClient>> & descriptor)2964 void CameraService::ClientEventListener::onClientRemoved(
2965         const resource_policy::ClientDescriptor<String8,
2966         sp<CameraService::BasicClient>>& descriptor) {
2967     const auto& basicClient = descriptor.getValue();
2968     if (basicClient.get() != nullptr) {
2969         BatteryNotifier& notifier(BatteryNotifier::getInstance());
2970         notifier.noteStopCamera(descriptor.getKey(),
2971                 static_cast<int>(basicClient->getClientUid()));
2972     }
2973 }
2974 
2975 
2976 // ----------------------------------------------------------------------------
2977 //                  CameraClientManager
2978 // ----------------------------------------------------------------------------
2979 
CameraClientManager()2980 CameraService::CameraClientManager::CameraClientManager() {
2981     setListener(std::make_shared<ClientEventListener>());
2982 }
2983 
~CameraClientManager()2984 CameraService::CameraClientManager::~CameraClientManager() {}
2985 
getCameraClient(const String8 & id) const2986 sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
2987         const String8& id) const {
2988     auto descriptor = get(id);
2989     if (descriptor == nullptr) {
2990         return sp<BasicClient>{nullptr};
2991     }
2992     return descriptor->getValue();
2993 }
2994 
toString() const2995 String8 CameraService::CameraClientManager::toString() const {
2996     auto all = getAll();
2997     String8 ret("[");
2998     bool hasAny = false;
2999     for (auto& i : all) {
3000         hasAny = true;
3001         String8 key = i->getKey();
3002         int32_t cost = i->getCost();
3003         int32_t pid = i->getOwnerId();
3004         int32_t score = i->getPriority().getScore();
3005         int32_t state = i->getPriority().getState();
3006         auto conflicting = i->getConflicting();
3007         auto clientSp = i->getValue();
3008         String8 packageName;
3009         userid_t clientUserId = 0;
3010         if (clientSp.get() != nullptr) {
3011             packageName = String8{clientSp->getPackageName()};
3012             uid_t clientUid = clientSp->getClientUid();
3013             clientUserId = multiuser_get_user_id(clientUid);
3014         }
3015         ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3016                 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
3017 
3018         if (clientSp.get() != nullptr) {
3019             ret.appendFormat("User Id: %d, ", clientUserId);
3020         }
3021         if (packageName.size() != 0) {
3022             ret.appendFormat("Client Package Name: %s", packageName.string());
3023         }
3024 
3025         ret.append(", Conflicting Client Devices: {");
3026         for (auto& j : conflicting) {
3027             ret.appendFormat("%s, ", j.string());
3028         }
3029         ret.append("})");
3030     }
3031     if (hasAny) ret.append("\n");
3032     ret.append("]\n");
3033     return ret;
3034 }
3035 
makeClientDescriptor(const String8 & key,const sp<BasicClient> & value,int32_t cost,const std::set<String8> & conflictingKeys,int32_t score,int32_t ownerId,int32_t state)3036 CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3037         const String8& key, const sp<BasicClient>& value, int32_t cost,
3038         const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
3039         int32_t state) {
3040 
3041     bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
3042     int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3043     int32_t state_adj = isVendorClient ? kVendorClientState: state;
3044 
3045     return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
3046             key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient);
3047 }
3048 
makeClientDescriptor(const sp<BasicClient> & value,const CameraService::DescriptorPtr & partial)3049 CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3050         const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
3051     return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
3052             partial->getConflicting(), partial->getPriority().getScore(),
3053             partial->getOwnerId(), partial->getPriority().getState());
3054 }
3055 
3056 // ----------------------------------------------------------------------------
3057 
3058 static const int kDumpLockRetries = 50;
3059 static const int kDumpLockSleep = 60000;
3060 
tryLock(Mutex & mutex)3061 static bool tryLock(Mutex& mutex)
3062 {
3063     bool locked = false;
3064     for (int i = 0; i < kDumpLockRetries; ++i) {
3065         if (mutex.tryLock() == NO_ERROR) {
3066             locked = true;
3067             break;
3068         }
3069         usleep(kDumpLockSleep);
3070     }
3071     return locked;
3072 }
3073 
dump(int fd,const Vector<String16> & args)3074 status_t CameraService::dump(int fd, const Vector<String16>& args) {
3075     ATRACE_CALL();
3076 
3077     if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
3078         dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
3079                 CameraThreadState::getCallingPid(),
3080                 CameraThreadState::getCallingUid());
3081         return NO_ERROR;
3082     }
3083     bool locked = tryLock(mServiceLock);
3084     // failed to lock - CameraService is probably deadlocked
3085     if (!locked) {
3086         dprintf(fd, "!! CameraService may be deadlocked !!\n");
3087     }
3088 
3089     if (!mInitialized) {
3090         dprintf(fd, "!! No camera HAL available !!\n");
3091 
3092         // Dump event log for error information
3093         dumpEventLog(fd);
3094 
3095         if (locked) mServiceLock.unlock();
3096         return NO_ERROR;
3097     }
3098     dprintf(fd, "\n== Service global info: ==\n\n");
3099     dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
3100     dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
3101     for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
3102         dprintf(fd, "    Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
3103     }
3104     String8 activeClientString = mActiveClientManager.toString();
3105     dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
3106     dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
3107 
3108     dumpEventLog(fd);
3109 
3110     bool stateLocked = tryLock(mCameraStatesLock);
3111     if (!stateLocked) {
3112         dprintf(fd, "CameraStates in use, may be deadlocked\n");
3113     }
3114 
3115     int argSize = args.size();
3116     for (int i = 0; i < argSize; i++) {
3117         if (args[i] == TagMonitor::kMonitorOption) {
3118             if (i + 1 < argSize) {
3119                 mMonitorTags = String8(args[i + 1]);
3120             }
3121             break;
3122         }
3123     }
3124 
3125     for (auto& state : mCameraStates) {
3126         String8 cameraId = state.first;
3127 
3128         dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
3129 
3130         CameraParameters p = state.second->getShimParams();
3131         if (!p.isEmpty()) {
3132             dprintf(fd, "  Camera1 API shim is using parameters:\n        ");
3133             p.dump(fd, args);
3134         }
3135 
3136         auto clientDescriptor = mActiveClientManager.get(cameraId);
3137         if (clientDescriptor != nullptr) {
3138             dprintf(fd, "  Device %s is open. Client instance dump:\n",
3139                     cameraId.string());
3140             dprintf(fd, "    Client priority score: %d state: %d\n",
3141                     clientDescriptor->getPriority().getScore(),
3142                     clientDescriptor->getPriority().getState());
3143             dprintf(fd, "    Client PID: %d\n", clientDescriptor->getOwnerId());
3144 
3145             auto client = clientDescriptor->getValue();
3146             dprintf(fd, "    Client package: %s\n",
3147                     String8(client->getPackageName()).string());
3148 
3149             client->dumpClient(fd, args);
3150         } else {
3151             dprintf(fd, "  Device %s is closed, no client instance\n",
3152                     cameraId.string());
3153         }
3154 
3155     }
3156 
3157     if (stateLocked) mCameraStatesLock.unlock();
3158 
3159     if (locked) mServiceLock.unlock();
3160 
3161     mCameraProviderManager->dump(fd, args);
3162 
3163     dprintf(fd, "\n== Vendor tags: ==\n\n");
3164 
3165     sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
3166     if (desc == NULL) {
3167         sp<VendorTagDescriptorCache> cache =
3168                 VendorTagDescriptorCache::getGlobalVendorTagCache();
3169         if (cache == NULL) {
3170             dprintf(fd, "No vendor tags.\n");
3171         } else {
3172             cache->dump(fd, /*verbosity*/2, /*indentation*/2);
3173         }
3174     } else {
3175         desc->dump(fd, /*verbosity*/2, /*indentation*/2);
3176     }
3177 
3178     // Dump camera traces if there were any
3179     dprintf(fd, "\n");
3180     camera3::CameraTraces::dump(fd, args);
3181 
3182     // Process dump arguments, if any
3183     int n = args.size();
3184     String16 verboseOption("-v");
3185     String16 unreachableOption("--unreachable");
3186     for (int i = 0; i < n; i++) {
3187         if (args[i] == verboseOption) {
3188             // change logging level
3189             if (i + 1 >= n) continue;
3190             String8 levelStr(args[i+1]);
3191             int level = atoi(levelStr.string());
3192             dprintf(fd, "\nSetting log level to %d.\n", level);
3193             setLogLevel(level);
3194         } else if (args[i] == unreachableOption) {
3195             // Dump memory analysis
3196             // TODO - should limit be an argument parameter?
3197             UnreachableMemoryInfo info;
3198             bool success = GetUnreachableMemory(info, /*limit*/ 10000);
3199             if (!success) {
3200                 dprintf(fd, "\n== Unable to dump unreachable memory. "
3201                         "Try disabling SELinux enforcement. ==\n");
3202             } else {
3203                 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
3204                 std::string s = info.ToString(/*log_contents*/ true);
3205                 write(fd, s.c_str(), s.size());
3206             }
3207         }
3208     }
3209     return NO_ERROR;
3210 }
3211 
dumpEventLog(int fd)3212 void CameraService::dumpEventLog(int fd) {
3213     dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
3214 
3215     Mutex::Autolock l(mLogLock);
3216     for (const auto& msg : mEventLog) {
3217         dprintf(fd, "  %s\n", msg.string());
3218     }
3219 
3220     if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
3221         dprintf(fd, "  ...\n");
3222     } else if (mEventLog.size() == 0) {
3223         dprintf(fd, "  [no events yet]\n");
3224     }
3225     dprintf(fd, "\n");
3226 }
3227 
handleTorchClientBinderDied(const wp<IBinder> & who)3228 void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
3229     Mutex::Autolock al(mTorchClientMapMutex);
3230     for (size_t i = 0; i < mTorchClientMap.size(); i++) {
3231         if (mTorchClientMap[i] == who) {
3232             // turn off the torch mode that was turned on by dead client
3233             String8 cameraId = mTorchClientMap.keyAt(i);
3234             status_t res = mFlashlight->setTorchMode(cameraId, false);
3235             if (res) {
3236                 ALOGE("%s: torch client died but couldn't turn off torch: "
3237                     "%s (%d)", __FUNCTION__, strerror(-res), res);
3238                 return;
3239             }
3240             mTorchClientMap.removeItemsAt(i);
3241             break;
3242         }
3243     }
3244 }
3245 
binderDied(const wp<IBinder> & who)3246 /*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
3247 
3248     /**
3249       * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
3250       * binder driver
3251       */
3252     // PID here is approximate and can be wrong.
3253     logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
3254 
3255     // check torch client
3256     handleTorchClientBinderDied(who);
3257 
3258     // check camera device client
3259     if(!evictClientIdByRemote(who)) {
3260         ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
3261         return;
3262     }
3263 
3264     ALOGE("%s: Java client's binder died, removing it from the list of active clients",
3265             __FUNCTION__);
3266 }
3267 
updateStatus(StatusInternal status,const String8 & cameraId)3268 void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
3269     updateStatus(status, cameraId, {});
3270 }
3271 
updateStatus(StatusInternal status,const String8 & cameraId,std::initializer_list<StatusInternal> rejectSourceStates)3272 void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
3273         std::initializer_list<StatusInternal> rejectSourceStates) {
3274     // Do not lock mServiceLock here or can get into a deadlock from
3275     // connect() -> disconnect -> updateStatus
3276 
3277     auto state = getCameraState(cameraId);
3278 
3279     if (state == nullptr) {
3280         ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
3281                 cameraId.string());
3282         return;
3283     }
3284     bool isHidden = isPublicallyHiddenSecureCamera(cameraId);
3285     bool supportsHAL3 = false;
3286     // supportsCameraApi also holds mInterfaceMutex, we can't call it in the
3287     // HIDL onStatusChanged wrapper call (we'll hold mStatusListenerLock and
3288     // mInterfaceMutex together, which can lead to deadlocks)
3289     binder::Status sRet =
3290             supportsCameraApi(String16(cameraId), hardware::ICameraService::API_VERSION_2,
3291                     &supportsHAL3);
3292     if (!sRet.isOk()) {
3293         ALOGW("%s: Failed to determine if device supports HAL3 %s, supportsCameraApi call failed",
3294                 __FUNCTION__, cameraId.string());
3295         return;
3296     }
3297     // Update the status for this camera state, then send the onStatusChangedCallbacks to each
3298     // of the listeners with both the mStatusStatus and mStatusListenerLock held
3299     state->updateStatus(status, cameraId, rejectSourceStates, [this, &isHidden, &supportsHAL3]
3300             (const String8& cameraId, StatusInternal status) {
3301 
3302             if (status != StatusInternal::ENUMERATING) {
3303                 // Update torch status if it has a flash unit.
3304                 Mutex::Autolock al(mTorchStatusMutex);
3305                 TorchModeStatus torchStatus;
3306                 if (getTorchStatusLocked(cameraId, &torchStatus) !=
3307                         NAME_NOT_FOUND) {
3308                     TorchModeStatus newTorchStatus =
3309                             status == StatusInternal::PRESENT ?
3310                             TorchModeStatus::AVAILABLE_OFF :
3311                             TorchModeStatus::NOT_AVAILABLE;
3312                     if (torchStatus != newTorchStatus) {
3313                         onTorchStatusChangedLocked(cameraId, newTorchStatus);
3314                     }
3315                 }
3316             }
3317 
3318             Mutex::Autolock lock(mStatusListenerLock);
3319 
3320             for (auto& listener : mListenerList) {
3321                 bool isVendorListener = listener.first;
3322                 if (isVendorListener && !supportsHAL3) {
3323                     ALOGV("Skipping vendor listener camera discovery callback for  HAL1 camera %s",
3324                             cameraId.c_str());
3325                     continue;
3326                 }
3327 
3328                 if (!isVendorListener && isHidden) {
3329                     ALOGV("Skipping camera discovery callback for system-only camera %s",
3330                           cameraId.c_str());
3331                     continue;
3332                 }
3333                 listener.second->getListener()->onStatusChanged(mapToInterface(status),
3334                         String16(cameraId));
3335             }
3336         });
3337 }
3338 
updateOpenCloseStatus(const String8 & cameraId,bool open,const String16 & clientPackageName)3339 void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
3340         const String16& clientPackageName) {
3341     Mutex::Autolock lock(mStatusListenerLock);
3342 
3343     for (const auto& it : mListenerList) {
3344         if (!it.second->isOpenCloseCallbackAllowed()) {
3345             continue;
3346         }
3347 
3348         binder::Status ret;
3349         String16 cameraId64(cameraId);
3350         if (open) {
3351             ret = it.second->getListener()->onCameraOpened(cameraId64, clientPackageName);
3352         } else {
3353             ret = it.second->getListener()->onCameraClosed(cameraId64);
3354         }
3355         if (!ret.isOk()) {
3356             ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
3357                     ret.exceptionCode());
3358         }
3359     }
3360 }
3361 
3362 template<class Func>
updateStatus(StatusInternal status,const String8 & cameraId,std::initializer_list<StatusInternal> rejectSourceStates,Func onStatusUpdatedLocked)3363 void CameraService::CameraState::updateStatus(StatusInternal status,
3364         const String8& cameraId,
3365         std::initializer_list<StatusInternal> rejectSourceStates,
3366         Func onStatusUpdatedLocked) {
3367     Mutex::Autolock lock(mStatusLock);
3368     StatusInternal oldStatus = mStatus;
3369     mStatus = status;
3370 
3371     if (oldStatus == status) {
3372         return;
3373     }
3374 
3375     ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
3376             cameraId.string(), oldStatus, status);
3377 
3378     if (oldStatus == StatusInternal::NOT_PRESENT &&
3379             (status != StatusInternal::PRESENT &&
3380              status != StatusInternal::ENUMERATING)) {
3381 
3382         ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
3383                 __FUNCTION__);
3384         mStatus = oldStatus;
3385         return;
3386     }
3387 
3388     /**
3389      * Sometimes we want to conditionally do a transition.
3390      * For example if a client disconnects, we want to go to PRESENT
3391      * only if we weren't already in NOT_PRESENT or ENUMERATING.
3392      */
3393     for (auto& rejectStatus : rejectSourceStates) {
3394         if (oldStatus == rejectStatus) {
3395             ALOGV("%s: Rejecting status transition for Camera ID %s,  since the source "
3396                     "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
3397             mStatus = oldStatus;
3398             return;
3399         }
3400     }
3401 
3402     onStatusUpdatedLocked(cameraId, status);
3403 }
3404 
updateProxyDeviceState(int newState,const String8 & cameraId,int facing,const String16 & clientName,int apiLevel)3405 void CameraService::updateProxyDeviceState(int newState,
3406         const String8& cameraId, int facing, const String16& clientName, int apiLevel) {
3407     sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
3408     if (proxyBinder == nullptr) return;
3409     String16 id(cameraId);
3410     proxyBinder->notifyCameraState(id, newState, facing, clientName, apiLevel);
3411 }
3412 
getTorchStatusLocked(const String8 & cameraId,TorchModeStatus * status) const3413 status_t CameraService::getTorchStatusLocked(
3414         const String8& cameraId,
3415         TorchModeStatus *status) const {
3416     if (!status) {
3417         return BAD_VALUE;
3418     }
3419     ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3420     if (index == NAME_NOT_FOUND) {
3421         // invalid camera ID or the camera doesn't have a flash unit
3422         return NAME_NOT_FOUND;
3423     }
3424 
3425     *status = mTorchStatusMap.valueAt(index);
3426     return OK;
3427 }
3428 
setTorchStatusLocked(const String8 & cameraId,TorchModeStatus status)3429 status_t CameraService::setTorchStatusLocked(const String8& cameraId,
3430         TorchModeStatus status) {
3431     ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
3432     if (index == NAME_NOT_FOUND) {
3433         return BAD_VALUE;
3434     }
3435     mTorchStatusMap.editValueAt(index) = status;
3436 
3437     return OK;
3438 }
3439 
blockClientsForUid(uid_t uid)3440 void CameraService::blockClientsForUid(uid_t uid) {
3441     const auto clients = mActiveClientManager.getAll();
3442     for (auto& current : clients) {
3443         if (current != nullptr) {
3444             const auto basicClient = current->getValue();
3445             if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
3446                 basicClient->block();
3447             }
3448         }
3449     }
3450 }
3451 
blockAllClients()3452 void CameraService::blockAllClients() {
3453     const auto clients = mActiveClientManager.getAll();
3454     for (auto& current : clients) {
3455         if (current != nullptr) {
3456             const auto basicClient = current->getValue();
3457             if (basicClient.get() != nullptr) {
3458                 basicClient->block();
3459             }
3460         }
3461     }
3462 }
3463 
3464 // NOTE: This is a remote API - make sure all args are validated
shellCommand(int in,int out,int err,const Vector<String16> & args)3465 status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
3466     if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
3467         return PERMISSION_DENIED;
3468     }
3469     if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
3470         return BAD_VALUE;
3471     }
3472     if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
3473         return handleSetUidState(args, err);
3474     } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
3475         return handleResetUidState(args, err);
3476     } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
3477         return handleGetUidState(args, out, err);
3478     } else if (args.size() == 1 && args[0] == String16("help")) {
3479         printHelp(out);
3480         return NO_ERROR;
3481     }
3482     printHelp(err);
3483     return BAD_VALUE;
3484 }
3485 
handleSetUidState(const Vector<String16> & args,int err)3486 status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
3487     String16 packageName = args[1];
3488 
3489     bool active = false;
3490     if (args[2] == String16("active")) {
3491         active = true;
3492     } else if ((args[2] != String16("idle"))) {
3493         ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
3494         return BAD_VALUE;
3495     }
3496 
3497     int userId = 0;
3498     if (args.size() >= 5 && args[3] == String16("--user")) {
3499         userId = atoi(String8(args[4]));
3500     }
3501 
3502     uid_t uid;
3503     if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
3504         return BAD_VALUE;
3505     }
3506 
3507     mUidPolicy->addOverrideUid(uid, packageName, active);
3508     return NO_ERROR;
3509 }
3510 
handleResetUidState(const Vector<String16> & args,int err)3511 status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
3512     String16 packageName = args[1];
3513 
3514     int userId = 0;
3515     if (args.size() >= 4 && args[2] == String16("--user")) {
3516         userId = atoi(String8(args[3]));
3517     }
3518 
3519     uid_t uid;
3520     if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
3521         return BAD_VALUE;
3522     }
3523 
3524     mUidPolicy->removeOverrideUid(uid, packageName);
3525     return NO_ERROR;
3526 }
3527 
handleGetUidState(const Vector<String16> & args,int out,int err)3528 status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
3529     String16 packageName = args[1];
3530 
3531     int userId = 0;
3532     if (args.size() >= 4 && args[2] == String16("--user")) {
3533         userId = atoi(String8(args[3]));
3534     }
3535 
3536     uid_t uid;
3537     if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
3538         return BAD_VALUE;
3539     }
3540 
3541     if (mUidPolicy->isUidActive(uid, packageName)) {
3542         return dprintf(out, "active\n");
3543     } else {
3544         return dprintf(out, "idle\n");
3545     }
3546 }
3547 
printHelp(int out)3548 status_t CameraService::printHelp(int out) {
3549     return dprintf(out, "Camera service commands:\n"
3550         "  get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
3551         "  set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
3552         "  reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
3553         "  help print this message\n");
3554 }
3555 
3556 }; // namespace android
3557